blob: 19dffac5f38314f8838d403d3fd5be125873d6dd [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;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002677 }
Kelvin Libf594a52016-12-17 05:48:59 +00002678 if (!NestingProhibited &&
2679 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2680 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2681 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002682 // OpenMP [2.16, Nesting of Regions]
2683 // distribute, parallel, parallel sections, parallel workshare, and the
2684 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2685 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002686 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2687 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002688 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002689 }
David Majnemer9d168222016-08-05 17:44:54 +00002690 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002691 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002692 // OpenMP 4.5 [2.17 Nesting of Regions]
2693 // The region associated with the distribute construct must be strictly
2694 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002695 NestingProhibited =
2696 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002697 Recommend = ShouldBeInTeamsRegion;
2698 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002699 if (!NestingProhibited &&
2700 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2701 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2702 // OpenMP 4.5 [2.17 Nesting of Regions]
2703 // If a target, target update, target data, target enter data, or
2704 // target exit data construct is encountered during execution of a
2705 // target region, the behavior is unspecified.
2706 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002707 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2708 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002709 if (isOpenMPTargetExecutionDirective(K)) {
2710 OffendingRegion = K;
2711 return true;
2712 } else
2713 return false;
2714 },
2715 false /* don't skip top directive */);
2716 CloseNesting = false;
2717 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002718 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002719 if (OrphanSeen) {
2720 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2721 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2722 } else {
2723 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2724 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2725 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2726 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002727 return true;
2728 }
2729 }
2730 return false;
2731}
2732
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002733static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2734 ArrayRef<OMPClause *> Clauses,
2735 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2736 bool ErrorFound = false;
2737 unsigned NamedModifiersNumber = 0;
2738 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2739 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002740 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002741 for (const auto *C : Clauses) {
2742 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2743 // At most one if clause without a directive-name-modifier can appear on
2744 // the directive.
2745 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2746 if (FoundNameModifiers[CurNM]) {
2747 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2748 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2749 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2750 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002751 } else if (CurNM != OMPD_unknown) {
2752 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002753 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002754 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002755 FoundNameModifiers[CurNM] = IC;
2756 if (CurNM == OMPD_unknown)
2757 continue;
2758 // Check if the specified name modifier is allowed for the current
2759 // directive.
2760 // At most one if clause with the particular directive-name-modifier can
2761 // appear on the directive.
2762 bool MatchFound = false;
2763 for (auto NM : AllowedNameModifiers) {
2764 if (CurNM == NM) {
2765 MatchFound = true;
2766 break;
2767 }
2768 }
2769 if (!MatchFound) {
2770 S.Diag(IC->getNameModifierLoc(),
2771 diag::err_omp_wrong_if_directive_name_modifier)
2772 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2773 ErrorFound = true;
2774 }
2775 }
2776 }
2777 // If any if clause on the directive includes a directive-name-modifier then
2778 // all if clauses on the directive must include a directive-name-modifier.
2779 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2780 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2781 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2782 diag::err_omp_no_more_if_clause);
2783 } else {
2784 std::string Values;
2785 std::string Sep(", ");
2786 unsigned AllowedCnt = 0;
2787 unsigned TotalAllowedNum =
2788 AllowedNameModifiers.size() - NamedModifiersNumber;
2789 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2790 ++Cnt) {
2791 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2792 if (!FoundNameModifiers[NM]) {
2793 Values += "'";
2794 Values += getOpenMPDirectiveName(NM);
2795 Values += "'";
2796 if (AllowedCnt + 2 == TotalAllowedNum)
2797 Values += " or ";
2798 else if (AllowedCnt + 1 != TotalAllowedNum)
2799 Values += Sep;
2800 ++AllowedCnt;
2801 }
2802 }
2803 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2804 diag::err_omp_unnamed_if_clause)
2805 << (TotalAllowedNum > 1) << Values;
2806 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002807 for (auto Loc : NameModifierLoc) {
2808 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2809 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002810 ErrorFound = true;
2811 }
2812 return ErrorFound;
2813}
2814
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002815StmtResult Sema::ActOnOpenMPExecutableDirective(
2816 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2817 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2818 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002819 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002820 // First check CancelRegion which is then used in checkNestingOfRegions.
2821 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2822 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002823 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002824 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002825
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002826 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002827 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002828 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002829 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002830 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002831 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2832
2833 // Check default data sharing attributes for referenced variables.
2834 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002835 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2836 Stmt *S = AStmt;
2837 while (--ThisCaptureLevel >= 0)
2838 S = cast<CapturedStmt>(S)->getCapturedStmt();
2839 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002840 if (DSAChecker.isErrorFound())
2841 return StmtError();
2842 // Generate list of implicitly defined firstprivate variables.
2843 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002844
Alexey Bataev88202be2017-07-27 13:20:36 +00002845 SmallVector<Expr *, 4> ImplicitFirstprivates(
2846 DSAChecker.getImplicitFirstprivate().begin(),
2847 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002848 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2849 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002850 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2851 for (auto *C : Clauses) {
2852 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2853 for (auto *E : IRC->taskgroup_descriptors())
2854 if (E)
2855 ImplicitFirstprivates.emplace_back(E);
2856 }
2857 }
2858 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002859 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002860 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2861 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002862 ClausesWithImplicit.push_back(Implicit);
2863 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002864 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002865 } else
2866 ErrorFound = true;
2867 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002868 if (!ImplicitMaps.empty()) {
2869 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2870 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2871 SourceLocation(), SourceLocation(), ImplicitMaps,
2872 SourceLocation(), SourceLocation(), SourceLocation())) {
2873 ClausesWithImplicit.emplace_back(Implicit);
2874 ErrorFound |=
2875 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2876 } else
2877 ErrorFound = true;
2878 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002879 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002880
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002881 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002882 switch (Kind) {
2883 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002884 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2885 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002886 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002887 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002888 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002889 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2890 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002891 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002892 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002893 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2894 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002895 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002896 case OMPD_for_simd:
2897 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2898 EndLoc, VarsWithInheritedDSA);
2899 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002900 case OMPD_sections:
2901 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2902 EndLoc);
2903 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002904 case OMPD_section:
2905 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002906 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002907 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2908 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002909 case OMPD_single:
2910 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2911 EndLoc);
2912 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002913 case OMPD_master:
2914 assert(ClausesWithImplicit.empty() &&
2915 "No clauses are allowed for 'omp master' directive");
2916 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2917 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002918 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002919 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2920 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002921 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002922 case OMPD_parallel_for:
2923 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2924 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002925 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002926 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002927 case OMPD_parallel_for_simd:
2928 Res = ActOnOpenMPParallelForSimdDirective(
2929 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002930 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002931 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002932 case OMPD_parallel_sections:
2933 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2934 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002935 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002936 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002937 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002938 Res =
2939 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002940 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002941 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002942 case OMPD_taskyield:
2943 assert(ClausesWithImplicit.empty() &&
2944 "No clauses are allowed for 'omp taskyield' directive");
2945 assert(AStmt == nullptr &&
2946 "No associated statement allowed for 'omp taskyield' directive");
2947 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2948 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002949 case OMPD_barrier:
2950 assert(ClausesWithImplicit.empty() &&
2951 "No clauses are allowed for 'omp barrier' directive");
2952 assert(AStmt == nullptr &&
2953 "No associated statement allowed for 'omp barrier' directive");
2954 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2955 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002956 case OMPD_taskwait:
2957 assert(ClausesWithImplicit.empty() &&
2958 "No clauses are allowed for 'omp taskwait' directive");
2959 assert(AStmt == nullptr &&
2960 "No associated statement allowed for 'omp taskwait' directive");
2961 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2962 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002963 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002964 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2965 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002966 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002967 case OMPD_flush:
2968 assert(AStmt == nullptr &&
2969 "No associated statement allowed for 'omp flush' directive");
2970 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2971 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002972 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002973 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2974 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002975 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002976 case OMPD_atomic:
2977 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2978 EndLoc);
2979 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002980 case OMPD_teams:
2981 Res =
2982 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2983 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002984 case OMPD_target:
2985 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2986 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002987 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002988 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002989 case OMPD_target_parallel:
2990 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2991 StartLoc, EndLoc);
2992 AllowedNameModifiers.push_back(OMPD_target);
2993 AllowedNameModifiers.push_back(OMPD_parallel);
2994 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002995 case OMPD_target_parallel_for:
2996 Res = ActOnOpenMPTargetParallelForDirective(
2997 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2998 AllowedNameModifiers.push_back(OMPD_target);
2999 AllowedNameModifiers.push_back(OMPD_parallel);
3000 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003001 case OMPD_cancellation_point:
3002 assert(ClausesWithImplicit.empty() &&
3003 "No clauses are allowed for 'omp cancellation point' directive");
3004 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3005 "cancellation point' directive");
3006 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3007 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003008 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003009 assert(AStmt == nullptr &&
3010 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003011 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3012 CancelRegion);
3013 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003014 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003015 case OMPD_target_data:
3016 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3017 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003018 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003019 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003020 case OMPD_target_enter_data:
3021 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003022 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003023 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3024 break;
Samuel Antao72590762016-01-19 20:04:50 +00003025 case OMPD_target_exit_data:
3026 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003027 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003028 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3029 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003030 case OMPD_taskloop:
3031 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3032 EndLoc, VarsWithInheritedDSA);
3033 AllowedNameModifiers.push_back(OMPD_taskloop);
3034 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003035 case OMPD_taskloop_simd:
3036 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3037 EndLoc, VarsWithInheritedDSA);
3038 AllowedNameModifiers.push_back(OMPD_taskloop);
3039 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003040 case OMPD_distribute:
3041 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3042 EndLoc, VarsWithInheritedDSA);
3043 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003044 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003045 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3046 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003047 AllowedNameModifiers.push_back(OMPD_target_update);
3048 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003049 case OMPD_distribute_parallel_for:
3050 Res = ActOnOpenMPDistributeParallelForDirective(
3051 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3052 AllowedNameModifiers.push_back(OMPD_parallel);
3053 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003054 case OMPD_distribute_parallel_for_simd:
3055 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3056 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3057 AllowedNameModifiers.push_back(OMPD_parallel);
3058 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003059 case OMPD_distribute_simd:
3060 Res = ActOnOpenMPDistributeSimdDirective(
3061 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3062 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003063 case OMPD_target_parallel_for_simd:
3064 Res = ActOnOpenMPTargetParallelForSimdDirective(
3065 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3066 AllowedNameModifiers.push_back(OMPD_target);
3067 AllowedNameModifiers.push_back(OMPD_parallel);
3068 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003069 case OMPD_target_simd:
3070 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3071 EndLoc, VarsWithInheritedDSA);
3072 AllowedNameModifiers.push_back(OMPD_target);
3073 break;
Kelvin Li02532872016-08-05 14:37:37 +00003074 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003075 Res = ActOnOpenMPTeamsDistributeDirective(
3076 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003077 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003078 case OMPD_teams_distribute_simd:
3079 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3080 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3081 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003082 case OMPD_teams_distribute_parallel_for_simd:
3083 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3084 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3085 AllowedNameModifiers.push_back(OMPD_parallel);
3086 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003087 case OMPD_teams_distribute_parallel_for:
3088 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3089 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3090 AllowedNameModifiers.push_back(OMPD_parallel);
3091 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003092 case OMPD_target_teams:
3093 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3094 EndLoc);
3095 AllowedNameModifiers.push_back(OMPD_target);
3096 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003097 case OMPD_target_teams_distribute:
3098 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3099 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3100 AllowedNameModifiers.push_back(OMPD_target);
3101 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003102 case OMPD_target_teams_distribute_parallel_for:
3103 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3104 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3105 AllowedNameModifiers.push_back(OMPD_target);
3106 AllowedNameModifiers.push_back(OMPD_parallel);
3107 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003108 case OMPD_target_teams_distribute_parallel_for_simd:
3109 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3110 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3111 AllowedNameModifiers.push_back(OMPD_target);
3112 AllowedNameModifiers.push_back(OMPD_parallel);
3113 break;
Kelvin Lida681182017-01-10 18:08:18 +00003114 case OMPD_target_teams_distribute_simd:
3115 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3116 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3117 AllowedNameModifiers.push_back(OMPD_target);
3118 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003119 case OMPD_declare_target:
3120 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003121 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003122 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003123 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003124 llvm_unreachable("OpenMP Directive is not allowed");
3125 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003126 llvm_unreachable("Unknown OpenMP directive");
3127 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003128
Alexey Bataev4acb8592014-07-07 13:01:15 +00003129 for (auto P : VarsWithInheritedDSA) {
3130 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3131 << P.first << P.second->getSourceRange();
3132 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003133 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3134
3135 if (!AllowedNameModifiers.empty())
3136 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3137 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003138
Alexey Bataeved09d242014-05-28 05:53:51 +00003139 if (ErrorFound)
3140 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003141 return Res;
3142}
3143
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003144Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3145 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003146 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003147 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3148 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003149 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003150 assert(Linears.size() == LinModifiers.size());
3151 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003152 if (!DG || DG.get().isNull())
3153 return DeclGroupPtrTy();
3154
3155 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003156 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003157 return DG;
3158 }
3159 auto *ADecl = DG.get().getSingleDecl();
3160 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3161 ADecl = FTD->getTemplatedDecl();
3162
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003163 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3164 if (!FD) {
3165 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003166 return DeclGroupPtrTy();
3167 }
3168
Alexey Bataev2af33e32016-04-07 12:45:37 +00003169 // OpenMP [2.8.2, declare simd construct, Description]
3170 // The parameter of the simdlen clause must be a constant positive integer
3171 // expression.
3172 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003173 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003174 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003175 // OpenMP [2.8.2, declare simd construct, Description]
3176 // The special this pointer can be used as if was one of the arguments to the
3177 // function in any of the linear, aligned, or uniform clauses.
3178 // The uniform clause declares one or more arguments to have an invariant
3179 // value for all concurrent invocations of the function in the execution of a
3180 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003181 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3182 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003183 for (auto *E : Uniforms) {
3184 E = E->IgnoreParenImpCasts();
3185 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3186 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3187 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3188 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003189 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3190 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003191 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003192 }
3193 if (isa<CXXThisExpr>(E)) {
3194 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003195 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003196 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003197 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3198 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003199 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003200 // OpenMP [2.8.2, declare simd construct, Description]
3201 // The aligned clause declares that the object to which each list item points
3202 // is aligned to the number of bytes expressed in the optional parameter of
3203 // the aligned clause.
3204 // The special this pointer can be used as if was one of the arguments to the
3205 // function in any of the linear, aligned, or uniform clauses.
3206 // The type of list items appearing in the aligned clause must be array,
3207 // pointer, reference to array, or reference to pointer.
3208 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3209 Expr *AlignedThis = nullptr;
3210 for (auto *E : Aligneds) {
3211 E = E->IgnoreParenImpCasts();
3212 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3213 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3214 auto *CanonPVD = PVD->getCanonicalDecl();
3215 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3216 FD->getParamDecl(PVD->getFunctionScopeIndex())
3217 ->getCanonicalDecl() == CanonPVD) {
3218 // OpenMP [2.8.1, simd construct, Restrictions]
3219 // A list-item cannot appear in more than one aligned clause.
3220 if (AlignedArgs.count(CanonPVD) > 0) {
3221 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3222 << 1 << E->getSourceRange();
3223 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3224 diag::note_omp_explicit_dsa)
3225 << getOpenMPClauseName(OMPC_aligned);
3226 continue;
3227 }
3228 AlignedArgs[CanonPVD] = E;
3229 QualType QTy = PVD->getType()
3230 .getNonReferenceType()
3231 .getUnqualifiedType()
3232 .getCanonicalType();
3233 const Type *Ty = QTy.getTypePtrOrNull();
3234 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3235 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3236 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3237 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3238 }
3239 continue;
3240 }
3241 }
3242 if (isa<CXXThisExpr>(E)) {
3243 if (AlignedThis) {
3244 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3245 << 2 << E->getSourceRange();
3246 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3247 << getOpenMPClauseName(OMPC_aligned);
3248 }
3249 AlignedThis = E;
3250 continue;
3251 }
3252 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3253 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3254 }
3255 // The optional parameter of the aligned clause, alignment, must be a constant
3256 // positive integer expression. If no optional parameter is specified,
3257 // implementation-defined default alignments for SIMD instructions on the
3258 // target platforms are assumed.
3259 SmallVector<Expr *, 4> NewAligns;
3260 for (auto *E : Alignments) {
3261 ExprResult Align;
3262 if (E)
3263 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3264 NewAligns.push_back(Align.get());
3265 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003266 // OpenMP [2.8.2, declare simd construct, Description]
3267 // The linear clause declares one or more list items to be private to a SIMD
3268 // lane and to have a linear relationship with respect to the iteration space
3269 // of a loop.
3270 // The special this pointer can be used as if was one of the arguments to the
3271 // function in any of the linear, aligned, or uniform clauses.
3272 // When a linear-step expression is specified in a linear clause it must be
3273 // either a constant integer expression or an integer-typed parameter that is
3274 // specified in a uniform clause on the directive.
3275 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3276 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3277 auto MI = LinModifiers.begin();
3278 for (auto *E : Linears) {
3279 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3280 ++MI;
3281 E = E->IgnoreParenImpCasts();
3282 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3283 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3284 auto *CanonPVD = PVD->getCanonicalDecl();
3285 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3286 FD->getParamDecl(PVD->getFunctionScopeIndex())
3287 ->getCanonicalDecl() == CanonPVD) {
3288 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3289 // A list-item cannot appear in more than one linear clause.
3290 if (LinearArgs.count(CanonPVD) > 0) {
3291 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3292 << getOpenMPClauseName(OMPC_linear)
3293 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3294 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3295 diag::note_omp_explicit_dsa)
3296 << getOpenMPClauseName(OMPC_linear);
3297 continue;
3298 }
3299 // Each argument can appear in at most one uniform or linear clause.
3300 if (UniformedArgs.count(CanonPVD) > 0) {
3301 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3302 << getOpenMPClauseName(OMPC_linear)
3303 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3304 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3305 diag::note_omp_explicit_dsa)
3306 << getOpenMPClauseName(OMPC_uniform);
3307 continue;
3308 }
3309 LinearArgs[CanonPVD] = E;
3310 if (E->isValueDependent() || E->isTypeDependent() ||
3311 E->isInstantiationDependent() ||
3312 E->containsUnexpandedParameterPack())
3313 continue;
3314 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3315 PVD->getOriginalType());
3316 continue;
3317 }
3318 }
3319 if (isa<CXXThisExpr>(E)) {
3320 if (UniformedLinearThis) {
3321 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3322 << getOpenMPClauseName(OMPC_linear)
3323 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3324 << E->getSourceRange();
3325 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3326 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3327 : OMPC_linear);
3328 continue;
3329 }
3330 UniformedLinearThis = E;
3331 if (E->isValueDependent() || E->isTypeDependent() ||
3332 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3333 continue;
3334 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3335 E->getType());
3336 continue;
3337 }
3338 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3339 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3340 }
3341 Expr *Step = nullptr;
3342 Expr *NewStep = nullptr;
3343 SmallVector<Expr *, 4> NewSteps;
3344 for (auto *E : Steps) {
3345 // Skip the same step expression, it was checked already.
3346 if (Step == E || !E) {
3347 NewSteps.push_back(E ? NewStep : nullptr);
3348 continue;
3349 }
3350 Step = E;
3351 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3352 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3353 auto *CanonPVD = PVD->getCanonicalDecl();
3354 if (UniformedArgs.count(CanonPVD) == 0) {
3355 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3356 << Step->getSourceRange();
3357 } else if (E->isValueDependent() || E->isTypeDependent() ||
3358 E->isInstantiationDependent() ||
3359 E->containsUnexpandedParameterPack() ||
3360 CanonPVD->getType()->hasIntegerRepresentation())
3361 NewSteps.push_back(Step);
3362 else {
3363 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3364 << Step->getSourceRange();
3365 }
3366 continue;
3367 }
3368 NewStep = Step;
3369 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3370 !Step->isInstantiationDependent() &&
3371 !Step->containsUnexpandedParameterPack()) {
3372 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3373 .get();
3374 if (NewStep)
3375 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3376 }
3377 NewSteps.push_back(NewStep);
3378 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003379 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3380 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003381 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003382 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3383 const_cast<Expr **>(Linears.data()), Linears.size(),
3384 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3385 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003386 ADecl->addAttr(NewAttr);
3387 return ConvertDeclToDeclGroup(ADecl);
3388}
3389
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003390StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3391 Stmt *AStmt,
3392 SourceLocation StartLoc,
3393 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003394 if (!AStmt)
3395 return StmtError();
3396
Alexey Bataev9959db52014-05-06 10:08:46 +00003397 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3398 // 1.2.2 OpenMP Language Terminology
3399 // Structured block - An executable statement with a single entry at the
3400 // top and a single exit at the bottom.
3401 // The point of exit cannot be a branch out of the structured block.
3402 // longjmp() and throw() must not violate the entry/exit criteria.
3403 CS->getCapturedDecl()->setNothrow();
3404
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003405 getCurFunction()->setHasBranchProtectedScope();
3406
Alexey Bataev25e5b442015-09-15 12:52:43 +00003407 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3408 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003409}
3410
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003411namespace {
3412/// \brief Helper class for checking canonical form of the OpenMP loops and
3413/// extracting iteration space of each loop in the loop nest, that will be used
3414/// for IR generation.
3415class OpenMPIterationSpaceChecker {
3416 /// \brief Reference to Sema.
3417 Sema &SemaRef;
3418 /// \brief A location for diagnostics (when there is no some better location).
3419 SourceLocation DefaultLoc;
3420 /// \brief A location for diagnostics (when increment is not compatible).
3421 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003422 /// \brief A source location for referring to loop init later.
3423 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003424 /// \brief A source location for referring to condition later.
3425 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003426 /// \brief A source location for referring to increment later.
3427 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003428 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003429 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003430 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003431 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003432 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003433 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003434 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003435 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003436 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003437 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003438 /// \brief This flag is true when condition is one of:
3439 /// Var < UB
3440 /// Var <= UB
3441 /// UB > Var
3442 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003443 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003444 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003445 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003446 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003447 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003448
3449public:
3450 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003451 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452 /// \brief Check init-expr for canonical loop form and save loop counter
3453 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003454 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003455 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3456 /// for less/greater and for strict/non-strict comparison.
3457 bool CheckCond(Expr *S);
3458 /// \brief Check incr-expr for canonical loop form and return true if it
3459 /// does not conform, otherwise save loop step (#Step).
3460 bool CheckInc(Expr *S);
3461 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003463 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003464 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003465 /// \brief Source range of the loop init.
3466 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3467 /// \brief Source range of the loop condition.
3468 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3469 /// \brief Source range of the loop increment.
3470 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3471 /// \brief True if the step should be subtracted.
3472 bool ShouldSubtractStep() const { return SubtractStep; }
3473 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003474 Expr *
3475 BuildNumIterations(Scope *S, const bool LimitedType,
3476 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003477 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003478 Expr *BuildPreCond(Scope *S, Expr *Cond,
3479 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003480 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003481 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3482 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003483 /// \brief Build reference expression to the private counter be used for
3484 /// codegen.
3485 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003486 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003487 Expr *BuildCounterInit() const;
3488 /// \brief Build step of the counter be used for codegen.
3489 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003490 /// \brief Return true if any expression is dependent.
3491 bool Dependent() const;
3492
3493private:
3494 /// \brief Check the right-hand side of an assignment in the increment
3495 /// expression.
3496 bool CheckIncRHS(Expr *RHS);
3497 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003498 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003499 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003500 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003501 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003502 /// \brief Helper to set loop increment.
3503 bool SetStep(Expr *NewStep, bool Subtract);
3504};
3505
3506bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003507 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003508 assert(!LB && !UB && !Step);
3509 return false;
3510 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003511 return LCDecl->getType()->isDependentType() ||
3512 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3513 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003514}
3515
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003516bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3517 Expr *NewLCRefExpr,
3518 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003519 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003520 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003521 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003522 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003523 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003524 LCDecl = getCanonicalDecl(NewLCDecl);
3525 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003526 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3527 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003528 if ((Ctor->isCopyOrMoveConstructor() ||
3529 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3530 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003531 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003532 LB = NewLB;
3533 return false;
3534}
3535
3536bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003537 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003538 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003539 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3540 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003541 if (!NewUB)
3542 return true;
3543 UB = NewUB;
3544 TestIsLessOp = LessOp;
3545 TestIsStrictOp = StrictOp;
3546 ConditionSrcRange = SR;
3547 ConditionLoc = SL;
3548 return false;
3549}
3550
3551bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3552 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003553 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003554 if (!NewStep)
3555 return true;
3556 if (!NewStep->isValueDependent()) {
3557 // Check that the step is integer expression.
3558 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003559 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3560 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003561 if (Val.isInvalid())
3562 return true;
3563 NewStep = Val.get();
3564
3565 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3566 // If test-expr is of form var relational-op b and relational-op is < or
3567 // <= then incr-expr must cause var to increase on each iteration of the
3568 // loop. If test-expr is of form var relational-op b and relational-op is
3569 // > or >= then incr-expr must cause var to decrease on each iteration of
3570 // the loop.
3571 // If test-expr is of form b relational-op var and relational-op is < or
3572 // <= then incr-expr must cause var to decrease on each iteration of the
3573 // loop. If test-expr is of form b relational-op var and relational-op is
3574 // > or >= then incr-expr must cause var to increase on each iteration of
3575 // the loop.
3576 llvm::APSInt Result;
3577 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3578 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3579 bool IsConstNeg =
3580 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003581 bool IsConstPos =
3582 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003583 bool IsConstZero = IsConstant && !Result.getBoolValue();
3584 if (UB && (IsConstZero ||
3585 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587 SemaRef.Diag(NewStep->getExprLoc(),
3588 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003589 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003590 SemaRef.Diag(ConditionLoc,
3591 diag::note_omp_loop_cond_requres_compatible_incr)
3592 << TestIsLessOp << ConditionSrcRange;
3593 return true;
3594 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003595 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003596 NewStep =
3597 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3598 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003599 Subtract = !Subtract;
3600 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003601 }
3602
3603 Step = NewStep;
3604 SubtractStep = Subtract;
3605 return false;
3606}
3607
Alexey Bataev9c821032015-04-30 04:23:23 +00003608bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003609 // Check init-expr for canonical loop form and save loop counter
3610 // variable - #Var and its initialization value - #LB.
3611 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3612 // var = lb
3613 // integer-type var = lb
3614 // random-access-iterator-type var = lb
3615 // pointer-type var = lb
3616 //
3617 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003618 if (EmitDiags) {
3619 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3620 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003621 return true;
3622 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003623 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3624 if (!ExprTemp->cleanupsHaveSideEffects())
3625 S = ExprTemp->getSubExpr();
3626
Alexander Musmana5f070a2014-10-01 06:03:56 +00003627 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003628 if (Expr *E = dyn_cast<Expr>(S))
3629 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003630 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003631 if (BO->getOpcode() == BO_Assign) {
3632 auto *LHS = BO->getLHS()->IgnoreParens();
3633 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3634 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3635 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3636 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3637 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3638 }
3639 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3640 if (ME->isArrow() &&
3641 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3642 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3643 }
3644 }
David Majnemer9d168222016-08-05 17:44:54 +00003645 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003646 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003647 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003648 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003649 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003650 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003651 SemaRef.Diag(S->getLocStart(),
3652 diag::ext_omp_loop_not_canonical_init)
3653 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003654 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003655 }
3656 }
3657 }
David Majnemer9d168222016-08-05 17:44:54 +00003658 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003659 if (CE->getOperator() == OO_Equal) {
3660 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003661 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003662 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3663 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3664 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3665 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3666 }
3667 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3668 if (ME->isArrow() &&
3669 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3670 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3671 }
3672 }
3673 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003674
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003675 if (Dependent() || SemaRef.CurContext->isDependentContext())
3676 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003677 if (EmitDiags) {
3678 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3679 << S->getSourceRange();
3680 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003681 return true;
3682}
3683
Alexey Bataev23b69422014-06-18 07:08:49 +00003684/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003685/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003686static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003687 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003688 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003689 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003690 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3691 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003692 if ((Ctor->isCopyOrMoveConstructor() ||
3693 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3694 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003695 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003697 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003698 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003699 }
3700 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3701 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3702 return getCanonicalDecl(ME->getMemberDecl());
3703 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003704}
3705
3706bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3707 // Check test-expr for canonical form, save upper-bound UB, flags for
3708 // less/greater and for strict/non-strict comparison.
3709 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3710 // var relational-op b
3711 // b relational-op var
3712 //
3713 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003714 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 return true;
3716 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003717 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003718 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003719 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003720 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003721 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003722 return SetUB(BO->getRHS(),
3723 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3724 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3725 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003726 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003727 return SetUB(BO->getLHS(),
3728 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3729 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3730 BO->getSourceRange(), BO->getOperatorLoc());
3731 }
David Majnemer9d168222016-08-05 17:44:54 +00003732 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003733 if (CE->getNumArgs() == 2) {
3734 auto Op = CE->getOperator();
3735 switch (Op) {
3736 case OO_Greater:
3737 case OO_GreaterEqual:
3738 case OO_Less:
3739 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003740 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003741 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3742 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3743 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003744 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003745 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3746 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3747 CE->getOperatorLoc());
3748 break;
3749 default:
3750 break;
3751 }
3752 }
3753 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003754 if (Dependent() || SemaRef.CurContext->isDependentContext())
3755 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003756 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003757 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003758 return true;
3759}
3760
3761bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3762 // RHS of canonical loop form increment can be:
3763 // var + incr
3764 // incr + var
3765 // var - incr
3766 //
3767 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003768 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003769 if (BO->isAdditiveOp()) {
3770 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003771 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003772 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003773 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003774 return SetStep(BO->getLHS(), false);
3775 }
David Majnemer9d168222016-08-05 17:44:54 +00003776 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 bool IsAdd = CE->getOperator() == OO_Plus;
3778 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003779 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003780 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003781 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003782 return SetStep(CE->getArg(0), false);
3783 }
3784 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003785 if (Dependent() || SemaRef.CurContext->isDependentContext())
3786 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003787 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003788 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003789 return true;
3790}
3791
3792bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3793 // Check incr-expr for canonical loop form and return true if it
3794 // does not conform.
3795 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3796 // ++var
3797 // var++
3798 // --var
3799 // var--
3800 // var += incr
3801 // var -= incr
3802 // var = var + incr
3803 // var = incr + var
3804 // var = var - incr
3805 //
3806 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003807 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003808 return true;
3809 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003810 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3811 if (!ExprTemp->cleanupsHaveSideEffects())
3812 S = ExprTemp->getSubExpr();
3813
Alexander Musmana5f070a2014-10-01 06:03:56 +00003814 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003815 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003816 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003817 if (UO->isIncrementDecrementOp() &&
3818 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003819 return SetStep(SemaRef
3820 .ActOnIntegerConstant(UO->getLocStart(),
3821 (UO->isDecrementOp() ? -1 : 1))
3822 .get(),
3823 false);
3824 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003825 switch (BO->getOpcode()) {
3826 case BO_AddAssign:
3827 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003828 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003829 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3830 break;
3831 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003832 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003833 return CheckIncRHS(BO->getRHS());
3834 break;
3835 default:
3836 break;
3837 }
David Majnemer9d168222016-08-05 17:44:54 +00003838 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003839 switch (CE->getOperator()) {
3840 case OO_PlusPlus:
3841 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003842 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003843 return SetStep(SemaRef
3844 .ActOnIntegerConstant(
3845 CE->getLocStart(),
3846 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3847 .get(),
3848 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003849 break;
3850 case OO_PlusEqual:
3851 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003852 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003853 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3854 break;
3855 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003856 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003857 return CheckIncRHS(CE->getArg(1));
3858 break;
3859 default:
3860 break;
3861 }
3862 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003863 if (Dependent() || SemaRef.CurContext->isDependentContext())
3864 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003865 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003866 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003867 return true;
3868}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003869
Alexey Bataev5a3af132016-03-29 08:58:54 +00003870static ExprResult
3871tryBuildCapture(Sema &SemaRef, Expr *Capture,
3872 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003873 if (SemaRef.CurContext->isDependentContext())
3874 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003875 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3876 return SemaRef.PerformImplicitConversion(
3877 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3878 /*AllowExplicit=*/true);
3879 auto I = Captures.find(Capture);
3880 if (I != Captures.end())
3881 return buildCapture(SemaRef, Capture, I->second);
3882 DeclRefExpr *Ref = nullptr;
3883 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3884 Captures[Capture] = Ref;
3885 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003886}
3887
Alexander Musmana5f070a2014-10-01 06:03:56 +00003888/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003889Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3890 Scope *S, const bool LimitedType,
3891 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003893 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003894 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003895 SemaRef.getLangOpts().CPlusPlus) {
3896 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003897 auto *UBExpr = TestIsLessOp ? UB : LB;
3898 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003899 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3900 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003901 if (!Upper || !Lower)
3902 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003903
3904 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3905
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003906 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003907 // BuildBinOp already emitted error, this one is to point user to upper
3908 // and lower bound, and to tell what is passed to 'operator-'.
3909 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3910 << Upper->getSourceRange() << Lower->getSourceRange();
3911 return nullptr;
3912 }
3913 }
3914
3915 if (!Diff.isUsable())
3916 return nullptr;
3917
3918 // Upper - Lower [- 1]
3919 if (TestIsStrictOp)
3920 Diff = SemaRef.BuildBinOp(
3921 S, DefaultLoc, BO_Sub, Diff.get(),
3922 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3923 if (!Diff.isUsable())
3924 return nullptr;
3925
3926 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003927 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3928 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003929 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003930 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003931 if (!Diff.isUsable())
3932 return nullptr;
3933
3934 // Parentheses (for dumping/debugging purposes only).
3935 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3936 if (!Diff.isUsable())
3937 return nullptr;
3938
3939 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003940 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003941 if (!Diff.isUsable())
3942 return nullptr;
3943
Alexander Musman174b3ca2014-10-06 11:16:29 +00003944 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003945 QualType Type = Diff.get()->getType();
3946 auto &C = SemaRef.Context;
3947 bool UseVarType = VarType->hasIntegerRepresentation() &&
3948 C.getTypeSize(Type) > C.getTypeSize(VarType);
3949 if (!Type->isIntegerType() || UseVarType) {
3950 unsigned NewSize =
3951 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3952 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3953 : Type->hasSignedIntegerRepresentation();
3954 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003955 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3956 Diff = SemaRef.PerformImplicitConversion(
3957 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3958 if (!Diff.isUsable())
3959 return nullptr;
3960 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003961 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003962 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003963 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3964 if (NewSize != C.getTypeSize(Type)) {
3965 if (NewSize < C.getTypeSize(Type)) {
3966 assert(NewSize == 64 && "incorrect loop var size");
3967 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3968 << InitSrcRange << ConditionSrcRange;
3969 }
3970 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003971 NewSize, Type->hasSignedIntegerRepresentation() ||
3972 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003973 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3974 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3975 Sema::AA_Converting, true);
3976 if (!Diff.isUsable())
3977 return nullptr;
3978 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003979 }
3980 }
3981
Alexander Musmana5f070a2014-10-01 06:03:56 +00003982 return Diff.get();
3983}
3984
Alexey Bataev5a3af132016-03-29 08:58:54 +00003985Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3986 Scope *S, Expr *Cond,
3987 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003988 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3989 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3990 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003991
Alexey Bataev5a3af132016-03-29 08:58:54 +00003992 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3993 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3994 if (!NewLB.isUsable() || !NewUB.isUsable())
3995 return nullptr;
3996
Alexey Bataev62dbb972015-04-22 11:59:37 +00003997 auto CondExpr = SemaRef.BuildBinOp(
3998 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3999 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004000 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004001 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004002 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4003 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004004 CondExpr = SemaRef.PerformImplicitConversion(
4005 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4006 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004007 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004008 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4009 // Otherwise use original loop conditon and evaluate it in runtime.
4010 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4011}
4012
Alexander Musmana5f070a2014-10-01 06:03:56 +00004013/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004014DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004015 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004016 auto *VD = dyn_cast<VarDecl>(LCDecl);
4017 if (!VD) {
4018 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4019 auto *Ref = buildDeclRefExpr(
4020 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004021 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4022 // If the loop control decl is explicitly marked as private, do not mark it
4023 // as captured again.
4024 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4025 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004026 return Ref;
4027 }
4028 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004029 DefaultLoc);
4030}
4031
4032Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004033 if (LCDecl && !LCDecl->isInvalidDecl()) {
4034 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004035 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004036 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4037 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004038 if (PrivateVar->isInvalidDecl())
4039 return nullptr;
4040 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4041 }
4042 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004043}
4044
Samuel Antao4c8035b2016-12-12 18:00:20 +00004045/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004046Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4047
4048/// \brief Build step of the counter be used for codegen.
4049Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4050
4051/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004052struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004053 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004054 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004055 /// \brief This expression calculates the number of iterations in the loop.
4056 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004057 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004058 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004059 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004060 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004061 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004062 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004063 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004064 /// \brief This is step for the #CounterVar used to generate its update:
4065 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004066 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004067 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004068 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004069 /// \brief Source range of the loop init.
4070 SourceRange InitSrcRange;
4071 /// \brief Source range of the loop condition.
4072 SourceRange CondSrcRange;
4073 /// \brief Source range of the loop increment.
4074 SourceRange IncSrcRange;
4075};
4076
Alexey Bataev23b69422014-06-18 07:08:49 +00004077} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004078
Alexey Bataev9c821032015-04-30 04:23:23 +00004079void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4080 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4081 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004082 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4083 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004084 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4085 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004086 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4087 if (auto *D = ISC.GetLoopDecl()) {
4088 auto *VD = dyn_cast<VarDecl>(D);
4089 if (!VD) {
4090 if (auto *Private = IsOpenMPCapturedDecl(D))
4091 VD = Private;
4092 else {
4093 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4094 /*WithInit=*/false);
4095 VD = cast<VarDecl>(Ref->getDecl());
4096 }
4097 }
4098 DSAStack->addLoopControlVariable(D, VD);
4099 }
4100 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004101 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004102 }
4103}
4104
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004105/// \brief Called on a for stmt to check and extract its iteration space
4106/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004107static bool CheckOpenMPIterationSpace(
4108 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4109 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004110 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004111 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004112 LoopIterationSpace &ResultIterSpace,
4113 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004114 // OpenMP [2.6, Canonical Loop Form]
4115 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004116 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004117 if (!For) {
4118 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004119 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4120 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4121 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4122 if (NestedLoopCount > 1) {
4123 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4124 SemaRef.Diag(DSA.getConstructLoc(),
4125 diag::note_omp_collapse_ordered_expr)
4126 << 2 << CollapseLoopCountExpr->getSourceRange()
4127 << OrderedLoopCountExpr->getSourceRange();
4128 else if (CollapseLoopCountExpr)
4129 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4130 diag::note_omp_collapse_ordered_expr)
4131 << 0 << CollapseLoopCountExpr->getSourceRange();
4132 else
4133 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4134 diag::note_omp_collapse_ordered_expr)
4135 << 1 << OrderedLoopCountExpr->getSourceRange();
4136 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004137 return true;
4138 }
4139 assert(For->getBody());
4140
4141 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4142
4143 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004144 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004145 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004146 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004147
4148 bool HasErrors = false;
4149
4150 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004151 if (auto *LCDecl = ISC.GetLoopDecl()) {
4152 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004153
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004154 // OpenMP [2.6, Canonical Loop Form]
4155 // Var is one of the following:
4156 // A variable of signed or unsigned integer type.
4157 // For C++, a variable of a random access iterator type.
4158 // For C, a variable of a pointer type.
4159 auto VarType = LCDecl->getType().getNonReferenceType();
4160 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4161 !VarType->isPointerType() &&
4162 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4163 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4164 << SemaRef.getLangOpts().CPlusPlus;
4165 HasErrors = true;
4166 }
4167
4168 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4169 // a Construct
4170 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4171 // parallel for construct is (are) private.
4172 // The loop iteration variable in the associated for-loop of a simd
4173 // construct with just one associated for-loop is linear with a
4174 // constant-linear-step that is the increment of the associated for-loop.
4175 // Exclude loop var from the list of variables with implicitly defined data
4176 // sharing attributes.
4177 VarsWithImplicitDSA.erase(LCDecl);
4178
4179 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4180 // in a Construct, C/C++].
4181 // The loop iteration variable in the associated for-loop of a simd
4182 // construct with just one associated for-loop may be listed in a linear
4183 // clause with a constant-linear-step that is the increment of the
4184 // associated for-loop.
4185 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4186 // parallel for construct may be listed in a private or lastprivate clause.
4187 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4188 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4189 // declared in the loop and it is predetermined as a private.
4190 auto PredeterminedCKind =
4191 isOpenMPSimdDirective(DKind)
4192 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4193 : OMPC_private;
4194 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4195 DVar.CKind != PredeterminedCKind) ||
4196 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4197 isOpenMPDistributeDirective(DKind)) &&
4198 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4199 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4200 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4201 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4202 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4203 << getOpenMPClauseName(PredeterminedCKind);
4204 if (DVar.RefExpr == nullptr)
4205 DVar.CKind = PredeterminedCKind;
4206 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4207 HasErrors = true;
4208 } else if (LoopDeclRefExpr != nullptr) {
4209 // Make the loop iteration variable private (for worksharing constructs),
4210 // linear (for simd directives with the only one associated loop) or
4211 // lastprivate (for simd directives with several collapsed or ordered
4212 // loops).
4213 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004214 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4215 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004216 /*FromParent=*/false);
4217 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4218 }
4219
4220 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4221
4222 // Check test-expr.
4223 HasErrors |= ISC.CheckCond(For->getCond());
4224
4225 // Check incr-expr.
4226 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004227 }
4228
Alexander Musmana5f070a2014-10-01 06:03:56 +00004229 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004230 return HasErrors;
4231
Alexander Musmana5f070a2014-10-01 06:03:56 +00004232 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004233 ResultIterSpace.PreCond =
4234 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004235 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004236 DSA.getCurScope(),
4237 (isOpenMPWorksharingDirective(DKind) ||
4238 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4239 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004240 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004241 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004242 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4243 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4244 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4245 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4246 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4247 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4248
Alexey Bataev62dbb972015-04-22 11:59:37 +00004249 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4250 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004251 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004252 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004253 ResultIterSpace.CounterInit == nullptr ||
4254 ResultIterSpace.CounterStep == nullptr);
4255
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004256 return HasErrors;
4257}
4258
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004259/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004260static ExprResult
4261BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4262 ExprResult Start,
4263 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004264 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004265 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4266 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004267 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004268 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004269 VarRef.get()->getType())) {
4270 NewStart = SemaRef.PerformImplicitConversion(
4271 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4272 /*AllowExplicit=*/true);
4273 if (!NewStart.isUsable())
4274 return ExprError();
4275 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004276
4277 auto Init =
4278 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4279 return Init;
4280}
4281
Alexander Musmana5f070a2014-10-01 06:03:56 +00004282/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004283static ExprResult
4284BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4285 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4286 ExprResult Step, bool Subtract,
4287 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004288 // Add parentheses (for debugging purposes only).
4289 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4290 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4291 !Step.isUsable())
4292 return ExprError();
4293
Alexey Bataev5a3af132016-03-29 08:58:54 +00004294 ExprResult NewStep = Step;
4295 if (Captures)
4296 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004297 if (NewStep.isInvalid())
4298 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004299 ExprResult Update =
4300 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004301 if (!Update.isUsable())
4302 return ExprError();
4303
Alexey Bataevc0214e02016-02-16 12:13:49 +00004304 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4305 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004306 ExprResult NewStart = Start;
4307 if (Captures)
4308 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004309 if (NewStart.isInvalid())
4310 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004311
Alexey Bataevc0214e02016-02-16 12:13:49 +00004312 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4313 ExprResult SavedUpdate = Update;
4314 ExprResult UpdateVal;
4315 if (VarRef.get()->getType()->isOverloadableType() ||
4316 NewStart.get()->getType()->isOverloadableType() ||
4317 Update.get()->getType()->isOverloadableType()) {
4318 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4319 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4320 Update =
4321 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4322 if (Update.isUsable()) {
4323 UpdateVal =
4324 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4325 VarRef.get(), SavedUpdate.get());
4326 if (UpdateVal.isUsable()) {
4327 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4328 UpdateVal.get());
4329 }
4330 }
4331 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4332 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004333
Alexey Bataevc0214e02016-02-16 12:13:49 +00004334 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4335 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4336 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4337 NewStart.get(), SavedUpdate.get());
4338 if (!Update.isUsable())
4339 return ExprError();
4340
Alexey Bataev11481f52016-02-17 10:29:05 +00004341 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4342 VarRef.get()->getType())) {
4343 Update = SemaRef.PerformImplicitConversion(
4344 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4345 if (!Update.isUsable())
4346 return ExprError();
4347 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004348
4349 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4350 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004351 return Update;
4352}
4353
4354/// \brief Convert integer expression \a E to make it have at least \a Bits
4355/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004356static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004357 if (E == nullptr)
4358 return ExprError();
4359 auto &C = SemaRef.Context;
4360 QualType OldType = E->getType();
4361 unsigned HasBits = C.getTypeSize(OldType);
4362 if (HasBits >= Bits)
4363 return ExprResult(E);
4364 // OK to convert to signed, because new type has more bits than old.
4365 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4366 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4367 true);
4368}
4369
4370/// \brief Check if the given expression \a E is a constant integer that fits
4371/// into \a Bits bits.
4372static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4373 if (E == nullptr)
4374 return false;
4375 llvm::APSInt Result;
4376 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4377 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4378 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004379}
4380
Alexey Bataev5a3af132016-03-29 08:58:54 +00004381/// Build preinits statement for the given declarations.
4382static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004383 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004384 if (!PreInits.empty()) {
4385 return new (Context) DeclStmt(
4386 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4387 SourceLocation(), SourceLocation());
4388 }
4389 return nullptr;
4390}
4391
4392/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004393static Stmt *
4394buildPreInits(ASTContext &Context,
4395 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004396 if (!Captures.empty()) {
4397 SmallVector<Decl *, 16> PreInits;
4398 for (auto &Pair : Captures)
4399 PreInits.push_back(Pair.second->getDecl());
4400 return buildPreInits(Context, PreInits);
4401 }
4402 return nullptr;
4403}
4404
4405/// Build postupdate expression for the given list of postupdates expressions.
4406static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4407 Expr *PostUpdate = nullptr;
4408 if (!PostUpdates.empty()) {
4409 for (auto *E : PostUpdates) {
4410 Expr *ConvE = S.BuildCStyleCastExpr(
4411 E->getExprLoc(),
4412 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4413 E->getExprLoc(), E)
4414 .get();
4415 PostUpdate = PostUpdate
4416 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4417 PostUpdate, ConvE)
4418 .get()
4419 : ConvE;
4420 }
4421 }
4422 return PostUpdate;
4423}
4424
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004425/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004426/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4427/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004428static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004429CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4430 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4431 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004432 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004433 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004434 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004435 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004436 // Found 'collapse' clause - calculate collapse number.
4437 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004438 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004439 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004440 }
4441 if (OrderedLoopCountExpr) {
4442 // Found 'ordered' clause - calculate collapse number.
4443 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004444 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4445 if (Result.getLimitedValue() < NestedLoopCount) {
4446 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4447 diag::err_omp_wrong_ordered_loop_count)
4448 << OrderedLoopCountExpr->getSourceRange();
4449 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4450 diag::note_collapse_loop_count)
4451 << CollapseLoopCountExpr->getSourceRange();
4452 }
4453 NestedLoopCount = Result.getLimitedValue();
4454 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004455 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004456 // This is helper routine for loop directives (e.g., 'for', 'simd',
4457 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004458 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004459 SmallVector<LoopIterationSpace, 4> IterSpaces;
4460 IterSpaces.resize(NestedLoopCount);
4461 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004462 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004463 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004464 NestedLoopCount, CollapseLoopCountExpr,
4465 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004466 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004467 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004468 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004469 // OpenMP [2.8.1, simd construct, Restrictions]
4470 // All loops associated with the construct must be perfectly nested; that
4471 // is, there must be no intervening code nor any OpenMP directive between
4472 // any two loops.
4473 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004474 }
4475
Alexander Musmana5f070a2014-10-01 06:03:56 +00004476 Built.clear(/* size */ NestedLoopCount);
4477
4478 if (SemaRef.CurContext->isDependentContext())
4479 return NestedLoopCount;
4480
4481 // An example of what is generated for the following code:
4482 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004483 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004484 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004485 // for (k = 0; k < NK; ++k)
4486 // for (j = J0; j < NJ; j+=2) {
4487 // <loop body>
4488 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004489 //
4490 // We generate the code below.
4491 // Note: the loop body may be outlined in CodeGen.
4492 // Note: some counters may be C++ classes, operator- is used to find number of
4493 // iterations and operator+= to calculate counter value.
4494 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4495 // or i64 is currently supported).
4496 //
4497 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4498 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4499 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4500 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4501 // // similar updates for vars in clauses (e.g. 'linear')
4502 // <loop body (using local i and j)>
4503 // }
4504 // i = NI; // assign final values of counters
4505 // j = NJ;
4506 //
4507
4508 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4509 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004510 // Precondition tests if there is at least one iteration (all conditions are
4511 // true).
4512 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004513 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004514 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004515 32 /* Bits */, SemaRef
4516 .PerformImplicitConversion(
4517 N0->IgnoreImpCasts(), N0->getType(),
4518 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004519 .get(),
4520 SemaRef);
4521 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004522 64 /* Bits */, SemaRef
4523 .PerformImplicitConversion(
4524 N0->IgnoreImpCasts(), N0->getType(),
4525 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004526 .get(),
4527 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004528
4529 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4530 return NestedLoopCount;
4531
4532 auto &C = SemaRef.Context;
4533 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4534
4535 Scope *CurScope = DSA.getCurScope();
4536 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004537 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004538 PreCond =
4539 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4540 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004541 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004542 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004543 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004544 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4545 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004546 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004547 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004548 SemaRef
4549 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4550 Sema::AA_Converting,
4551 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004552 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004553 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004554 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004555 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004556 SemaRef
4557 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4558 Sema::AA_Converting,
4559 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004560 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004561 }
4562
4563 // Choose either the 32-bit or 64-bit version.
4564 ExprResult LastIteration = LastIteration64;
4565 if (LastIteration32.isUsable() &&
4566 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4567 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4568 FitsInto(
4569 32 /* Bits */,
4570 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4571 LastIteration64.get(), SemaRef)))
4572 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004573 QualType VType = LastIteration.get()->getType();
4574 QualType RealVType = VType;
4575 QualType StrideVType = VType;
4576 if (isOpenMPTaskLoopDirective(DKind)) {
4577 VType =
4578 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4579 StrideVType =
4580 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4581 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004582
4583 if (!LastIteration.isUsable())
4584 return 0;
4585
4586 // Save the number of iterations.
4587 ExprResult NumIterations = LastIteration;
4588 {
4589 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004590 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4591 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004592 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4593 if (!LastIteration.isUsable())
4594 return 0;
4595 }
4596
4597 // Calculate the last iteration number beforehand instead of doing this on
4598 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4599 llvm::APSInt Result;
4600 bool IsConstant =
4601 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4602 ExprResult CalcLastIteration;
4603 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004604 ExprResult SaveRef =
4605 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004606 LastIteration = SaveRef;
4607
4608 // Prepare SaveRef + 1.
4609 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004610 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004611 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4612 if (!NumIterations.isUsable())
4613 return 0;
4614 }
4615
4616 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4617
David Majnemer9d168222016-08-05 17:44:54 +00004618 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004619 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004620 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4621 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004622 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004623 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4624 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004625 SemaRef.AddInitializerToDecl(LBDecl,
4626 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4627 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004628
4629 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004630 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4631 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004632 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004633 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004634
4635 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4636 // This will be used to implement clause 'lastprivate'.
4637 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004638 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4639 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004640 SemaRef.AddInitializerToDecl(ILDecl,
4641 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4642 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004643
4644 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004645 VarDecl *STDecl =
4646 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4647 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004648 SemaRef.AddInitializerToDecl(STDecl,
4649 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4650 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004651
4652 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004653 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004654 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4655 UB.get(), LastIteration.get());
4656 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4657 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4658 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4659 CondOp.get());
4660 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004661
4662 // If we have a combined directive that combines 'distribute', 'for' or
4663 // 'simd' we need to be able to access the bounds of the schedule of the
4664 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4665 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4666 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004667
Carlo Bertolliffafe102017-04-20 00:39:39 +00004668 // Lower bound variable, initialized with zero.
4669 VarDecl *CombLBDecl =
4670 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4671 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4672 SemaRef.AddInitializerToDecl(
4673 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4674 /*DirectInit*/ false);
4675
4676 // Upper bound variable, initialized with last iteration number.
4677 VarDecl *CombUBDecl =
4678 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4679 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4680 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4681 /*DirectInit*/ false);
4682
4683 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4684 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4685 ExprResult CombCondOp =
4686 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4687 LastIteration.get(), CombUB.get());
4688 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4689 CombCondOp.get());
4690 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4691
4692 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004693 // We expect to have at least 2 more parameters than the 'parallel'
4694 // directive does - the lower and upper bounds of the previous schedule.
4695 assert(CD->getNumParams() >= 4 &&
4696 "Unexpected number of parameters in loop combined directive");
4697
4698 // Set the proper type for the bounds given what we learned from the
4699 // enclosed loops.
4700 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4701 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4702
4703 // Previous lower and upper bounds are obtained from the region
4704 // parameters.
4705 PrevLB =
4706 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4707 PrevUB =
4708 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4709 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004710 }
4711
4712 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004713 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004714 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004715 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004716 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4717 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004718 Expr *RHS =
4719 (isOpenMPWorksharingDirective(DKind) ||
4720 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4721 ? LB.get()
4722 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004723 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4724 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004725
4726 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4727 Expr *CombRHS =
4728 (isOpenMPWorksharingDirective(DKind) ||
4729 isOpenMPTaskLoopDirective(DKind) ||
4730 isOpenMPDistributeDirective(DKind))
4731 ? CombLB.get()
4732 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4733 CombInit =
4734 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4735 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4736 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004737 }
4738
Alexander Musmanc6388682014-12-15 07:07:06 +00004739 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004740 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004741 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004742 (isOpenMPWorksharingDirective(DKind) ||
4743 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004744 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4745 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4746 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004747 ExprResult CombCond;
4748 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4749 CombCond =
4750 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4751 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004752 // Loop increment (IV = IV + 1)
4753 SourceLocation IncLoc;
4754 ExprResult Inc =
4755 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4756 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4757 if (!Inc.isUsable())
4758 return 0;
4759 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004760 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4761 if (!Inc.isUsable())
4762 return 0;
4763
4764 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4765 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004766 // In combined construct, add combined version that use CombLB and CombUB
4767 // base variables for the update
4768 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004769 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4770 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004771 // LB + ST
4772 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4773 if (!NextLB.isUsable())
4774 return 0;
4775 // LB = LB + ST
4776 NextLB =
4777 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4778 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4779 if (!NextLB.isUsable())
4780 return 0;
4781 // UB + ST
4782 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4783 if (!NextUB.isUsable())
4784 return 0;
4785 // UB = UB + ST
4786 NextUB =
4787 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4788 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4789 if (!NextUB.isUsable())
4790 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004791 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4792 CombNextLB =
4793 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4794 if (!NextLB.isUsable())
4795 return 0;
4796 // LB = LB + ST
4797 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4798 CombNextLB.get());
4799 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4800 if (!CombNextLB.isUsable())
4801 return 0;
4802 // UB + ST
4803 CombNextUB =
4804 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4805 if (!CombNextUB.isUsable())
4806 return 0;
4807 // UB = UB + ST
4808 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4809 CombNextUB.get());
4810 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4811 if (!CombNextUB.isUsable())
4812 return 0;
4813 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004814 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004815
Carlo Bertolliffafe102017-04-20 00:39:39 +00004816 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004817 // directive with for as IV = IV + ST; ensure upper bound expression based
4818 // on PrevUB instead of NumIterations - used to implement 'for' when found
4819 // in combination with 'distribute', like in 'distribute parallel for'
4820 SourceLocation DistIncLoc;
4821 ExprResult DistCond, DistInc, PrevEUB;
4822 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4823 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4824 assert(DistCond.isUsable() && "distribute cond expr was not built");
4825
4826 DistInc =
4827 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4828 assert(DistInc.isUsable() && "distribute inc expr was not built");
4829 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4830 DistInc.get());
4831 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4832 assert(DistInc.isUsable() && "distribute inc expr was not built");
4833
4834 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4835 // construct
4836 SourceLocation DistEUBLoc;
4837 ExprResult IsUBGreater =
4838 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4839 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4840 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4841 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4842 CondOp.get());
4843 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4844 }
4845
Alexander Musmana5f070a2014-10-01 06:03:56 +00004846 // Build updates and final values of the loop counters.
4847 bool HasErrors = false;
4848 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004849 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004850 Built.Updates.resize(NestedLoopCount);
4851 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004852 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004853 {
4854 ExprResult Div;
4855 // Go from inner nested loop to outer.
4856 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4857 LoopIterationSpace &IS = IterSpaces[Cnt];
4858 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4859 // Build: Iter = (IV / Div) % IS.NumIters
4860 // where Div is product of previous iterations' IS.NumIters.
4861 ExprResult Iter;
4862 if (Div.isUsable()) {
4863 Iter =
4864 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4865 } else {
4866 Iter = IV;
4867 assert((Cnt == (int)NestedLoopCount - 1) &&
4868 "unusable div expected on first iteration only");
4869 }
4870
4871 if (Cnt != 0 && Iter.isUsable())
4872 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4873 IS.NumIterations);
4874 if (!Iter.isUsable()) {
4875 HasErrors = true;
4876 break;
4877 }
4878
Alexey Bataev39f915b82015-05-08 10:41:21 +00004879 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004880 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4881 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4882 IS.CounterVar->getExprLoc(),
4883 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004884 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004885 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004886 if (!Init.isUsable()) {
4887 HasErrors = true;
4888 break;
4889 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004890 ExprResult Update = BuildCounterUpdate(
4891 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4892 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004893 if (!Update.isUsable()) {
4894 HasErrors = true;
4895 break;
4896 }
4897
4898 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4899 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004900 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004901 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004902 if (!Final.isUsable()) {
4903 HasErrors = true;
4904 break;
4905 }
4906
4907 // Build Div for the next iteration: Div <- Div * IS.NumIters
4908 if (Cnt != 0) {
4909 if (Div.isUnset())
4910 Div = IS.NumIterations;
4911 else
4912 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4913 IS.NumIterations);
4914
4915 // Add parentheses (for debugging purposes only).
4916 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004917 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004918 if (!Div.isUsable()) {
4919 HasErrors = true;
4920 break;
4921 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004922 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004923 }
4924 if (!Update.isUsable() || !Final.isUsable()) {
4925 HasErrors = true;
4926 break;
4927 }
4928 // Save results
4929 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004930 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004931 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004932 Built.Updates[Cnt] = Update.get();
4933 Built.Finals[Cnt] = Final.get();
4934 }
4935 }
4936
4937 if (HasErrors)
4938 return 0;
4939
4940 // Save results
4941 Built.IterationVarRef = IV.get();
4942 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004943 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004944 Built.CalcLastIteration =
4945 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004946 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004947 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004948 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004949 Built.Init = Init.get();
4950 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004951 Built.LB = LB.get();
4952 Built.UB = UB.get();
4953 Built.IL = IL.get();
4954 Built.ST = ST.get();
4955 Built.EUB = EUB.get();
4956 Built.NLB = NextLB.get();
4957 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004958 Built.PrevLB = PrevLB.get();
4959 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004960 Built.DistInc = DistInc.get();
4961 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004962 Built.DistCombinedFields.LB = CombLB.get();
4963 Built.DistCombinedFields.UB = CombUB.get();
4964 Built.DistCombinedFields.EUB = CombEUB.get();
4965 Built.DistCombinedFields.Init = CombInit.get();
4966 Built.DistCombinedFields.Cond = CombCond.get();
4967 Built.DistCombinedFields.NLB = CombNextLB.get();
4968 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004969
Alexey Bataev8b427062016-05-25 12:36:08 +00004970 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4971 // Fill data for doacross depend clauses.
4972 for (auto Pair : DSA.getDoacrossDependClauses()) {
4973 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4974 Pair.first->setCounterValue(CounterVal);
4975 else {
4976 if (NestedLoopCount != Pair.second.size() ||
4977 NestedLoopCount != LoopMultipliers.size() + 1) {
4978 // Erroneous case - clause has some problems.
4979 Pair.first->setCounterValue(CounterVal);
4980 continue;
4981 }
4982 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4983 auto I = Pair.second.rbegin();
4984 auto IS = IterSpaces.rbegin();
4985 auto ILM = LoopMultipliers.rbegin();
4986 Expr *UpCounterVal = CounterVal;
4987 Expr *Multiplier = nullptr;
4988 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4989 if (I->first) {
4990 assert(IS->CounterStep);
4991 Expr *NormalizedOffset =
4992 SemaRef
4993 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4994 I->first, IS->CounterStep)
4995 .get();
4996 if (Multiplier) {
4997 NormalizedOffset =
4998 SemaRef
4999 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5000 NormalizedOffset, Multiplier)
5001 .get();
5002 }
5003 assert(I->second == OO_Plus || I->second == OO_Minus);
5004 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005005 UpCounterVal = SemaRef
5006 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5007 UpCounterVal, NormalizedOffset)
5008 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005009 }
5010 Multiplier = *ILM;
5011 ++I;
5012 ++IS;
5013 ++ILM;
5014 }
5015 Pair.first->setCounterValue(UpCounterVal);
5016 }
5017 }
5018
Alexey Bataevabfc0692014-06-25 06:52:00 +00005019 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005020}
5021
Alexey Bataev10e775f2015-07-30 11:36:16 +00005022static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005023 auto CollapseClauses =
5024 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5025 if (CollapseClauses.begin() != CollapseClauses.end())
5026 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005027 return nullptr;
5028}
5029
Alexey Bataev10e775f2015-07-30 11:36:16 +00005030static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005031 auto OrderedClauses =
5032 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5033 if (OrderedClauses.begin() != OrderedClauses.end())
5034 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005035 return nullptr;
5036}
5037
Kelvin Lic5609492016-07-15 04:39:07 +00005038static bool checkSimdlenSafelenSpecified(Sema &S,
5039 const ArrayRef<OMPClause *> Clauses) {
5040 OMPSafelenClause *Safelen = nullptr;
5041 OMPSimdlenClause *Simdlen = nullptr;
5042
5043 for (auto *Clause : Clauses) {
5044 if (Clause->getClauseKind() == OMPC_safelen)
5045 Safelen = cast<OMPSafelenClause>(Clause);
5046 else if (Clause->getClauseKind() == OMPC_simdlen)
5047 Simdlen = cast<OMPSimdlenClause>(Clause);
5048 if (Safelen && Simdlen)
5049 break;
5050 }
5051
5052 if (Simdlen && Safelen) {
5053 llvm::APSInt SimdlenRes, SafelenRes;
5054 auto SimdlenLength = Simdlen->getSimdlen();
5055 auto SafelenLength = Safelen->getSafelen();
5056 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5057 SimdlenLength->isInstantiationDependent() ||
5058 SimdlenLength->containsUnexpandedParameterPack())
5059 return false;
5060 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5061 SafelenLength->isInstantiationDependent() ||
5062 SafelenLength->containsUnexpandedParameterPack())
5063 return false;
5064 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5065 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5066 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5067 // If both simdlen and safelen clauses are specified, the value of the
5068 // simdlen parameter must be less than or equal to the value of the safelen
5069 // parameter.
5070 if (SimdlenRes > SafelenRes) {
5071 S.Diag(SimdlenLength->getExprLoc(),
5072 diag::err_omp_wrong_simdlen_safelen_values)
5073 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5074 return true;
5075 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005076 }
5077 return false;
5078}
5079
Alexey Bataev4acb8592014-07-07 13:01:15 +00005080StmtResult Sema::ActOnOpenMPSimdDirective(
5081 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5082 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005083 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005084 if (!AStmt)
5085 return StmtError();
5086
5087 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005088 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005089 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5090 // define the nested loops number.
5091 unsigned NestedLoopCount = CheckOpenMPLoop(
5092 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5093 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005094 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005095 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005096
Alexander Musmana5f070a2014-10-01 06:03:56 +00005097 assert((CurContext->isDependentContext() || B.builtAll()) &&
5098 "omp simd loop exprs were not built");
5099
Alexander Musman3276a272015-03-21 10:12:56 +00005100 if (!CurContext->isDependentContext()) {
5101 // Finalize the clauses that need pre-built expressions for CodeGen.
5102 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005103 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005104 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005105 B.NumIterations, *this, CurScope,
5106 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005107 return StmtError();
5108 }
5109 }
5110
Kelvin Lic5609492016-07-15 04:39:07 +00005111 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005112 return StmtError();
5113
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005114 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005115 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5116 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005117}
5118
Alexey Bataev4acb8592014-07-07 13:01:15 +00005119StmtResult Sema::ActOnOpenMPForDirective(
5120 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5121 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005122 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005123 if (!AStmt)
5124 return StmtError();
5125
5126 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005127 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005128 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5129 // define the nested loops number.
5130 unsigned NestedLoopCount = CheckOpenMPLoop(
5131 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5132 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005133 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005134 return StmtError();
5135
Alexander Musmana5f070a2014-10-01 06:03:56 +00005136 assert((CurContext->isDependentContext() || B.builtAll()) &&
5137 "omp for loop exprs were not built");
5138
Alexey Bataev54acd402015-08-04 11:18:19 +00005139 if (!CurContext->isDependentContext()) {
5140 // Finalize the clauses that need pre-built expressions for CodeGen.
5141 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005142 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005143 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005144 B.NumIterations, *this, CurScope,
5145 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005146 return StmtError();
5147 }
5148 }
5149
Alexey Bataevf29276e2014-06-18 04:14:57 +00005150 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005151 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005152 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005153}
5154
Alexander Musmanf82886e2014-09-18 05:12:34 +00005155StmtResult Sema::ActOnOpenMPForSimdDirective(
5156 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5157 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005158 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005159 if (!AStmt)
5160 return StmtError();
5161
5162 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005163 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005164 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5165 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005166 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005167 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5168 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5169 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005170 if (NestedLoopCount == 0)
5171 return StmtError();
5172
Alexander Musmanc6388682014-12-15 07:07:06 +00005173 assert((CurContext->isDependentContext() || B.builtAll()) &&
5174 "omp for simd loop exprs were not built");
5175
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005176 if (!CurContext->isDependentContext()) {
5177 // Finalize the clauses that need pre-built expressions for CodeGen.
5178 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005179 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005180 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005181 B.NumIterations, *this, CurScope,
5182 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005183 return StmtError();
5184 }
5185 }
5186
Kelvin Lic5609492016-07-15 04:39:07 +00005187 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005188 return StmtError();
5189
Alexander Musmanf82886e2014-09-18 05:12:34 +00005190 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005191 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5192 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005193}
5194
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005195StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5196 Stmt *AStmt,
5197 SourceLocation StartLoc,
5198 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005199 if (!AStmt)
5200 return StmtError();
5201
5202 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005203 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005204 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005205 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005206 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005207 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005208 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005209 return StmtError();
5210 // All associated statements must be '#pragma omp section' except for
5211 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005212 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005213 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5214 if (SectionStmt)
5215 Diag(SectionStmt->getLocStart(),
5216 diag::err_omp_sections_substmt_not_section);
5217 return StmtError();
5218 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005219 cast<OMPSectionDirective>(SectionStmt)
5220 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005221 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005222 } else {
5223 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5224 return StmtError();
5225 }
5226
5227 getCurFunction()->setHasBranchProtectedScope();
5228
Alexey Bataev25e5b442015-09-15 12:52:43 +00005229 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5230 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005231}
5232
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005233StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5234 SourceLocation StartLoc,
5235 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005236 if (!AStmt)
5237 return StmtError();
5238
5239 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005240
5241 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005242 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005243
Alexey Bataev25e5b442015-09-15 12:52:43 +00005244 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5245 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005246}
5247
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005248StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5249 Stmt *AStmt,
5250 SourceLocation StartLoc,
5251 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005252 if (!AStmt)
5253 return StmtError();
5254
5255 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005256
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005257 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005258
Alexey Bataev3255bf32015-01-19 05:20:46 +00005259 // OpenMP [2.7.3, single Construct, Restrictions]
5260 // The copyprivate clause must not be used with the nowait clause.
5261 OMPClause *Nowait = nullptr;
5262 OMPClause *Copyprivate = nullptr;
5263 for (auto *Clause : Clauses) {
5264 if (Clause->getClauseKind() == OMPC_nowait)
5265 Nowait = Clause;
5266 else if (Clause->getClauseKind() == OMPC_copyprivate)
5267 Copyprivate = Clause;
5268 if (Copyprivate && Nowait) {
5269 Diag(Copyprivate->getLocStart(),
5270 diag::err_omp_single_copyprivate_with_nowait);
5271 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5272 return StmtError();
5273 }
5274 }
5275
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005276 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5277}
5278
Alexander Musman80c22892014-07-17 08:54:58 +00005279StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5280 SourceLocation StartLoc,
5281 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005282 if (!AStmt)
5283 return StmtError();
5284
5285 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005286
5287 getCurFunction()->setHasBranchProtectedScope();
5288
5289 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5290}
5291
Alexey Bataev28c75412015-12-15 08:19:24 +00005292StmtResult Sema::ActOnOpenMPCriticalDirective(
5293 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5294 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005295 if (!AStmt)
5296 return StmtError();
5297
5298 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005299
Alexey Bataev28c75412015-12-15 08:19:24 +00005300 bool ErrorFound = false;
5301 llvm::APSInt Hint;
5302 SourceLocation HintLoc;
5303 bool DependentHint = false;
5304 for (auto *C : Clauses) {
5305 if (C->getClauseKind() == OMPC_hint) {
5306 if (!DirName.getName()) {
5307 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5308 ErrorFound = true;
5309 }
5310 Expr *E = cast<OMPHintClause>(C)->getHint();
5311 if (E->isTypeDependent() || E->isValueDependent() ||
5312 E->isInstantiationDependent())
5313 DependentHint = true;
5314 else {
5315 Hint = E->EvaluateKnownConstInt(Context);
5316 HintLoc = C->getLocStart();
5317 }
5318 }
5319 }
5320 if (ErrorFound)
5321 return StmtError();
5322 auto Pair = DSAStack->getCriticalWithHint(DirName);
5323 if (Pair.first && DirName.getName() && !DependentHint) {
5324 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5325 Diag(StartLoc, diag::err_omp_critical_with_hint);
5326 if (HintLoc.isValid()) {
5327 Diag(HintLoc, diag::note_omp_critical_hint_here)
5328 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5329 } else
5330 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5331 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5332 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5333 << 1
5334 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5335 /*Radix=*/10, /*Signed=*/false);
5336 } else
5337 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5338 }
5339 }
5340
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005341 getCurFunction()->setHasBranchProtectedScope();
5342
Alexey Bataev28c75412015-12-15 08:19:24 +00005343 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5344 Clauses, AStmt);
5345 if (!Pair.first && DirName.getName() && !DependentHint)
5346 DSAStack->addCriticalWithHint(Dir, Hint);
5347 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005348}
5349
Alexey Bataev4acb8592014-07-07 13:01:15 +00005350StmtResult Sema::ActOnOpenMPParallelForDirective(
5351 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5352 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005353 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005354 if (!AStmt)
5355 return StmtError();
5356
Alexey Bataev4acb8592014-07-07 13:01:15 +00005357 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5358 // 1.2.2 OpenMP Language Terminology
5359 // Structured block - An executable statement with a single entry at the
5360 // top and a single exit at the bottom.
5361 // The point of exit cannot be a branch out of the structured block.
5362 // longjmp() and throw() must not violate the entry/exit criteria.
5363 CS->getCapturedDecl()->setNothrow();
5364
Alexander Musmanc6388682014-12-15 07:07:06 +00005365 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005366 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5367 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005368 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005369 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5370 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5371 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005372 if (NestedLoopCount == 0)
5373 return StmtError();
5374
Alexander Musmana5f070a2014-10-01 06:03:56 +00005375 assert((CurContext->isDependentContext() || B.builtAll()) &&
5376 "omp parallel for loop exprs were not built");
5377
Alexey Bataev54acd402015-08-04 11:18:19 +00005378 if (!CurContext->isDependentContext()) {
5379 // Finalize the clauses that need pre-built expressions for CodeGen.
5380 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005381 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005382 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005383 B.NumIterations, *this, CurScope,
5384 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005385 return StmtError();
5386 }
5387 }
5388
Alexey Bataev4acb8592014-07-07 13:01:15 +00005389 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005390 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005391 NestedLoopCount, Clauses, AStmt, B,
5392 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005393}
5394
Alexander Musmane4e893b2014-09-23 09:33:00 +00005395StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5396 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5397 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005398 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005399 if (!AStmt)
5400 return StmtError();
5401
Alexander Musmane4e893b2014-09-23 09:33:00 +00005402 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5403 // 1.2.2 OpenMP Language Terminology
5404 // Structured block - An executable statement with a single entry at the
5405 // top and a single exit at the bottom.
5406 // The point of exit cannot be a branch out of the structured block.
5407 // longjmp() and throw() must not violate the entry/exit criteria.
5408 CS->getCapturedDecl()->setNothrow();
5409
Alexander Musmanc6388682014-12-15 07:07:06 +00005410 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005411 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5412 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005413 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005414 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5415 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5416 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005417 if (NestedLoopCount == 0)
5418 return StmtError();
5419
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005420 if (!CurContext->isDependentContext()) {
5421 // Finalize the clauses that need pre-built expressions for CodeGen.
5422 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005423 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005424 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005425 B.NumIterations, *this, CurScope,
5426 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005427 return StmtError();
5428 }
5429 }
5430
Kelvin Lic5609492016-07-15 04:39:07 +00005431 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005432 return StmtError();
5433
Alexander Musmane4e893b2014-09-23 09:33:00 +00005434 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005435 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005436 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005437}
5438
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005439StmtResult
5440Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5441 Stmt *AStmt, SourceLocation StartLoc,
5442 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005443 if (!AStmt)
5444 return StmtError();
5445
5446 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005447 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005448 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005449 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005450 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005451 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005452 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005453 return StmtError();
5454 // All associated statements must be '#pragma omp section' except for
5455 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005456 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005457 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5458 if (SectionStmt)
5459 Diag(SectionStmt->getLocStart(),
5460 diag::err_omp_parallel_sections_substmt_not_section);
5461 return StmtError();
5462 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005463 cast<OMPSectionDirective>(SectionStmt)
5464 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005465 }
5466 } else {
5467 Diag(AStmt->getLocStart(),
5468 diag::err_omp_parallel_sections_not_compound_stmt);
5469 return StmtError();
5470 }
5471
5472 getCurFunction()->setHasBranchProtectedScope();
5473
Alexey Bataev25e5b442015-09-15 12:52:43 +00005474 return OMPParallelSectionsDirective::Create(
5475 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005476}
5477
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005478StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5479 Stmt *AStmt, SourceLocation StartLoc,
5480 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005481 if (!AStmt)
5482 return StmtError();
5483
David Majnemer9d168222016-08-05 17:44:54 +00005484 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005485 // 1.2.2 OpenMP Language Terminology
5486 // Structured block - An executable statement with a single entry at the
5487 // top and a single exit at the bottom.
5488 // The point of exit cannot be a branch out of the structured block.
5489 // longjmp() and throw() must not violate the entry/exit criteria.
5490 CS->getCapturedDecl()->setNothrow();
5491
5492 getCurFunction()->setHasBranchProtectedScope();
5493
Alexey Bataev25e5b442015-09-15 12:52:43 +00005494 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5495 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005496}
5497
Alexey Bataev68446b72014-07-18 07:47:19 +00005498StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5499 SourceLocation EndLoc) {
5500 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5501}
5502
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005503StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5504 SourceLocation EndLoc) {
5505 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5506}
5507
Alexey Bataev2df347a2014-07-18 10:17:07 +00005508StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5509 SourceLocation EndLoc) {
5510 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5511}
5512
Alexey Bataev169d96a2017-07-18 20:17:46 +00005513StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5514 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005515 SourceLocation StartLoc,
5516 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005517 if (!AStmt)
5518 return StmtError();
5519
5520 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005521
5522 getCurFunction()->setHasBranchProtectedScope();
5523
Alexey Bataev169d96a2017-07-18 20:17:46 +00005524 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005525 AStmt,
5526 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005527}
5528
Alexey Bataev6125da92014-07-21 11:26:11 +00005529StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5530 SourceLocation StartLoc,
5531 SourceLocation EndLoc) {
5532 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5533 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5534}
5535
Alexey Bataev346265e2015-09-25 10:37:12 +00005536StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5537 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005538 SourceLocation StartLoc,
5539 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005540 OMPClause *DependFound = nullptr;
5541 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005542 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005543 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005544 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005545 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005546 for (auto *C : Clauses) {
5547 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5548 DependFound = C;
5549 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5550 if (DependSourceClause) {
5551 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5552 << getOpenMPDirectiveName(OMPD_ordered)
5553 << getOpenMPClauseName(OMPC_depend) << 2;
5554 ErrorFound = true;
5555 } else
5556 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005557 if (DependSinkClause) {
5558 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5559 << 0;
5560 ErrorFound = true;
5561 }
5562 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5563 if (DependSourceClause) {
5564 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5565 << 1;
5566 ErrorFound = true;
5567 }
5568 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005569 }
5570 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005571 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005572 else if (C->getClauseKind() == OMPC_simd)
5573 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005574 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005575 if (!ErrorFound && !SC &&
5576 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005577 // OpenMP [2.8.1,simd Construct, Restrictions]
5578 // An ordered construct with the simd clause is the only OpenMP construct
5579 // that can appear in the simd region.
5580 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005581 ErrorFound = true;
5582 } else if (DependFound && (TC || SC)) {
5583 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5584 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5585 ErrorFound = true;
5586 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5587 Diag(DependFound->getLocStart(),
5588 diag::err_omp_ordered_directive_without_param);
5589 ErrorFound = true;
5590 } else if (TC || Clauses.empty()) {
5591 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5592 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5593 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5594 << (TC != nullptr);
5595 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5596 ErrorFound = true;
5597 }
5598 }
5599 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005600 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005601
5602 if (AStmt) {
5603 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5604
5605 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005606 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005607
5608 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005609}
5610
Alexey Bataev1d160b12015-03-13 12:27:31 +00005611namespace {
5612/// \brief Helper class for checking expression in 'omp atomic [update]'
5613/// construct.
5614class OpenMPAtomicUpdateChecker {
5615 /// \brief Error results for atomic update expressions.
5616 enum ExprAnalysisErrorCode {
5617 /// \brief A statement is not an expression statement.
5618 NotAnExpression,
5619 /// \brief Expression is not builtin binary or unary operation.
5620 NotABinaryOrUnaryExpression,
5621 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5622 NotAnUnaryIncDecExpression,
5623 /// \brief An expression is not of scalar type.
5624 NotAScalarType,
5625 /// \brief A binary operation is not an assignment operation.
5626 NotAnAssignmentOp,
5627 /// \brief RHS part of the binary operation is not a binary expression.
5628 NotABinaryExpression,
5629 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5630 /// expression.
5631 NotABinaryOperator,
5632 /// \brief RHS binary operation does not have reference to the updated LHS
5633 /// part.
5634 NotAnUpdateExpression,
5635 /// \brief No errors is found.
5636 NoError
5637 };
5638 /// \brief Reference to Sema.
5639 Sema &SemaRef;
5640 /// \brief A location for note diagnostics (when error is found).
5641 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005642 /// \brief 'x' lvalue part of the source atomic expression.
5643 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005644 /// \brief 'expr' rvalue part of the source atomic expression.
5645 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005646 /// \brief Helper expression of the form
5647 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5648 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5649 Expr *UpdateExpr;
5650 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5651 /// important for non-associative operations.
5652 bool IsXLHSInRHSPart;
5653 BinaryOperatorKind Op;
5654 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005655 /// \brief true if the source expression is a postfix unary operation, false
5656 /// if it is a prefix unary operation.
5657 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005658
5659public:
5660 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005661 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005662 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005663 /// \brief Check specified statement that it is suitable for 'atomic update'
5664 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005665 /// expression. If DiagId and NoteId == 0, then only check is performed
5666 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005667 /// \param DiagId Diagnostic which should be emitted if error is found.
5668 /// \param NoteId Diagnostic note for the main error message.
5669 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005670 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005671 /// \brief Return the 'x' lvalue part of the source atomic expression.
5672 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005673 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5674 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005675 /// \brief Return the update expression used in calculation of the updated
5676 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5677 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5678 Expr *getUpdateExpr() const { return UpdateExpr; }
5679 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5680 /// false otherwise.
5681 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5682
Alexey Bataevb78ca832015-04-01 03:33:17 +00005683 /// \brief true if the source expression is a postfix unary operation, false
5684 /// if it is a prefix unary operation.
5685 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5686
Alexey Bataev1d160b12015-03-13 12:27:31 +00005687private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005688 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5689 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005690};
5691} // namespace
5692
5693bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5694 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5695 ExprAnalysisErrorCode ErrorFound = NoError;
5696 SourceLocation ErrorLoc, NoteLoc;
5697 SourceRange ErrorRange, NoteRange;
5698 // Allowed constructs are:
5699 // x = x binop expr;
5700 // x = expr binop x;
5701 if (AtomicBinOp->getOpcode() == BO_Assign) {
5702 X = AtomicBinOp->getLHS();
5703 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5704 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5705 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5706 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5707 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005708 Op = AtomicInnerBinOp->getOpcode();
5709 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005710 auto *LHS = AtomicInnerBinOp->getLHS();
5711 auto *RHS = AtomicInnerBinOp->getRHS();
5712 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5713 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5714 /*Canonical=*/true);
5715 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5716 /*Canonical=*/true);
5717 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5718 /*Canonical=*/true);
5719 if (XId == LHSId) {
5720 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005721 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005722 } else if (XId == RHSId) {
5723 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005724 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005725 } else {
5726 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5727 ErrorRange = AtomicInnerBinOp->getSourceRange();
5728 NoteLoc = X->getExprLoc();
5729 NoteRange = X->getSourceRange();
5730 ErrorFound = NotAnUpdateExpression;
5731 }
5732 } else {
5733 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5734 ErrorRange = AtomicInnerBinOp->getSourceRange();
5735 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5736 NoteRange = SourceRange(NoteLoc, NoteLoc);
5737 ErrorFound = NotABinaryOperator;
5738 }
5739 } else {
5740 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5741 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5742 ErrorFound = NotABinaryExpression;
5743 }
5744 } else {
5745 ErrorLoc = AtomicBinOp->getExprLoc();
5746 ErrorRange = AtomicBinOp->getSourceRange();
5747 NoteLoc = AtomicBinOp->getOperatorLoc();
5748 NoteRange = SourceRange(NoteLoc, NoteLoc);
5749 ErrorFound = NotAnAssignmentOp;
5750 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005751 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005752 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5753 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5754 return true;
5755 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005756 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005757 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005758}
5759
5760bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5761 unsigned NoteId) {
5762 ExprAnalysisErrorCode ErrorFound = NoError;
5763 SourceLocation ErrorLoc, NoteLoc;
5764 SourceRange ErrorRange, NoteRange;
5765 // Allowed constructs are:
5766 // x++;
5767 // x--;
5768 // ++x;
5769 // --x;
5770 // x binop= expr;
5771 // x = x binop expr;
5772 // x = expr binop x;
5773 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5774 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5775 if (AtomicBody->getType()->isScalarType() ||
5776 AtomicBody->isInstantiationDependent()) {
5777 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5778 AtomicBody->IgnoreParenImpCasts())) {
5779 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005780 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005781 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005782 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005783 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005784 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005785 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005786 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5787 AtomicBody->IgnoreParenImpCasts())) {
5788 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005789 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005790 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005791 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5792 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005793 // Check for Unary Operation
5794 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005795 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005796 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5797 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005798 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005799 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5800 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005801 } else {
5802 ErrorFound = NotAnUnaryIncDecExpression;
5803 ErrorLoc = AtomicUnaryOp->getExprLoc();
5804 ErrorRange = AtomicUnaryOp->getSourceRange();
5805 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5806 NoteRange = SourceRange(NoteLoc, NoteLoc);
5807 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005808 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005809 ErrorFound = NotABinaryOrUnaryExpression;
5810 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5811 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5812 }
5813 } else {
5814 ErrorFound = NotAScalarType;
5815 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5816 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5817 }
5818 } else {
5819 ErrorFound = NotAnExpression;
5820 NoteLoc = ErrorLoc = S->getLocStart();
5821 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5822 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005823 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005824 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5825 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5826 return true;
5827 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005828 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005829 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005830 // Build an update expression of form 'OpaqueValueExpr(x) binop
5831 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5832 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5833 auto *OVEX = new (SemaRef.getASTContext())
5834 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5835 auto *OVEExpr = new (SemaRef.getASTContext())
5836 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5837 auto Update =
5838 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5839 IsXLHSInRHSPart ? OVEExpr : OVEX);
5840 if (Update.isInvalid())
5841 return true;
5842 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5843 Sema::AA_Casting);
5844 if (Update.isInvalid())
5845 return true;
5846 UpdateExpr = Update.get();
5847 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005848 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005849}
5850
Alexey Bataev0162e452014-07-22 10:10:35 +00005851StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5852 Stmt *AStmt,
5853 SourceLocation StartLoc,
5854 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005855 if (!AStmt)
5856 return StmtError();
5857
David Majnemer9d168222016-08-05 17:44:54 +00005858 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005859 // 1.2.2 OpenMP Language Terminology
5860 // Structured block - An executable statement with a single entry at the
5861 // top and a single exit at the bottom.
5862 // The point of exit cannot be a branch out of the structured block.
5863 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005864 OpenMPClauseKind AtomicKind = OMPC_unknown;
5865 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005866 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005867 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005868 C->getClauseKind() == OMPC_update ||
5869 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005870 if (AtomicKind != OMPC_unknown) {
5871 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5872 << SourceRange(C->getLocStart(), C->getLocEnd());
5873 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5874 << getOpenMPClauseName(AtomicKind);
5875 } else {
5876 AtomicKind = C->getClauseKind();
5877 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005878 }
5879 }
5880 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005881
Alexey Bataev459dec02014-07-24 06:46:57 +00005882 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005883 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5884 Body = EWC->getSubExpr();
5885
Alexey Bataev62cec442014-11-18 10:14:22 +00005886 Expr *X = nullptr;
5887 Expr *V = nullptr;
5888 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005889 Expr *UE = nullptr;
5890 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005891 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005892 // OpenMP [2.12.6, atomic Construct]
5893 // In the next expressions:
5894 // * x and v (as applicable) are both l-value expressions with scalar type.
5895 // * During the execution of an atomic region, multiple syntactic
5896 // occurrences of x must designate the same storage location.
5897 // * Neither of v and expr (as applicable) may access the storage location
5898 // designated by x.
5899 // * Neither of x and expr (as applicable) may access the storage location
5900 // designated by v.
5901 // * expr is an expression with scalar type.
5902 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5903 // * binop, binop=, ++, and -- are not overloaded operators.
5904 // * The expression x binop expr must be numerically equivalent to x binop
5905 // (expr). This requirement is satisfied if the operators in expr have
5906 // precedence greater than binop, or by using parentheses around expr or
5907 // subexpressions of expr.
5908 // * The expression expr binop x must be numerically equivalent to (expr)
5909 // binop x. This requirement is satisfied if the operators in expr have
5910 // precedence equal to or greater than binop, or by using parentheses around
5911 // expr or subexpressions of expr.
5912 // * For forms that allow multiple occurrences of x, the number of times
5913 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005914 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005915 enum {
5916 NotAnExpression,
5917 NotAnAssignmentOp,
5918 NotAScalarType,
5919 NotAnLValue,
5920 NoError
5921 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005922 SourceLocation ErrorLoc, NoteLoc;
5923 SourceRange ErrorRange, NoteRange;
5924 // If clause is read:
5925 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005926 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5927 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005928 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5929 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5930 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5931 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5932 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5933 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5934 if (!X->isLValue() || !V->isLValue()) {
5935 auto NotLValueExpr = X->isLValue() ? V : X;
5936 ErrorFound = NotAnLValue;
5937 ErrorLoc = AtomicBinOp->getExprLoc();
5938 ErrorRange = AtomicBinOp->getSourceRange();
5939 NoteLoc = NotLValueExpr->getExprLoc();
5940 NoteRange = NotLValueExpr->getSourceRange();
5941 }
5942 } else if (!X->isInstantiationDependent() ||
5943 !V->isInstantiationDependent()) {
5944 auto NotScalarExpr =
5945 (X->isInstantiationDependent() || X->getType()->isScalarType())
5946 ? V
5947 : X;
5948 ErrorFound = NotAScalarType;
5949 ErrorLoc = AtomicBinOp->getExprLoc();
5950 ErrorRange = AtomicBinOp->getSourceRange();
5951 NoteLoc = NotScalarExpr->getExprLoc();
5952 NoteRange = NotScalarExpr->getSourceRange();
5953 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005954 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005955 ErrorFound = NotAnAssignmentOp;
5956 ErrorLoc = AtomicBody->getExprLoc();
5957 ErrorRange = AtomicBody->getSourceRange();
5958 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5959 : AtomicBody->getExprLoc();
5960 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5961 : AtomicBody->getSourceRange();
5962 }
5963 } else {
5964 ErrorFound = NotAnExpression;
5965 NoteLoc = ErrorLoc = Body->getLocStart();
5966 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005967 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005968 if (ErrorFound != NoError) {
5969 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5970 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005971 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5972 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005973 return StmtError();
5974 } else if (CurContext->isDependentContext())
5975 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005976 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005977 enum {
5978 NotAnExpression,
5979 NotAnAssignmentOp,
5980 NotAScalarType,
5981 NotAnLValue,
5982 NoError
5983 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005984 SourceLocation ErrorLoc, NoteLoc;
5985 SourceRange ErrorRange, NoteRange;
5986 // If clause is write:
5987 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005988 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5989 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005990 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5991 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005992 X = AtomicBinOp->getLHS();
5993 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005994 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5995 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5996 if (!X->isLValue()) {
5997 ErrorFound = NotAnLValue;
5998 ErrorLoc = AtomicBinOp->getExprLoc();
5999 ErrorRange = AtomicBinOp->getSourceRange();
6000 NoteLoc = X->getExprLoc();
6001 NoteRange = X->getSourceRange();
6002 }
6003 } else if (!X->isInstantiationDependent() ||
6004 !E->isInstantiationDependent()) {
6005 auto NotScalarExpr =
6006 (X->isInstantiationDependent() || X->getType()->isScalarType())
6007 ? E
6008 : X;
6009 ErrorFound = NotAScalarType;
6010 ErrorLoc = AtomicBinOp->getExprLoc();
6011 ErrorRange = AtomicBinOp->getSourceRange();
6012 NoteLoc = NotScalarExpr->getExprLoc();
6013 NoteRange = NotScalarExpr->getSourceRange();
6014 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006015 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006016 ErrorFound = NotAnAssignmentOp;
6017 ErrorLoc = AtomicBody->getExprLoc();
6018 ErrorRange = AtomicBody->getSourceRange();
6019 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6020 : AtomicBody->getExprLoc();
6021 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6022 : AtomicBody->getSourceRange();
6023 }
6024 } else {
6025 ErrorFound = NotAnExpression;
6026 NoteLoc = ErrorLoc = Body->getLocStart();
6027 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006028 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006029 if (ErrorFound != NoError) {
6030 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6031 << ErrorRange;
6032 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6033 << NoteRange;
6034 return StmtError();
6035 } else if (CurContext->isDependentContext())
6036 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006037 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006038 // If clause is update:
6039 // x++;
6040 // x--;
6041 // ++x;
6042 // --x;
6043 // x binop= expr;
6044 // x = x binop expr;
6045 // x = expr binop x;
6046 OpenMPAtomicUpdateChecker Checker(*this);
6047 if (Checker.checkStatement(
6048 Body, (AtomicKind == OMPC_update)
6049 ? diag::err_omp_atomic_update_not_expression_statement
6050 : diag::err_omp_atomic_not_expression_statement,
6051 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006052 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006053 if (!CurContext->isDependentContext()) {
6054 E = Checker.getExpr();
6055 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006056 UE = Checker.getUpdateExpr();
6057 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006058 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006059 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006060 enum {
6061 NotAnAssignmentOp,
6062 NotACompoundStatement,
6063 NotTwoSubstatements,
6064 NotASpecificExpression,
6065 NoError
6066 } ErrorFound = NoError;
6067 SourceLocation ErrorLoc, NoteLoc;
6068 SourceRange ErrorRange, NoteRange;
6069 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6070 // If clause is a capture:
6071 // v = x++;
6072 // v = x--;
6073 // v = ++x;
6074 // v = --x;
6075 // v = x binop= expr;
6076 // v = x = x binop expr;
6077 // v = x = expr binop x;
6078 auto *AtomicBinOp =
6079 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6080 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6081 V = AtomicBinOp->getLHS();
6082 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6083 OpenMPAtomicUpdateChecker Checker(*this);
6084 if (Checker.checkStatement(
6085 Body, diag::err_omp_atomic_capture_not_expression_statement,
6086 diag::note_omp_atomic_update))
6087 return StmtError();
6088 E = Checker.getExpr();
6089 X = Checker.getX();
6090 UE = Checker.getUpdateExpr();
6091 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6092 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006093 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006094 ErrorLoc = AtomicBody->getExprLoc();
6095 ErrorRange = AtomicBody->getSourceRange();
6096 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6097 : AtomicBody->getExprLoc();
6098 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6099 : AtomicBody->getSourceRange();
6100 ErrorFound = NotAnAssignmentOp;
6101 }
6102 if (ErrorFound != NoError) {
6103 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6104 << ErrorRange;
6105 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6106 return StmtError();
6107 } else if (CurContext->isDependentContext()) {
6108 UE = V = E = X = nullptr;
6109 }
6110 } else {
6111 // If clause is a capture:
6112 // { v = x; x = expr; }
6113 // { v = x; x++; }
6114 // { v = x; x--; }
6115 // { v = x; ++x; }
6116 // { v = x; --x; }
6117 // { v = x; x binop= expr; }
6118 // { v = x; x = x binop expr; }
6119 // { v = x; x = expr binop x; }
6120 // { x++; v = x; }
6121 // { x--; v = x; }
6122 // { ++x; v = x; }
6123 // { --x; v = x; }
6124 // { x binop= expr; v = x; }
6125 // { x = x binop expr; v = x; }
6126 // { x = expr binop x; v = x; }
6127 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6128 // Check that this is { expr1; expr2; }
6129 if (CS->size() == 2) {
6130 auto *First = CS->body_front();
6131 auto *Second = CS->body_back();
6132 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6133 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6134 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6135 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6136 // Need to find what subexpression is 'v' and what is 'x'.
6137 OpenMPAtomicUpdateChecker Checker(*this);
6138 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6139 BinaryOperator *BinOp = nullptr;
6140 if (IsUpdateExprFound) {
6141 BinOp = dyn_cast<BinaryOperator>(First);
6142 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6143 }
6144 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6145 // { v = x; x++; }
6146 // { v = x; x--; }
6147 // { v = x; ++x; }
6148 // { v = x; --x; }
6149 // { v = x; x binop= expr; }
6150 // { v = x; x = x binop expr; }
6151 // { v = x; x = expr binop x; }
6152 // Check that the first expression has form v = x.
6153 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6154 llvm::FoldingSetNodeID XId, PossibleXId;
6155 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6156 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6157 IsUpdateExprFound = XId == PossibleXId;
6158 if (IsUpdateExprFound) {
6159 V = BinOp->getLHS();
6160 X = Checker.getX();
6161 E = Checker.getExpr();
6162 UE = Checker.getUpdateExpr();
6163 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006164 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006165 }
6166 }
6167 if (!IsUpdateExprFound) {
6168 IsUpdateExprFound = !Checker.checkStatement(First);
6169 BinOp = nullptr;
6170 if (IsUpdateExprFound) {
6171 BinOp = dyn_cast<BinaryOperator>(Second);
6172 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6173 }
6174 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6175 // { x++; v = x; }
6176 // { x--; v = x; }
6177 // { ++x; v = x; }
6178 // { --x; v = x; }
6179 // { x binop= expr; v = x; }
6180 // { x = x binop expr; v = x; }
6181 // { x = expr binop x; v = x; }
6182 // Check that the second expression has form v = x.
6183 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6184 llvm::FoldingSetNodeID XId, PossibleXId;
6185 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6186 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6187 IsUpdateExprFound = XId == PossibleXId;
6188 if (IsUpdateExprFound) {
6189 V = BinOp->getLHS();
6190 X = Checker.getX();
6191 E = Checker.getExpr();
6192 UE = Checker.getUpdateExpr();
6193 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006194 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006195 }
6196 }
6197 }
6198 if (!IsUpdateExprFound) {
6199 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006200 auto *FirstExpr = dyn_cast<Expr>(First);
6201 auto *SecondExpr = dyn_cast<Expr>(Second);
6202 if (!FirstExpr || !SecondExpr ||
6203 !(FirstExpr->isInstantiationDependent() ||
6204 SecondExpr->isInstantiationDependent())) {
6205 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6206 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006207 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006208 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6209 : First->getLocStart();
6210 NoteRange = ErrorRange = FirstBinOp
6211 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006212 : SourceRange(ErrorLoc, ErrorLoc);
6213 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006214 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6215 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6216 ErrorFound = NotAnAssignmentOp;
6217 NoteLoc = ErrorLoc = SecondBinOp
6218 ? SecondBinOp->getOperatorLoc()
6219 : Second->getLocStart();
6220 NoteRange = ErrorRange =
6221 SecondBinOp ? SecondBinOp->getSourceRange()
6222 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006223 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006224 auto *PossibleXRHSInFirst =
6225 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6226 auto *PossibleXLHSInSecond =
6227 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6228 llvm::FoldingSetNodeID X1Id, X2Id;
6229 PossibleXRHSInFirst->Profile(X1Id, Context,
6230 /*Canonical=*/true);
6231 PossibleXLHSInSecond->Profile(X2Id, Context,
6232 /*Canonical=*/true);
6233 IsUpdateExprFound = X1Id == X2Id;
6234 if (IsUpdateExprFound) {
6235 V = FirstBinOp->getLHS();
6236 X = SecondBinOp->getLHS();
6237 E = SecondBinOp->getRHS();
6238 UE = nullptr;
6239 IsXLHSInRHSPart = false;
6240 IsPostfixUpdate = true;
6241 } else {
6242 ErrorFound = NotASpecificExpression;
6243 ErrorLoc = FirstBinOp->getExprLoc();
6244 ErrorRange = FirstBinOp->getSourceRange();
6245 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6246 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6247 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006248 }
6249 }
6250 }
6251 }
6252 } else {
6253 NoteLoc = ErrorLoc = Body->getLocStart();
6254 NoteRange = ErrorRange =
6255 SourceRange(Body->getLocStart(), Body->getLocStart());
6256 ErrorFound = NotTwoSubstatements;
6257 }
6258 } else {
6259 NoteLoc = ErrorLoc = Body->getLocStart();
6260 NoteRange = ErrorRange =
6261 SourceRange(Body->getLocStart(), Body->getLocStart());
6262 ErrorFound = NotACompoundStatement;
6263 }
6264 if (ErrorFound != NoError) {
6265 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6266 << ErrorRange;
6267 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6268 return StmtError();
6269 } else if (CurContext->isDependentContext()) {
6270 UE = V = E = X = nullptr;
6271 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006272 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006273 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006274
6275 getCurFunction()->setHasBranchProtectedScope();
6276
Alexey Bataev62cec442014-11-18 10:14:22 +00006277 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006278 X, V, E, UE, IsXLHSInRHSPart,
6279 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006280}
6281
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006282StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6283 Stmt *AStmt,
6284 SourceLocation StartLoc,
6285 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006286 if (!AStmt)
6287 return StmtError();
6288
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006289 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6290 // 1.2.2 OpenMP Language Terminology
6291 // Structured block - An executable statement with a single entry at the
6292 // top and a single exit at the bottom.
6293 // The point of exit cannot be a branch out of the structured block.
6294 // longjmp() and throw() must not violate the entry/exit criteria.
6295 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006296
Alexey Bataev13314bf2014-10-09 04:18:56 +00006297 // OpenMP [2.16, Nesting of Regions]
6298 // If specified, a teams construct must be contained within a target
6299 // construct. That target construct must contain no statements or directives
6300 // outside of the teams construct.
6301 if (DSAStack->hasInnerTeamsRegion()) {
6302 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6303 bool OMPTeamsFound = true;
6304 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6305 auto I = CS->body_begin();
6306 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006307 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006308 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6309 OMPTeamsFound = false;
6310 break;
6311 }
6312 ++I;
6313 }
6314 assert(I != CS->body_end() && "Not found statement");
6315 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006316 } else {
6317 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6318 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006319 }
6320 if (!OMPTeamsFound) {
6321 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6322 Diag(DSAStack->getInnerTeamsRegionLoc(),
6323 diag::note_omp_nested_teams_construct_here);
6324 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6325 << isa<OMPExecutableDirective>(S);
6326 return StmtError();
6327 }
6328 }
6329
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006330 getCurFunction()->setHasBranchProtectedScope();
6331
6332 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6333}
6334
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006335StmtResult
6336Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6337 Stmt *AStmt, SourceLocation StartLoc,
6338 SourceLocation EndLoc) {
6339 if (!AStmt)
6340 return StmtError();
6341
6342 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6343 // 1.2.2 OpenMP Language Terminology
6344 // Structured block - An executable statement with a single entry at the
6345 // top and a single exit at the bottom.
6346 // The point of exit cannot be a branch out of the structured block.
6347 // longjmp() and throw() must not violate the entry/exit criteria.
6348 CS->getCapturedDecl()->setNothrow();
6349
6350 getCurFunction()->setHasBranchProtectedScope();
6351
6352 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6353 AStmt);
6354}
6355
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006356StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6357 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6358 SourceLocation EndLoc,
6359 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6360 if (!AStmt)
6361 return StmtError();
6362
6363 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6364 // 1.2.2 OpenMP Language Terminology
6365 // Structured block - An executable statement with a single entry at the
6366 // top and a single exit at the bottom.
6367 // The point of exit cannot be a branch out of the structured block.
6368 // longjmp() and throw() must not violate the entry/exit criteria.
6369 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006370 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6371 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6372 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6373 // 1.2.2 OpenMP Language Terminology
6374 // Structured block - An executable statement with a single entry at the
6375 // top and a single exit at the bottom.
6376 // The point of exit cannot be a branch out of the structured block.
6377 // longjmp() and throw() must not violate the entry/exit criteria.
6378 CS->getCapturedDecl()->setNothrow();
6379 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006380
6381 OMPLoopDirective::HelperExprs B;
6382 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6383 // define the nested loops number.
6384 unsigned NestedLoopCount =
6385 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006386 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006387 VarsWithImplicitDSA, B);
6388 if (NestedLoopCount == 0)
6389 return StmtError();
6390
6391 assert((CurContext->isDependentContext() || B.builtAll()) &&
6392 "omp target parallel for loop exprs were not built");
6393
6394 if (!CurContext->isDependentContext()) {
6395 // Finalize the clauses that need pre-built expressions for CodeGen.
6396 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006397 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006398 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006399 B.NumIterations, *this, CurScope,
6400 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006401 return StmtError();
6402 }
6403 }
6404
6405 getCurFunction()->setHasBranchProtectedScope();
6406 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6407 NestedLoopCount, Clauses, AStmt,
6408 B, DSAStack->isCancelRegion());
6409}
6410
Alexey Bataev95b64a92017-05-30 16:00:04 +00006411/// Check for existence of a map clause in the list of clauses.
6412static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6413 const OpenMPClauseKind K) {
6414 return llvm::any_of(
6415 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6416}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006417
Alexey Bataev95b64a92017-05-30 16:00:04 +00006418template <typename... Params>
6419static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6420 const Params... ClauseTypes) {
6421 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006422}
6423
Michael Wong65f367f2015-07-21 13:44:28 +00006424StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6425 Stmt *AStmt,
6426 SourceLocation StartLoc,
6427 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006428 if (!AStmt)
6429 return StmtError();
6430
6431 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6432
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006433 // OpenMP [2.10.1, Restrictions, p. 97]
6434 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006435 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6436 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6437 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006438 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006439 return StmtError();
6440 }
6441
Michael Wong65f367f2015-07-21 13:44:28 +00006442 getCurFunction()->setHasBranchProtectedScope();
6443
6444 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6445 AStmt);
6446}
6447
Samuel Antaodf67fc42016-01-19 19:15:56 +00006448StmtResult
6449Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6450 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006451 SourceLocation EndLoc, Stmt *AStmt) {
6452 if (!AStmt)
6453 return StmtError();
6454
6455 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6456 // 1.2.2 OpenMP Language Terminology
6457 // Structured block - An executable statement with a single entry at the
6458 // top and a single exit at the bottom.
6459 // The point of exit cannot be a branch out of the structured block.
6460 // longjmp() and throw() must not violate the entry/exit criteria.
6461 CS->getCapturedDecl()->setNothrow();
6462 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6463 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6464 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6465 // 1.2.2 OpenMP Language Terminology
6466 // Structured block - An executable statement with a single entry at the
6467 // top and a single exit at the bottom.
6468 // The point of exit cannot be a branch out of the structured block.
6469 // longjmp() and throw() must not violate the entry/exit criteria.
6470 CS->getCapturedDecl()->setNothrow();
6471 }
6472
Samuel Antaodf67fc42016-01-19 19:15:56 +00006473 // OpenMP [2.10.2, Restrictions, p. 99]
6474 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006475 if (!hasClauses(Clauses, OMPC_map)) {
6476 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6477 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006478 return StmtError();
6479 }
6480
Alexey Bataev7828b252017-11-21 17:08:48 +00006481 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6482 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006483}
6484
Samuel Antao72590762016-01-19 20:04:50 +00006485StmtResult
6486Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6487 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006488 SourceLocation EndLoc, Stmt *AStmt) {
6489 if (!AStmt)
6490 return StmtError();
6491
6492 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6493 // 1.2.2 OpenMP Language Terminology
6494 // Structured block - An executable statement with a single entry at the
6495 // top and a single exit at the bottom.
6496 // The point of exit cannot be a branch out of the structured block.
6497 // longjmp() and throw() must not violate the entry/exit criteria.
6498 CS->getCapturedDecl()->setNothrow();
6499 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6500 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6501 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6502 // 1.2.2 OpenMP Language Terminology
6503 // Structured block - An executable statement with a single entry at the
6504 // top and a single exit at the bottom.
6505 // The point of exit cannot be a branch out of the structured block.
6506 // longjmp() and throw() must not violate the entry/exit criteria.
6507 CS->getCapturedDecl()->setNothrow();
6508 }
6509
Samuel Antao72590762016-01-19 20:04:50 +00006510 // OpenMP [2.10.3, Restrictions, p. 102]
6511 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006512 if (!hasClauses(Clauses, OMPC_map)) {
6513 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6514 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006515 return StmtError();
6516 }
6517
Alexey Bataev7828b252017-11-21 17:08:48 +00006518 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6519 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006520}
6521
Samuel Antao686c70c2016-05-26 17:30:50 +00006522StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6523 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006524 SourceLocation EndLoc,
6525 Stmt *AStmt) {
6526 if (!AStmt)
6527 return StmtError();
6528
6529 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6530 // 1.2.2 OpenMP Language Terminology
6531 // Structured block - An executable statement with a single entry at the
6532 // top and a single exit at the bottom.
6533 // The point of exit cannot be a branch out of the structured block.
6534 // longjmp() and throw() must not violate the entry/exit criteria.
6535 CS->getCapturedDecl()->setNothrow();
6536 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6537 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6538 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6539 // 1.2.2 OpenMP Language Terminology
6540 // Structured block - An executable statement with a single entry at the
6541 // top and a single exit at the bottom.
6542 // The point of exit cannot be a branch out of the structured block.
6543 // longjmp() and throw() must not violate the entry/exit criteria.
6544 CS->getCapturedDecl()->setNothrow();
6545 }
6546
Alexey Bataev95b64a92017-05-30 16:00:04 +00006547 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006548 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6549 return StmtError();
6550 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006551 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6552 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006553}
6554
Alexey Bataev13314bf2014-10-09 04:18:56 +00006555StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6556 Stmt *AStmt, SourceLocation StartLoc,
6557 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006558 if (!AStmt)
6559 return StmtError();
6560
Alexey Bataev13314bf2014-10-09 04:18:56 +00006561 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6562 // 1.2.2 OpenMP Language Terminology
6563 // Structured block - An executable statement with a single entry at the
6564 // top and a single exit at the bottom.
6565 // The point of exit cannot be a branch out of the structured block.
6566 // longjmp() and throw() must not violate the entry/exit criteria.
6567 CS->getCapturedDecl()->setNothrow();
6568
6569 getCurFunction()->setHasBranchProtectedScope();
6570
Alexey Bataevceabd412017-11-30 18:01:54 +00006571 DSAStack->setParentTeamsRegionLoc(StartLoc);
6572
Alexey Bataev13314bf2014-10-09 04:18:56 +00006573 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6574}
6575
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006576StmtResult
6577Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6578 SourceLocation EndLoc,
6579 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006580 if (DSAStack->isParentNowaitRegion()) {
6581 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6582 return StmtError();
6583 }
6584 if (DSAStack->isParentOrderedRegion()) {
6585 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6586 return StmtError();
6587 }
6588 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6589 CancelRegion);
6590}
6591
Alexey Bataev87933c72015-09-18 08:07:34 +00006592StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6593 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006594 SourceLocation EndLoc,
6595 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006596 if (DSAStack->isParentNowaitRegion()) {
6597 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6598 return StmtError();
6599 }
6600 if (DSAStack->isParentOrderedRegion()) {
6601 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6602 return StmtError();
6603 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006604 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006605 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6606 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006607}
6608
Alexey Bataev382967a2015-12-08 12:06:20 +00006609static bool checkGrainsizeNumTasksClauses(Sema &S,
6610 ArrayRef<OMPClause *> Clauses) {
6611 OMPClause *PrevClause = nullptr;
6612 bool ErrorFound = false;
6613 for (auto *C : Clauses) {
6614 if (C->getClauseKind() == OMPC_grainsize ||
6615 C->getClauseKind() == OMPC_num_tasks) {
6616 if (!PrevClause)
6617 PrevClause = C;
6618 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6619 S.Diag(C->getLocStart(),
6620 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6621 << getOpenMPClauseName(C->getClauseKind())
6622 << getOpenMPClauseName(PrevClause->getClauseKind());
6623 S.Diag(PrevClause->getLocStart(),
6624 diag::note_omp_previous_grainsize_num_tasks)
6625 << getOpenMPClauseName(PrevClause->getClauseKind());
6626 ErrorFound = true;
6627 }
6628 }
6629 }
6630 return ErrorFound;
6631}
6632
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006633static bool checkReductionClauseWithNogroup(Sema &S,
6634 ArrayRef<OMPClause *> Clauses) {
6635 OMPClause *ReductionClause = nullptr;
6636 OMPClause *NogroupClause = nullptr;
6637 for (auto *C : Clauses) {
6638 if (C->getClauseKind() == OMPC_reduction) {
6639 ReductionClause = C;
6640 if (NogroupClause)
6641 break;
6642 continue;
6643 }
6644 if (C->getClauseKind() == OMPC_nogroup) {
6645 NogroupClause = C;
6646 if (ReductionClause)
6647 break;
6648 continue;
6649 }
6650 }
6651 if (ReductionClause && NogroupClause) {
6652 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6653 << SourceRange(NogroupClause->getLocStart(),
6654 NogroupClause->getLocEnd());
6655 return true;
6656 }
6657 return false;
6658}
6659
Alexey Bataev49f6e782015-12-01 04:18:41 +00006660StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6661 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6662 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006663 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006664 if (!AStmt)
6665 return StmtError();
6666
6667 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6668 OMPLoopDirective::HelperExprs B;
6669 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6670 // define the nested loops number.
6671 unsigned NestedLoopCount =
6672 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006673 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006674 VarsWithImplicitDSA, B);
6675 if (NestedLoopCount == 0)
6676 return StmtError();
6677
6678 assert((CurContext->isDependentContext() || B.builtAll()) &&
6679 "omp for loop exprs were not built");
6680
Alexey Bataev382967a2015-12-08 12:06:20 +00006681 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6682 // The grainsize clause and num_tasks clause are mutually exclusive and may
6683 // not appear on the same taskloop directive.
6684 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6685 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006686 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6687 // If a reduction clause is present on the taskloop directive, the nogroup
6688 // clause must not be specified.
6689 if (checkReductionClauseWithNogroup(*this, Clauses))
6690 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006691
Alexey Bataev49f6e782015-12-01 04:18:41 +00006692 getCurFunction()->setHasBranchProtectedScope();
6693 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6694 NestedLoopCount, Clauses, AStmt, B);
6695}
6696
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006697StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6698 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6699 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006700 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006701 if (!AStmt)
6702 return StmtError();
6703
6704 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6705 OMPLoopDirective::HelperExprs B;
6706 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6707 // define the nested loops number.
6708 unsigned NestedLoopCount =
6709 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6710 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6711 VarsWithImplicitDSA, B);
6712 if (NestedLoopCount == 0)
6713 return StmtError();
6714
6715 assert((CurContext->isDependentContext() || B.builtAll()) &&
6716 "omp for loop exprs were not built");
6717
Alexey Bataev5a3af132016-03-29 08:58:54 +00006718 if (!CurContext->isDependentContext()) {
6719 // Finalize the clauses that need pre-built expressions for CodeGen.
6720 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006721 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006722 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006723 B.NumIterations, *this, CurScope,
6724 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006725 return StmtError();
6726 }
6727 }
6728
Alexey Bataev382967a2015-12-08 12:06:20 +00006729 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6730 // The grainsize clause and num_tasks clause are mutually exclusive and may
6731 // not appear on the same taskloop directive.
6732 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6733 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006734 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6735 // If a reduction clause is present on the taskloop directive, the nogroup
6736 // clause must not be specified.
6737 if (checkReductionClauseWithNogroup(*this, Clauses))
6738 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006739 if (checkSimdlenSafelenSpecified(*this, Clauses))
6740 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006741
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006742 getCurFunction()->setHasBranchProtectedScope();
6743 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6744 NestedLoopCount, Clauses, AStmt, B);
6745}
6746
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006747StmtResult Sema::ActOnOpenMPDistributeDirective(
6748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6749 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006750 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006751 if (!AStmt)
6752 return StmtError();
6753
6754 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6755 OMPLoopDirective::HelperExprs B;
6756 // In presence of clause 'collapse' with number of loops, it will
6757 // define the nested loops number.
6758 unsigned NestedLoopCount =
6759 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6760 nullptr /*ordered not a clause on distribute*/, AStmt,
6761 *this, *DSAStack, VarsWithImplicitDSA, B);
6762 if (NestedLoopCount == 0)
6763 return StmtError();
6764
6765 assert((CurContext->isDependentContext() || B.builtAll()) &&
6766 "omp for loop exprs were not built");
6767
6768 getCurFunction()->setHasBranchProtectedScope();
6769 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6770 NestedLoopCount, Clauses, AStmt, B);
6771}
6772
Carlo Bertolli9925f152016-06-27 14:55:37 +00006773StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6774 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6775 SourceLocation EndLoc,
6776 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6777 if (!AStmt)
6778 return StmtError();
6779
6780 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6781 // 1.2.2 OpenMP Language Terminology
6782 // Structured block - An executable statement with a single entry at the
6783 // top and a single exit at the bottom.
6784 // The point of exit cannot be a branch out of the structured block.
6785 // longjmp() and throw() must not violate the entry/exit criteria.
6786 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006787 for (int ThisCaptureLevel =
6788 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6789 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6790 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6791 // 1.2.2 OpenMP Language Terminology
6792 // Structured block - An executable statement with a single entry at the
6793 // top and a single exit at the bottom.
6794 // The point of exit cannot be a branch out of the structured block.
6795 // longjmp() and throw() must not violate the entry/exit criteria.
6796 CS->getCapturedDecl()->setNothrow();
6797 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006798
6799 OMPLoopDirective::HelperExprs B;
6800 // In presence of clause 'collapse' with number of loops, it will
6801 // define the nested loops number.
6802 unsigned NestedLoopCount = CheckOpenMPLoop(
6803 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006804 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006805 VarsWithImplicitDSA, B);
6806 if (NestedLoopCount == 0)
6807 return StmtError();
6808
6809 assert((CurContext->isDependentContext() || B.builtAll()) &&
6810 "omp for loop exprs were not built");
6811
6812 getCurFunction()->setHasBranchProtectedScope();
6813 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00006814 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
6815 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00006816}
6817
Kelvin Li4a39add2016-07-05 05:00:15 +00006818StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6820 SourceLocation EndLoc,
6821 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6822 if (!AStmt)
6823 return StmtError();
6824
6825 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6826 // 1.2.2 OpenMP Language Terminology
6827 // Structured block - An executable statement with a single entry at the
6828 // top and a single exit at the bottom.
6829 // The point of exit cannot be a branch out of the structured block.
6830 // longjmp() and throw() must not violate the entry/exit criteria.
6831 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00006832 for (int ThisCaptureLevel =
6833 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
6834 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6835 CS = cast<CapturedStmt>(CS->getCapturedStmt());
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();
6842 }
Kelvin Li4a39add2016-07-05 05:00:15 +00006843
6844 OMPLoopDirective::HelperExprs B;
6845 // In presence of clause 'collapse' with number of loops, it will
6846 // define the nested loops number.
6847 unsigned NestedLoopCount = CheckOpenMPLoop(
6848 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00006849 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00006850 VarsWithImplicitDSA, B);
6851 if (NestedLoopCount == 0)
6852 return StmtError();
6853
6854 assert((CurContext->isDependentContext() || B.builtAll()) &&
6855 "omp for loop exprs were not built");
6856
Alexey Bataev438388c2017-11-22 18:34:02 +00006857 if (!CurContext->isDependentContext()) {
6858 // Finalize the clauses that need pre-built expressions for CodeGen.
6859 for (auto C : Clauses) {
6860 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6861 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6862 B.NumIterations, *this, CurScope,
6863 DSAStack))
6864 return StmtError();
6865 }
6866 }
6867
Kelvin Lic5609492016-07-15 04:39:07 +00006868 if (checkSimdlenSafelenSpecified(*this, Clauses))
6869 return StmtError();
6870
Kelvin Li4a39add2016-07-05 05:00:15 +00006871 getCurFunction()->setHasBranchProtectedScope();
6872 return OMPDistributeParallelForSimdDirective::Create(
6873 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6874}
6875
Kelvin Li787f3fc2016-07-06 04:45:38 +00006876StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6877 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6878 SourceLocation EndLoc,
6879 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6880 if (!AStmt)
6881 return StmtError();
6882
6883 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6884 // 1.2.2 OpenMP Language Terminology
6885 // Structured block - An executable statement with a single entry at the
6886 // top and a single exit at the bottom.
6887 // The point of exit cannot be a branch out of the structured block.
6888 // longjmp() and throw() must not violate the entry/exit criteria.
6889 CS->getCapturedDecl()->setNothrow();
6890
6891 OMPLoopDirective::HelperExprs B;
6892 // In presence of clause 'collapse' with number of loops, it will
6893 // define the nested loops number.
6894 unsigned NestedLoopCount =
6895 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6896 nullptr /*ordered not a clause on distribute*/, AStmt,
6897 *this, *DSAStack, VarsWithImplicitDSA, B);
6898 if (NestedLoopCount == 0)
6899 return StmtError();
6900
6901 assert((CurContext->isDependentContext() || B.builtAll()) &&
6902 "omp for loop exprs were not built");
6903
Alexey Bataev438388c2017-11-22 18:34:02 +00006904 if (!CurContext->isDependentContext()) {
6905 // Finalize the clauses that need pre-built expressions for CodeGen.
6906 for (auto C : Clauses) {
6907 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6908 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6909 B.NumIterations, *this, CurScope,
6910 DSAStack))
6911 return StmtError();
6912 }
6913 }
6914
Kelvin Lic5609492016-07-15 04:39:07 +00006915 if (checkSimdlenSafelenSpecified(*this, Clauses))
6916 return StmtError();
6917
Kelvin Li787f3fc2016-07-06 04:45:38 +00006918 getCurFunction()->setHasBranchProtectedScope();
6919 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6920 NestedLoopCount, Clauses, AStmt, B);
6921}
6922
Kelvin Lia579b912016-07-14 02:54:56 +00006923StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6925 SourceLocation EndLoc,
6926 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6927 if (!AStmt)
6928 return StmtError();
6929
6930 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6931 // 1.2.2 OpenMP Language Terminology
6932 // Structured block - An executable statement with a single entry at the
6933 // top and a single exit at the bottom.
6934 // The point of exit cannot be a branch out of the structured block.
6935 // longjmp() and throw() must not violate the entry/exit criteria.
6936 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006937 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6938 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6939 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6940 // 1.2.2 OpenMP Language Terminology
6941 // Structured block - An executable statement with a single entry at the
6942 // top and a single exit at the bottom.
6943 // The point of exit cannot be a branch out of the structured block.
6944 // longjmp() and throw() must not violate the entry/exit criteria.
6945 CS->getCapturedDecl()->setNothrow();
6946 }
Kelvin Lia579b912016-07-14 02:54:56 +00006947
6948 OMPLoopDirective::HelperExprs B;
6949 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6950 // define the nested loops number.
6951 unsigned NestedLoopCount = CheckOpenMPLoop(
6952 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006953 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00006954 VarsWithImplicitDSA, B);
6955 if (NestedLoopCount == 0)
6956 return StmtError();
6957
6958 assert((CurContext->isDependentContext() || B.builtAll()) &&
6959 "omp target parallel for simd loop exprs were not built");
6960
6961 if (!CurContext->isDependentContext()) {
6962 // Finalize the clauses that need pre-built expressions for CodeGen.
6963 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006964 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006965 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6966 B.NumIterations, *this, CurScope,
6967 DSAStack))
6968 return StmtError();
6969 }
6970 }
Kelvin Lic5609492016-07-15 04:39:07 +00006971 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006972 return StmtError();
6973
6974 getCurFunction()->setHasBranchProtectedScope();
6975 return OMPTargetParallelForSimdDirective::Create(
6976 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6977}
6978
Kelvin Li986330c2016-07-20 22:57:10 +00006979StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6980 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6981 SourceLocation EndLoc,
6982 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6983 if (!AStmt)
6984 return StmtError();
6985
6986 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6987 // 1.2.2 OpenMP Language Terminology
6988 // Structured block - An executable statement with a single entry at the
6989 // top and a single exit at the bottom.
6990 // The point of exit cannot be a branch out of the structured block.
6991 // longjmp() and throw() must not violate the entry/exit criteria.
6992 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00006993 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
6994 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6995 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6996 // 1.2.2 OpenMP Language Terminology
6997 // Structured block - An executable statement with a single entry at the
6998 // top and a single exit at the bottom.
6999 // The point of exit cannot be a branch out of the structured block.
7000 // longjmp() and throw() must not violate the entry/exit criteria.
7001 CS->getCapturedDecl()->setNothrow();
7002 }
7003
Kelvin Li986330c2016-07-20 22:57:10 +00007004 OMPLoopDirective::HelperExprs B;
7005 // In presence of clause 'collapse' with number of loops, it will define the
7006 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007007 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007008 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007009 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007010 VarsWithImplicitDSA, B);
7011 if (NestedLoopCount == 0)
7012 return StmtError();
7013
7014 assert((CurContext->isDependentContext() || B.builtAll()) &&
7015 "omp target simd loop exprs were not built");
7016
7017 if (!CurContext->isDependentContext()) {
7018 // Finalize the clauses that need pre-built expressions for CodeGen.
7019 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007020 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007021 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7022 B.NumIterations, *this, CurScope,
7023 DSAStack))
7024 return StmtError();
7025 }
7026 }
7027
7028 if (checkSimdlenSafelenSpecified(*this, Clauses))
7029 return StmtError();
7030
7031 getCurFunction()->setHasBranchProtectedScope();
7032 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7033 NestedLoopCount, Clauses, AStmt, B);
7034}
7035
Kelvin Li02532872016-08-05 14:37:37 +00007036StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7037 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7038 SourceLocation EndLoc,
7039 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7040 if (!AStmt)
7041 return StmtError();
7042
7043 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7044 // 1.2.2 OpenMP Language Terminology
7045 // Structured block - An executable statement with a single entry at the
7046 // top and a single exit at the bottom.
7047 // The point of exit cannot be a branch out of the structured block.
7048 // longjmp() and throw() must not violate the entry/exit criteria.
7049 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007050 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7051 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7052 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7053 // 1.2.2 OpenMP Language Terminology
7054 // Structured block - An executable statement with a single entry at the
7055 // top and a single exit at the bottom.
7056 // The point of exit cannot be a branch out of the structured block.
7057 // longjmp() and throw() must not violate the entry/exit criteria.
7058 CS->getCapturedDecl()->setNothrow();
7059 }
Kelvin Li02532872016-08-05 14:37:37 +00007060
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),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007066 nullptr /*ordered not a clause on distribute*/, CS, *this,
7067 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007068 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();
Alexey Bataevceabd412017-11-30 18:01:54 +00007075
7076 DSAStack->setParentTeamsRegionLoc(StartLoc);
7077
David Majnemer9d168222016-08-05 17:44:54 +00007078 return OMPTeamsDistributeDirective::Create(
7079 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007080}
7081
Kelvin Li4e325f72016-10-25 12:50:55 +00007082StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7083 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7084 SourceLocation EndLoc,
7085 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7086 if (!AStmt)
7087 return StmtError();
7088
7089 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7090 // 1.2.2 OpenMP Language Terminology
7091 // Structured block - An executable statement with a single entry at the
7092 // top and a single exit at the bottom.
7093 // The point of exit cannot be a branch out of the structured block.
7094 // longjmp() and throw() must not violate the entry/exit criteria.
7095 CS->getCapturedDecl()->setNothrow();
7096
7097 OMPLoopDirective::HelperExprs B;
7098 // In presence of clause 'collapse' with number of loops, it will
7099 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007100 unsigned NestedLoopCount = CheckOpenMPLoop(
7101 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7102 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7103 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007104
7105 if (NestedLoopCount == 0)
7106 return StmtError();
7107
7108 assert((CurContext->isDependentContext() || B.builtAll()) &&
7109 "omp teams distribute simd loop exprs were not built");
7110
7111 if (!CurContext->isDependentContext()) {
7112 // Finalize the clauses that need pre-built expressions for CodeGen.
7113 for (auto C : Clauses) {
7114 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7115 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7116 B.NumIterations, *this, CurScope,
7117 DSAStack))
7118 return StmtError();
7119 }
7120 }
7121
7122 if (checkSimdlenSafelenSpecified(*this, Clauses))
7123 return StmtError();
7124
7125 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007126
7127 DSAStack->setParentTeamsRegionLoc(StartLoc);
7128
Kelvin Li4e325f72016-10-25 12:50:55 +00007129 return OMPTeamsDistributeSimdDirective::Create(
7130 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7131}
7132
Kelvin Li579e41c2016-11-30 23:51:03 +00007133StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7134 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7135 SourceLocation EndLoc,
7136 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7137 if (!AStmt)
7138 return StmtError();
7139
7140 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7141 // 1.2.2 OpenMP Language Terminology
7142 // Structured block - An executable statement with a single entry at the
7143 // top and a single exit at the bottom.
7144 // The point of exit cannot be a branch out of the structured block.
7145 // longjmp() and throw() must not violate the entry/exit criteria.
7146 CS->getCapturedDecl()->setNothrow();
7147
7148 OMPLoopDirective::HelperExprs B;
7149 // In presence of clause 'collapse' with number of loops, it will
7150 // define the nested loops number.
7151 auto NestedLoopCount = CheckOpenMPLoop(
7152 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7153 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7154 VarsWithImplicitDSA, B);
7155
7156 if (NestedLoopCount == 0)
7157 return StmtError();
7158
7159 assert((CurContext->isDependentContext() || B.builtAll()) &&
7160 "omp for loop exprs were not built");
7161
7162 if (!CurContext->isDependentContext()) {
7163 // Finalize the clauses that need pre-built expressions for CodeGen.
7164 for (auto C : Clauses) {
7165 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7166 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7167 B.NumIterations, *this, CurScope,
7168 DSAStack))
7169 return StmtError();
7170 }
7171 }
7172
7173 if (checkSimdlenSafelenSpecified(*this, Clauses))
7174 return StmtError();
7175
7176 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007177
7178 DSAStack->setParentTeamsRegionLoc(StartLoc);
7179
Kelvin Li579e41c2016-11-30 23:51:03 +00007180 return OMPTeamsDistributeParallelForSimdDirective::Create(
7181 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7182}
7183
Kelvin Li7ade93f2016-12-09 03:24:30 +00007184StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7185 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7186 SourceLocation EndLoc,
7187 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7188 if (!AStmt)
7189 return StmtError();
7190
7191 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7192 // 1.2.2 OpenMP Language Terminology
7193 // Structured block - An executable statement with a single entry at the
7194 // top and a single exit at the bottom.
7195 // The point of exit cannot be a branch out of the structured block.
7196 // longjmp() and throw() must not violate the entry/exit criteria.
7197 CS->getCapturedDecl()->setNothrow();
7198
Carlo Bertolli62fae152017-11-20 20:46:39 +00007199 for (int ThisCaptureLevel =
7200 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7201 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7202 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7203 // 1.2.2 OpenMP Language Terminology
7204 // Structured block - An executable statement with a single entry at the
7205 // top and a single exit at the bottom.
7206 // The point of exit cannot be a branch out of the structured block.
7207 // longjmp() and throw() must not violate the entry/exit criteria.
7208 CS->getCapturedDecl()->setNothrow();
7209 }
7210
Kelvin Li7ade93f2016-12-09 03:24:30 +00007211 OMPLoopDirective::HelperExprs B;
7212 // In presence of clause 'collapse' with number of loops, it will
7213 // define the nested loops number.
7214 unsigned NestedLoopCount = CheckOpenMPLoop(
7215 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007216 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007217 VarsWithImplicitDSA, B);
7218
7219 if (NestedLoopCount == 0)
7220 return StmtError();
7221
7222 assert((CurContext->isDependentContext() || B.builtAll()) &&
7223 "omp for loop exprs were not built");
7224
Kelvin Li7ade93f2016-12-09 03:24:30 +00007225 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007226
7227 DSAStack->setParentTeamsRegionLoc(StartLoc);
7228
Kelvin Li7ade93f2016-12-09 03:24:30 +00007229 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007230 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7231 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007232}
7233
Kelvin Libf594a52016-12-17 05:48:59 +00007234StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7235 Stmt *AStmt,
7236 SourceLocation StartLoc,
7237 SourceLocation EndLoc) {
7238 if (!AStmt)
7239 return StmtError();
7240
7241 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7242 // 1.2.2 OpenMP Language Terminology
7243 // Structured block - An executable statement with a single entry at the
7244 // top and a single exit at the bottom.
7245 // The point of exit cannot be a branch out of the structured block.
7246 // longjmp() and throw() must not violate the entry/exit criteria.
7247 CS->getCapturedDecl()->setNothrow();
7248
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007249 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7250 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7251 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7252 // 1.2.2 OpenMP Language Terminology
7253 // Structured block - An executable statement with a single entry at the
7254 // top and a single exit at the bottom.
7255 // The point of exit cannot be a branch out of the structured block.
7256 // longjmp() and throw() must not violate the entry/exit criteria.
7257 CS->getCapturedDecl()->setNothrow();
7258 }
Kelvin Libf594a52016-12-17 05:48:59 +00007259 getCurFunction()->setHasBranchProtectedScope();
7260
7261 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7262 AStmt);
7263}
7264
Kelvin Li83c451e2016-12-25 04:52:54 +00007265StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7266 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7267 SourceLocation EndLoc,
7268 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7269 if (!AStmt)
7270 return StmtError();
7271
7272 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7273 // 1.2.2 OpenMP Language Terminology
7274 // Structured block - An executable statement with a single entry at the
7275 // top and a single exit at the bottom.
7276 // The point of exit cannot be a branch out of the structured block.
7277 // longjmp() and throw() must not violate the entry/exit criteria.
7278 CS->getCapturedDecl()->setNothrow();
7279
7280 OMPLoopDirective::HelperExprs B;
7281 // In presence of clause 'collapse' with number of loops, it will
7282 // define the nested loops number.
7283 auto NestedLoopCount = CheckOpenMPLoop(
7284 OMPD_target_teams_distribute,
7285 getCollapseNumberExpr(Clauses),
7286 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7287 VarsWithImplicitDSA, B);
7288 if (NestedLoopCount == 0)
7289 return StmtError();
7290
7291 assert((CurContext->isDependentContext() || B.builtAll()) &&
7292 "omp target teams distribute loop exprs were not built");
7293
7294 getCurFunction()->setHasBranchProtectedScope();
7295 return OMPTargetTeamsDistributeDirective::Create(
7296 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7297}
7298
Kelvin Li80e8f562016-12-29 22:16:30 +00007299StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7301 SourceLocation EndLoc,
7302 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7303 if (!AStmt)
7304 return StmtError();
7305
7306 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7307 // 1.2.2 OpenMP Language Terminology
7308 // Structured block - An executable statement with a single entry at the
7309 // top and a single exit at the bottom.
7310 // The point of exit cannot be a branch out of the structured block.
7311 // longjmp() and throw() must not violate the entry/exit criteria.
7312 CS->getCapturedDecl()->setNothrow();
7313
7314 OMPLoopDirective::HelperExprs B;
7315 // In presence of clause 'collapse' with number of loops, it will
7316 // define the nested loops number.
7317 auto NestedLoopCount = CheckOpenMPLoop(
7318 OMPD_target_teams_distribute_parallel_for,
7319 getCollapseNumberExpr(Clauses),
7320 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7321 VarsWithImplicitDSA, B);
7322 if (NestedLoopCount == 0)
7323 return StmtError();
7324
7325 assert((CurContext->isDependentContext() || B.builtAll()) &&
7326 "omp target teams distribute parallel for loop exprs were not built");
7327
Kelvin Li80e8f562016-12-29 22:16:30 +00007328 getCurFunction()->setHasBranchProtectedScope();
7329 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007330 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7331 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007332}
7333
Kelvin Li1851df52017-01-03 05:23:48 +00007334StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7335 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7336 SourceLocation EndLoc,
7337 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7338 if (!AStmt)
7339 return StmtError();
7340
7341 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7342 // 1.2.2 OpenMP Language Terminology
7343 // Structured block - An executable statement with a single entry at the
7344 // top and a single exit at the bottom.
7345 // The point of exit cannot be a branch out of the structured block.
7346 // longjmp() and throw() must not violate the entry/exit criteria.
7347 CS->getCapturedDecl()->setNothrow();
7348
7349 OMPLoopDirective::HelperExprs B;
7350 // In presence of clause 'collapse' with number of loops, it will
7351 // define the nested loops number.
7352 auto NestedLoopCount = CheckOpenMPLoop(
7353 OMPD_target_teams_distribute_parallel_for_simd,
7354 getCollapseNumberExpr(Clauses),
7355 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7356 VarsWithImplicitDSA, B);
7357 if (NestedLoopCount == 0)
7358 return StmtError();
7359
7360 assert((CurContext->isDependentContext() || B.builtAll()) &&
7361 "omp target teams distribute parallel for simd loop exprs were not "
7362 "built");
7363
7364 if (!CurContext->isDependentContext()) {
7365 // Finalize the clauses that need pre-built expressions for CodeGen.
7366 for (auto C : Clauses) {
7367 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7368 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7369 B.NumIterations, *this, CurScope,
7370 DSAStack))
7371 return StmtError();
7372 }
7373 }
7374
Alexey Bataev438388c2017-11-22 18:34:02 +00007375 if (checkSimdlenSafelenSpecified(*this, Clauses))
7376 return StmtError();
7377
Kelvin Li1851df52017-01-03 05:23:48 +00007378 getCurFunction()->setHasBranchProtectedScope();
7379 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7380 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7381}
7382
Kelvin Lida681182017-01-10 18:08:18 +00007383StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7384 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7385 SourceLocation EndLoc,
7386 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7387 if (!AStmt)
7388 return StmtError();
7389
7390 auto *CS = cast<CapturedStmt>(AStmt);
7391 // 1.2.2 OpenMP Language Terminology
7392 // Structured block - An executable statement with a single entry at the
7393 // top and a single exit at the bottom.
7394 // The point of exit cannot be a branch out of the structured block.
7395 // longjmp() and throw() must not violate the entry/exit criteria.
7396 CS->getCapturedDecl()->setNothrow();
7397
7398 OMPLoopDirective::HelperExprs B;
7399 // In presence of clause 'collapse' with number of loops, it will
7400 // define the nested loops number.
7401 auto NestedLoopCount = CheckOpenMPLoop(
7402 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7403 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7404 VarsWithImplicitDSA, B);
7405 if (NestedLoopCount == 0)
7406 return StmtError();
7407
7408 assert((CurContext->isDependentContext() || B.builtAll()) &&
7409 "omp target teams distribute simd loop exprs were not built");
7410
Alexey Bataev438388c2017-11-22 18:34:02 +00007411 if (!CurContext->isDependentContext()) {
7412 // Finalize the clauses that need pre-built expressions for CodeGen.
7413 for (auto C : Clauses) {
7414 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7415 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7416 B.NumIterations, *this, CurScope,
7417 DSAStack))
7418 return StmtError();
7419 }
7420 }
7421
7422 if (checkSimdlenSafelenSpecified(*this, Clauses))
7423 return StmtError();
7424
Kelvin Lida681182017-01-10 18:08:18 +00007425 getCurFunction()->setHasBranchProtectedScope();
7426 return OMPTargetTeamsDistributeSimdDirective::Create(
7427 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7428}
7429
Alexey Bataeved09d242014-05-28 05:53:51 +00007430OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007431 SourceLocation StartLoc,
7432 SourceLocation LParenLoc,
7433 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007434 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007435 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007436 case OMPC_final:
7437 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7438 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007439 case OMPC_num_threads:
7440 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7441 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007442 case OMPC_safelen:
7443 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7444 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007445 case OMPC_simdlen:
7446 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7447 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007448 case OMPC_collapse:
7449 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7450 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007451 case OMPC_ordered:
7452 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7453 break;
Michael Wonge710d542015-08-07 16:16:36 +00007454 case OMPC_device:
7455 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7456 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007457 case OMPC_num_teams:
7458 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7459 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007460 case OMPC_thread_limit:
7461 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7462 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007463 case OMPC_priority:
7464 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7465 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007466 case OMPC_grainsize:
7467 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7468 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007469 case OMPC_num_tasks:
7470 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7471 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007472 case OMPC_hint:
7473 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7474 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007475 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007476 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007477 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007478 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007479 case OMPC_private:
7480 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007481 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007482 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007483 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007484 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007485 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007486 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007487 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007488 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007489 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007490 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007491 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007492 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007493 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007494 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007495 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007496 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007497 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007498 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007499 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007500 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007501 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007502 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007503 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007504 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007505 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007506 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007507 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007508 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007509 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007510 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007511 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007512 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007513 llvm_unreachable("Clause is not allowed.");
7514 }
7515 return Res;
7516}
7517
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007518// An OpenMP directive such as 'target parallel' has two captured regions:
7519// for the 'target' and 'parallel' respectively. This function returns
7520// the region in which to capture expressions associated with a clause.
7521// A return value of OMPD_unknown signifies that the expression should not
7522// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007523static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7524 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7525 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007526 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007527 switch (CKind) {
7528 case OMPC_if:
7529 switch (DKind) {
7530 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007531 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007532 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007533 case OMPD_target_teams_distribute_parallel_for:
7534 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007535 // If this clause applies to the nested 'parallel' region, capture within
7536 // the 'target' region, otherwise do not capture.
7537 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7538 CaptureRegion = OMPD_target;
7539 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007540 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007541 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007542 CaptureRegion = OMPD_teams;
7543 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007544 case OMPD_cancel:
7545 case OMPD_parallel:
7546 case OMPD_parallel_sections:
7547 case OMPD_parallel_for:
7548 case OMPD_parallel_for_simd:
7549 case OMPD_target:
7550 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007551 case OMPD_target_teams:
7552 case OMPD_target_teams_distribute:
7553 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007554 case OMPD_distribute_parallel_for:
7555 case OMPD_distribute_parallel_for_simd:
7556 case OMPD_task:
7557 case OMPD_taskloop:
7558 case OMPD_taskloop_simd:
7559 case OMPD_target_data:
7560 case OMPD_target_enter_data:
7561 case OMPD_target_exit_data:
7562 case OMPD_target_update:
7563 // Do not capture if-clause expressions.
7564 break;
7565 case OMPD_threadprivate:
7566 case OMPD_taskyield:
7567 case OMPD_barrier:
7568 case OMPD_taskwait:
7569 case OMPD_cancellation_point:
7570 case OMPD_flush:
7571 case OMPD_declare_reduction:
7572 case OMPD_declare_simd:
7573 case OMPD_declare_target:
7574 case OMPD_end_declare_target:
7575 case OMPD_teams:
7576 case OMPD_simd:
7577 case OMPD_for:
7578 case OMPD_for_simd:
7579 case OMPD_sections:
7580 case OMPD_section:
7581 case OMPD_single:
7582 case OMPD_master:
7583 case OMPD_critical:
7584 case OMPD_taskgroup:
7585 case OMPD_distribute:
7586 case OMPD_ordered:
7587 case OMPD_atomic:
7588 case OMPD_distribute_simd:
7589 case OMPD_teams_distribute:
7590 case OMPD_teams_distribute_simd:
7591 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7592 case OMPD_unknown:
7593 llvm_unreachable("Unknown OpenMP directive");
7594 }
7595 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007596 case OMPC_num_threads:
7597 switch (DKind) {
7598 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007599 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007600 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007601 case OMPD_target_teams_distribute_parallel_for:
7602 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007603 CaptureRegion = OMPD_target;
7604 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007605 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007606 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007607 CaptureRegion = OMPD_teams;
7608 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007609 case OMPD_parallel:
7610 case OMPD_parallel_sections:
7611 case OMPD_parallel_for:
7612 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007613 case OMPD_distribute_parallel_for:
7614 case OMPD_distribute_parallel_for_simd:
7615 // Do not capture num_threads-clause expressions.
7616 break;
7617 case OMPD_target_data:
7618 case OMPD_target_enter_data:
7619 case OMPD_target_exit_data:
7620 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007621 case OMPD_target:
7622 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007623 case OMPD_target_teams:
7624 case OMPD_target_teams_distribute:
7625 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007626 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007627 case OMPD_task:
7628 case OMPD_taskloop:
7629 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007630 case OMPD_threadprivate:
7631 case OMPD_taskyield:
7632 case OMPD_barrier:
7633 case OMPD_taskwait:
7634 case OMPD_cancellation_point:
7635 case OMPD_flush:
7636 case OMPD_declare_reduction:
7637 case OMPD_declare_simd:
7638 case OMPD_declare_target:
7639 case OMPD_end_declare_target:
7640 case OMPD_teams:
7641 case OMPD_simd:
7642 case OMPD_for:
7643 case OMPD_for_simd:
7644 case OMPD_sections:
7645 case OMPD_section:
7646 case OMPD_single:
7647 case OMPD_master:
7648 case OMPD_critical:
7649 case OMPD_taskgroup:
7650 case OMPD_distribute:
7651 case OMPD_ordered:
7652 case OMPD_atomic:
7653 case OMPD_distribute_simd:
7654 case OMPD_teams_distribute:
7655 case OMPD_teams_distribute_simd:
7656 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7657 case OMPD_unknown:
7658 llvm_unreachable("Unknown OpenMP directive");
7659 }
7660 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007661 case OMPC_num_teams:
7662 switch (DKind) {
7663 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007664 case OMPD_target_teams_distribute:
7665 case OMPD_target_teams_distribute_simd:
7666 case OMPD_target_teams_distribute_parallel_for:
7667 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007668 CaptureRegion = OMPD_target;
7669 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007670 case OMPD_teams_distribute_parallel_for:
7671 case OMPD_teams_distribute_parallel_for_simd:
7672 case OMPD_teams:
7673 case OMPD_teams_distribute:
7674 case OMPD_teams_distribute_simd:
7675 // Do not capture num_teams-clause expressions.
7676 break;
7677 case OMPD_distribute_parallel_for:
7678 case OMPD_distribute_parallel_for_simd:
7679 case OMPD_task:
7680 case OMPD_taskloop:
7681 case OMPD_taskloop_simd:
7682 case OMPD_target_data:
7683 case OMPD_target_enter_data:
7684 case OMPD_target_exit_data:
7685 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007686 case OMPD_cancel:
7687 case OMPD_parallel:
7688 case OMPD_parallel_sections:
7689 case OMPD_parallel_for:
7690 case OMPD_parallel_for_simd:
7691 case OMPD_target:
7692 case OMPD_target_simd:
7693 case OMPD_target_parallel:
7694 case OMPD_target_parallel_for:
7695 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007696 case OMPD_threadprivate:
7697 case OMPD_taskyield:
7698 case OMPD_barrier:
7699 case OMPD_taskwait:
7700 case OMPD_cancellation_point:
7701 case OMPD_flush:
7702 case OMPD_declare_reduction:
7703 case OMPD_declare_simd:
7704 case OMPD_declare_target:
7705 case OMPD_end_declare_target:
7706 case OMPD_simd:
7707 case OMPD_for:
7708 case OMPD_for_simd:
7709 case OMPD_sections:
7710 case OMPD_section:
7711 case OMPD_single:
7712 case OMPD_master:
7713 case OMPD_critical:
7714 case OMPD_taskgroup:
7715 case OMPD_distribute:
7716 case OMPD_ordered:
7717 case OMPD_atomic:
7718 case OMPD_distribute_simd:
7719 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7720 case OMPD_unknown:
7721 llvm_unreachable("Unknown OpenMP directive");
7722 }
7723 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007724 case OMPC_thread_limit:
7725 switch (DKind) {
7726 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007727 case OMPD_target_teams_distribute:
7728 case OMPD_target_teams_distribute_simd:
7729 case OMPD_target_teams_distribute_parallel_for:
7730 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007731 CaptureRegion = OMPD_target;
7732 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007733 case OMPD_teams_distribute_parallel_for:
7734 case OMPD_teams_distribute_parallel_for_simd:
7735 case OMPD_teams:
7736 case OMPD_teams_distribute:
7737 case OMPD_teams_distribute_simd:
7738 // Do not capture thread_limit-clause expressions.
7739 break;
7740 case OMPD_distribute_parallel_for:
7741 case OMPD_distribute_parallel_for_simd:
7742 case OMPD_task:
7743 case OMPD_taskloop:
7744 case OMPD_taskloop_simd:
7745 case OMPD_target_data:
7746 case OMPD_target_enter_data:
7747 case OMPD_target_exit_data:
7748 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007749 case OMPD_cancel:
7750 case OMPD_parallel:
7751 case OMPD_parallel_sections:
7752 case OMPD_parallel_for:
7753 case OMPD_parallel_for_simd:
7754 case OMPD_target:
7755 case OMPD_target_simd:
7756 case OMPD_target_parallel:
7757 case OMPD_target_parallel_for:
7758 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007759 case OMPD_threadprivate:
7760 case OMPD_taskyield:
7761 case OMPD_barrier:
7762 case OMPD_taskwait:
7763 case OMPD_cancellation_point:
7764 case OMPD_flush:
7765 case OMPD_declare_reduction:
7766 case OMPD_declare_simd:
7767 case OMPD_declare_target:
7768 case OMPD_end_declare_target:
7769 case OMPD_simd:
7770 case OMPD_for:
7771 case OMPD_for_simd:
7772 case OMPD_sections:
7773 case OMPD_section:
7774 case OMPD_single:
7775 case OMPD_master:
7776 case OMPD_critical:
7777 case OMPD_taskgroup:
7778 case OMPD_distribute:
7779 case OMPD_ordered:
7780 case OMPD_atomic:
7781 case OMPD_distribute_simd:
7782 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7783 case OMPD_unknown:
7784 llvm_unreachable("Unknown OpenMP directive");
7785 }
7786 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007787 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007788 switch (DKind) {
7789 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007790 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007791 case OMPD_target_teams_distribute_parallel_for:
7792 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007793 CaptureRegion = OMPD_target;
7794 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007795 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007796 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007797 CaptureRegion = OMPD_teams;
7798 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007799 case OMPD_parallel_for:
7800 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00007801 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00007802 case OMPD_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00007803 CaptureRegion = OMPD_parallel;
7804 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007805 case OMPD_for:
7806 case OMPD_for_simd:
7807 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007808 break;
7809 case OMPD_task:
7810 case OMPD_taskloop:
7811 case OMPD_taskloop_simd:
7812 case OMPD_target_data:
7813 case OMPD_target_enter_data:
7814 case OMPD_target_exit_data:
7815 case OMPD_target_update:
7816 case OMPD_teams:
7817 case OMPD_teams_distribute:
7818 case OMPD_teams_distribute_simd:
7819 case OMPD_target_teams_distribute:
7820 case OMPD_target_teams_distribute_simd:
7821 case OMPD_target:
7822 case OMPD_target_simd:
7823 case OMPD_target_parallel:
7824 case OMPD_cancel:
7825 case OMPD_parallel:
7826 case OMPD_parallel_sections:
7827 case OMPD_threadprivate:
7828 case OMPD_taskyield:
7829 case OMPD_barrier:
7830 case OMPD_taskwait:
7831 case OMPD_cancellation_point:
7832 case OMPD_flush:
7833 case OMPD_declare_reduction:
7834 case OMPD_declare_simd:
7835 case OMPD_declare_target:
7836 case OMPD_end_declare_target:
7837 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007838 case OMPD_sections:
7839 case OMPD_section:
7840 case OMPD_single:
7841 case OMPD_master:
7842 case OMPD_critical:
7843 case OMPD_taskgroup:
7844 case OMPD_distribute:
7845 case OMPD_ordered:
7846 case OMPD_atomic:
7847 case OMPD_distribute_simd:
7848 case OMPD_target_teams:
7849 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7850 case OMPD_unknown:
7851 llvm_unreachable("Unknown OpenMP directive");
7852 }
7853 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007854 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007855 switch (DKind) {
7856 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007857 case OMPD_teams_distribute_parallel_for_simd:
7858 case OMPD_teams_distribute:
7859 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007860 CaptureRegion = OMPD_teams;
7861 break;
7862 case OMPD_target_teams_distribute_parallel_for:
7863 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007864 case OMPD_target_teams_distribute:
7865 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007866 CaptureRegion = OMPD_target;
7867 break;
7868 case OMPD_distribute_parallel_for:
7869 case OMPD_distribute_parallel_for_simd:
7870 CaptureRegion = OMPD_parallel;
7871 break;
7872 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007873 case OMPD_distribute_simd:
7874 // Do not capture thread_limit-clause expressions.
7875 break;
7876 case OMPD_parallel_for:
7877 case OMPD_parallel_for_simd:
7878 case OMPD_target_parallel_for_simd:
7879 case OMPD_target_parallel_for:
7880 case OMPD_task:
7881 case OMPD_taskloop:
7882 case OMPD_taskloop_simd:
7883 case OMPD_target_data:
7884 case OMPD_target_enter_data:
7885 case OMPD_target_exit_data:
7886 case OMPD_target_update:
7887 case OMPD_teams:
7888 case OMPD_target:
7889 case OMPD_target_simd:
7890 case OMPD_target_parallel:
7891 case OMPD_cancel:
7892 case OMPD_parallel:
7893 case OMPD_parallel_sections:
7894 case OMPD_threadprivate:
7895 case OMPD_taskyield:
7896 case OMPD_barrier:
7897 case OMPD_taskwait:
7898 case OMPD_cancellation_point:
7899 case OMPD_flush:
7900 case OMPD_declare_reduction:
7901 case OMPD_declare_simd:
7902 case OMPD_declare_target:
7903 case OMPD_end_declare_target:
7904 case OMPD_simd:
7905 case OMPD_for:
7906 case OMPD_for_simd:
7907 case OMPD_sections:
7908 case OMPD_section:
7909 case OMPD_single:
7910 case OMPD_master:
7911 case OMPD_critical:
7912 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007913 case OMPD_ordered:
7914 case OMPD_atomic:
7915 case OMPD_target_teams:
7916 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7917 case OMPD_unknown:
7918 llvm_unreachable("Unknown OpenMP directive");
7919 }
7920 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007921 case OMPC_device:
7922 switch (DKind) {
7923 case OMPD_target_teams:
7924 case OMPD_target_teams_distribute:
7925 case OMPD_target_teams_distribute_simd:
7926 case OMPD_target_teams_distribute_parallel_for:
7927 case OMPD_target_teams_distribute_parallel_for_simd:
7928 case OMPD_target_data:
7929 case OMPD_target_enter_data:
7930 case OMPD_target_exit_data:
7931 case OMPD_target_update:
7932 case OMPD_target:
7933 case OMPD_target_simd:
7934 case OMPD_target_parallel:
7935 case OMPD_target_parallel_for:
7936 case OMPD_target_parallel_for_simd:
7937 // Do not capture device-clause expressions.
7938 break;
7939 case OMPD_teams_distribute_parallel_for:
7940 case OMPD_teams_distribute_parallel_for_simd:
7941 case OMPD_teams:
7942 case OMPD_teams_distribute:
7943 case OMPD_teams_distribute_simd:
7944 case OMPD_distribute_parallel_for:
7945 case OMPD_distribute_parallel_for_simd:
7946 case OMPD_task:
7947 case OMPD_taskloop:
7948 case OMPD_taskloop_simd:
7949 case OMPD_cancel:
7950 case OMPD_parallel:
7951 case OMPD_parallel_sections:
7952 case OMPD_parallel_for:
7953 case OMPD_parallel_for_simd:
7954 case OMPD_threadprivate:
7955 case OMPD_taskyield:
7956 case OMPD_barrier:
7957 case OMPD_taskwait:
7958 case OMPD_cancellation_point:
7959 case OMPD_flush:
7960 case OMPD_declare_reduction:
7961 case OMPD_declare_simd:
7962 case OMPD_declare_target:
7963 case OMPD_end_declare_target:
7964 case OMPD_simd:
7965 case OMPD_for:
7966 case OMPD_for_simd:
7967 case OMPD_sections:
7968 case OMPD_section:
7969 case OMPD_single:
7970 case OMPD_master:
7971 case OMPD_critical:
7972 case OMPD_taskgroup:
7973 case OMPD_distribute:
7974 case OMPD_ordered:
7975 case OMPD_atomic:
7976 case OMPD_distribute_simd:
7977 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7978 case OMPD_unknown:
7979 llvm_unreachable("Unknown OpenMP directive");
7980 }
7981 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007982 case OMPC_firstprivate:
7983 case OMPC_lastprivate:
7984 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007985 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007986 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007987 case OMPC_linear:
7988 case OMPC_default:
7989 case OMPC_proc_bind:
7990 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007991 case OMPC_safelen:
7992 case OMPC_simdlen:
7993 case OMPC_collapse:
7994 case OMPC_private:
7995 case OMPC_shared:
7996 case OMPC_aligned:
7997 case OMPC_copyin:
7998 case OMPC_copyprivate:
7999 case OMPC_ordered:
8000 case OMPC_nowait:
8001 case OMPC_untied:
8002 case OMPC_mergeable:
8003 case OMPC_threadprivate:
8004 case OMPC_flush:
8005 case OMPC_read:
8006 case OMPC_write:
8007 case OMPC_update:
8008 case OMPC_capture:
8009 case OMPC_seq_cst:
8010 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008011 case OMPC_threads:
8012 case OMPC_simd:
8013 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008014 case OMPC_priority:
8015 case OMPC_grainsize:
8016 case OMPC_nogroup:
8017 case OMPC_num_tasks:
8018 case OMPC_hint:
8019 case OMPC_defaultmap:
8020 case OMPC_unknown:
8021 case OMPC_uniform:
8022 case OMPC_to:
8023 case OMPC_from:
8024 case OMPC_use_device_ptr:
8025 case OMPC_is_device_ptr:
8026 llvm_unreachable("Unexpected OpenMP clause.");
8027 }
8028 return CaptureRegion;
8029}
8030
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008031OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8032 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008033 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008034 SourceLocation NameModifierLoc,
8035 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008036 SourceLocation EndLoc) {
8037 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008038 Stmt *HelperValStmt = nullptr;
8039 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008040 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8041 !Condition->isInstantiationDependent() &&
8042 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008043 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008044 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008045 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008046
Richard Smith03a4aa32016-06-23 19:02:52 +00008047 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008048
8049 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8050 CaptureRegion =
8051 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008052 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008053 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8054 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8055 HelperValStmt = buildPreInits(Context, Captures);
8056 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008057 }
8058
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008059 return new (Context)
8060 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8061 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008062}
8063
Alexey Bataev3778b602014-07-17 07:32:53 +00008064OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8065 SourceLocation StartLoc,
8066 SourceLocation LParenLoc,
8067 SourceLocation EndLoc) {
8068 Expr *ValExpr = Condition;
8069 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8070 !Condition->isInstantiationDependent() &&
8071 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008072 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008073 if (Val.isInvalid())
8074 return nullptr;
8075
Richard Smith03a4aa32016-06-23 19:02:52 +00008076 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008077 }
8078
8079 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8080}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008081ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8082 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008083 if (!Op)
8084 return ExprError();
8085
8086 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8087 public:
8088 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008089 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008090 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8091 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008092 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8093 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008094 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8095 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008096 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8097 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008098 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8099 QualType T,
8100 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008101 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8102 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008103 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8104 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008105 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008106 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008107 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008108 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8109 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008110 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8111 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008112 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8113 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008114 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008115 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008116 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008117 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8118 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008119 llvm_unreachable("conversion functions are permitted");
8120 }
8121 } ConvertDiagnoser;
8122 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8123}
8124
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008125static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008126 OpenMPClauseKind CKind,
8127 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008128 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8129 !ValExpr->isInstantiationDependent()) {
8130 SourceLocation Loc = ValExpr->getExprLoc();
8131 ExprResult Value =
8132 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8133 if (Value.isInvalid())
8134 return false;
8135
8136 ValExpr = Value.get();
8137 // The expression must evaluate to a non-negative integer value.
8138 llvm::APSInt Result;
8139 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008140 Result.isSigned() &&
8141 !((!StrictlyPositive && Result.isNonNegative()) ||
8142 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008143 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008144 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8145 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008146 return false;
8147 }
8148 }
8149 return true;
8150}
8151
Alexey Bataev568a8332014-03-06 06:15:19 +00008152OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8153 SourceLocation StartLoc,
8154 SourceLocation LParenLoc,
8155 SourceLocation EndLoc) {
8156 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008157 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008158
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008159 // OpenMP [2.5, Restrictions]
8160 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008161 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8162 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008163 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008164
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008165 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008166 OpenMPDirectiveKind CaptureRegion =
8167 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8168 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008169 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8170 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8171 HelperValStmt = buildPreInits(Context, Captures);
8172 }
8173
8174 return new (Context) OMPNumThreadsClause(
8175 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008176}
8177
Alexey Bataev62c87d22014-03-21 04:51:18 +00008178ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008179 OpenMPClauseKind CKind,
8180 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008181 if (!E)
8182 return ExprError();
8183 if (E->isValueDependent() || E->isTypeDependent() ||
8184 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008185 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008186 llvm::APSInt Result;
8187 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8188 if (ICE.isInvalid())
8189 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008190 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8191 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008192 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008193 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8194 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008195 return ExprError();
8196 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008197 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8198 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8199 << E->getSourceRange();
8200 return ExprError();
8201 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008202 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8203 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008204 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008205 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008206 return ICE;
8207}
8208
8209OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8210 SourceLocation LParenLoc,
8211 SourceLocation EndLoc) {
8212 // OpenMP [2.8.1, simd construct, Description]
8213 // The parameter of the safelen clause must be a constant
8214 // positive integer expression.
8215 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8216 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008217 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008218 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008219 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008220}
8221
Alexey Bataev66b15b52015-08-21 11:14:16 +00008222OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8223 SourceLocation LParenLoc,
8224 SourceLocation EndLoc) {
8225 // OpenMP [2.8.1, simd construct, Description]
8226 // The parameter of the simdlen clause must be a constant
8227 // positive integer expression.
8228 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8229 if (Simdlen.isInvalid())
8230 return nullptr;
8231 return new (Context)
8232 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8233}
8234
Alexander Musman64d33f12014-06-04 07:53:32 +00008235OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8236 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008237 SourceLocation LParenLoc,
8238 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008239 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008240 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008241 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008242 // The parameter of the collapse clause must be a constant
8243 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008244 ExprResult NumForLoopsResult =
8245 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8246 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008247 return nullptr;
8248 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008249 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008250}
8251
Alexey Bataev10e775f2015-07-30 11:36:16 +00008252OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8253 SourceLocation EndLoc,
8254 SourceLocation LParenLoc,
8255 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008256 // OpenMP [2.7.1, loop construct, Description]
8257 // OpenMP [2.8.1, simd construct, Description]
8258 // OpenMP [2.9.6, distribute construct, Description]
8259 // The parameter of the ordered clause must be a constant
8260 // positive integer expression if any.
8261 if (NumForLoops && LParenLoc.isValid()) {
8262 ExprResult NumForLoopsResult =
8263 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8264 if (NumForLoopsResult.isInvalid())
8265 return nullptr;
8266 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008267 } else
8268 NumForLoops = nullptr;
8269 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008270 return new (Context)
8271 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8272}
8273
Alexey Bataeved09d242014-05-28 05:53:51 +00008274OMPClause *Sema::ActOnOpenMPSimpleClause(
8275 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8276 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008277 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008278 switch (Kind) {
8279 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008280 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008281 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8282 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008283 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008284 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008285 Res = ActOnOpenMPProcBindClause(
8286 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8287 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008288 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008289 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008290 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008291 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008292 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008293 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008294 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008295 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008296 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008297 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008298 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008299 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008300 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008301 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008302 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008303 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008304 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008305 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008306 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008307 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008308 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008309 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008310 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008311 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008312 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008313 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008314 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008315 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008316 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008317 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008318 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008319 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008320 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008321 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008322 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008323 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008324 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008325 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008326 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008327 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008328 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008329 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008330 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008331 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008332 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008333 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008334 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008335 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008336 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008337 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008338 llvm_unreachable("Clause is not allowed.");
8339 }
8340 return Res;
8341}
8342
Alexey Bataev6402bca2015-12-28 07:25:51 +00008343static std::string
8344getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8345 ArrayRef<unsigned> Exclude = llvm::None) {
8346 std::string Values;
8347 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8348 unsigned Skipped = Exclude.size();
8349 auto S = Exclude.begin(), E = Exclude.end();
8350 for (unsigned i = First; i < Last; ++i) {
8351 if (std::find(S, E, i) != E) {
8352 --Skipped;
8353 continue;
8354 }
8355 Values += "'";
8356 Values += getOpenMPSimpleClauseTypeName(K, i);
8357 Values += "'";
8358 if (i == Bound - Skipped)
8359 Values += " or ";
8360 else if (i != Bound + 1 - Skipped)
8361 Values += ", ";
8362 }
8363 return Values;
8364}
8365
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008366OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8367 SourceLocation KindKwLoc,
8368 SourceLocation StartLoc,
8369 SourceLocation LParenLoc,
8370 SourceLocation EndLoc) {
8371 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008372 static_assert(OMPC_DEFAULT_unknown > 0,
8373 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008374 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008375 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8376 /*Last=*/OMPC_DEFAULT_unknown)
8377 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008378 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008379 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008380 switch (Kind) {
8381 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008382 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008383 break;
8384 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008385 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008386 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008387 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008388 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008389 break;
8390 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008391 return new (Context)
8392 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008393}
8394
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008395OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8396 SourceLocation KindKwLoc,
8397 SourceLocation StartLoc,
8398 SourceLocation LParenLoc,
8399 SourceLocation EndLoc) {
8400 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008401 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008402 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8403 /*Last=*/OMPC_PROC_BIND_unknown)
8404 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008405 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008406 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008407 return new (Context)
8408 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008409}
8410
Alexey Bataev56dafe82014-06-20 07:16:17 +00008411OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008412 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008413 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008414 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008415 SourceLocation EndLoc) {
8416 OMPClause *Res = nullptr;
8417 switch (Kind) {
8418 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008419 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8420 assert(Argument.size() == NumberOfElements &&
8421 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008422 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008423 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8424 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8425 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8426 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8427 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008428 break;
8429 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008430 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8431 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8432 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8433 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008434 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008435 case OMPC_dist_schedule:
8436 Res = ActOnOpenMPDistScheduleClause(
8437 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8438 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8439 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008440 case OMPC_defaultmap:
8441 enum { Modifier, DefaultmapKind };
8442 Res = ActOnOpenMPDefaultmapClause(
8443 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8444 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008445 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8446 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008447 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008448 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008449 case OMPC_num_threads:
8450 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008451 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008452 case OMPC_collapse:
8453 case OMPC_default:
8454 case OMPC_proc_bind:
8455 case OMPC_private:
8456 case OMPC_firstprivate:
8457 case OMPC_lastprivate:
8458 case OMPC_shared:
8459 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008460 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008461 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008462 case OMPC_linear:
8463 case OMPC_aligned:
8464 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008465 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008466 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008467 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008468 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008469 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008470 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008471 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008472 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008473 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008474 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008475 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008476 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008477 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008478 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008479 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008480 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008481 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008482 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008483 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008484 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008485 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008486 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008487 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008488 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008489 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008490 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008491 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008492 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008493 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008494 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008495 llvm_unreachable("Clause is not allowed.");
8496 }
8497 return Res;
8498}
8499
Alexey Bataev6402bca2015-12-28 07:25:51 +00008500static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8501 OpenMPScheduleClauseModifier M2,
8502 SourceLocation M1Loc, SourceLocation M2Loc) {
8503 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8504 SmallVector<unsigned, 2> Excluded;
8505 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8506 Excluded.push_back(M2);
8507 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8508 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8509 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8510 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8511 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8512 << getListOfPossibleValues(OMPC_schedule,
8513 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8514 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8515 Excluded)
8516 << getOpenMPClauseName(OMPC_schedule);
8517 return true;
8518 }
8519 return false;
8520}
8521
Alexey Bataev56dafe82014-06-20 07:16:17 +00008522OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008523 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008524 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008525 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8526 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8527 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8528 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8529 return nullptr;
8530 // OpenMP, 2.7.1, Loop Construct, Restrictions
8531 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8532 // but not both.
8533 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8534 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8535 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8536 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8537 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8538 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8539 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8540 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8541 return nullptr;
8542 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008543 if (Kind == OMPC_SCHEDULE_unknown) {
8544 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008545 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8546 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8547 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8548 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8549 Exclude);
8550 } else {
8551 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8552 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008553 }
8554 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8555 << Values << getOpenMPClauseName(OMPC_schedule);
8556 return nullptr;
8557 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008558 // OpenMP, 2.7.1, Loop Construct, Restrictions
8559 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8560 // schedule(guided).
8561 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8562 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8563 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8564 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8565 diag::err_omp_schedule_nonmonotonic_static);
8566 return nullptr;
8567 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008568 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008569 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008570 if (ChunkSize) {
8571 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8572 !ChunkSize->isInstantiationDependent() &&
8573 !ChunkSize->containsUnexpandedParameterPack()) {
8574 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8575 ExprResult Val =
8576 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8577 if (Val.isInvalid())
8578 return nullptr;
8579
8580 ValExpr = Val.get();
8581
8582 // OpenMP [2.7.1, Restrictions]
8583 // chunk_size must be a loop invariant integer expression with a positive
8584 // value.
8585 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008586 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8587 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8588 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008589 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008590 return nullptr;
8591 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008592 } else if (getOpenMPCaptureRegionForClause(
8593 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8594 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008595 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008596 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8597 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8598 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008599 }
8600 }
8601 }
8602
Alexey Bataev6402bca2015-12-28 07:25:51 +00008603 return new (Context)
8604 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008605 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008606}
8607
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008608OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8609 SourceLocation StartLoc,
8610 SourceLocation EndLoc) {
8611 OMPClause *Res = nullptr;
8612 switch (Kind) {
8613 case OMPC_ordered:
8614 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8615 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008616 case OMPC_nowait:
8617 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8618 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008619 case OMPC_untied:
8620 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8621 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008622 case OMPC_mergeable:
8623 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8624 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008625 case OMPC_read:
8626 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8627 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008628 case OMPC_write:
8629 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8630 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008631 case OMPC_update:
8632 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8633 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008634 case OMPC_capture:
8635 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8636 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008637 case OMPC_seq_cst:
8638 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8639 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008640 case OMPC_threads:
8641 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8642 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008643 case OMPC_simd:
8644 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8645 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008646 case OMPC_nogroup:
8647 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8648 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008649 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008650 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008651 case OMPC_num_threads:
8652 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008653 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008654 case OMPC_collapse:
8655 case OMPC_schedule:
8656 case OMPC_private:
8657 case OMPC_firstprivate:
8658 case OMPC_lastprivate:
8659 case OMPC_shared:
8660 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008661 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008662 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008663 case OMPC_linear:
8664 case OMPC_aligned:
8665 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008666 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008667 case OMPC_default:
8668 case OMPC_proc_bind:
8669 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008670 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008671 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008672 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008673 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008674 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008675 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008676 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008677 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008678 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008679 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008680 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008681 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008682 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008683 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008684 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008685 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008686 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008687 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008688 llvm_unreachable("Clause is not allowed.");
8689 }
8690 return Res;
8691}
8692
Alexey Bataev236070f2014-06-20 11:19:47 +00008693OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8694 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008695 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008696 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8697}
8698
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008699OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8700 SourceLocation EndLoc) {
8701 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8702}
8703
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008704OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8705 SourceLocation EndLoc) {
8706 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8707}
8708
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008709OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8710 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008711 return new (Context) OMPReadClause(StartLoc, EndLoc);
8712}
8713
Alexey Bataevdea47612014-07-23 07:46:59 +00008714OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8715 SourceLocation EndLoc) {
8716 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8717}
8718
Alexey Bataev67a4f222014-07-23 10:25:33 +00008719OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8720 SourceLocation EndLoc) {
8721 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8722}
8723
Alexey Bataev459dec02014-07-24 06:46:57 +00008724OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8725 SourceLocation EndLoc) {
8726 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8727}
8728
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008729OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8730 SourceLocation EndLoc) {
8731 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8732}
8733
Alexey Bataev346265e2015-09-25 10:37:12 +00008734OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8735 SourceLocation EndLoc) {
8736 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8737}
8738
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008739OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8740 SourceLocation EndLoc) {
8741 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8742}
8743
Alexey Bataevb825de12015-12-07 10:51:44 +00008744OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8745 SourceLocation EndLoc) {
8746 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8747}
8748
Alexey Bataevc5e02582014-06-16 07:08:35 +00008749OMPClause *Sema::ActOnOpenMPVarListClause(
8750 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8751 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8752 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008753 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008754 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8755 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8756 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008757 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008758 switch (Kind) {
8759 case OMPC_private:
8760 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8761 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008762 case OMPC_firstprivate:
8763 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8764 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008765 case OMPC_lastprivate:
8766 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8767 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008768 case OMPC_shared:
8769 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8770 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008771 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008772 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8773 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008774 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008775 case OMPC_task_reduction:
8776 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8777 EndLoc, ReductionIdScopeSpec,
8778 ReductionId);
8779 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008780 case OMPC_in_reduction:
8781 Res =
8782 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8783 EndLoc, ReductionIdScopeSpec, ReductionId);
8784 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008785 case OMPC_linear:
8786 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008787 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008788 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008789 case OMPC_aligned:
8790 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8791 ColonLoc, EndLoc);
8792 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008793 case OMPC_copyin:
8794 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8795 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008796 case OMPC_copyprivate:
8797 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8798 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008799 case OMPC_flush:
8800 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8801 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008802 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008803 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008804 StartLoc, LParenLoc, EndLoc);
8805 break;
8806 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008807 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8808 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8809 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008810 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008811 case OMPC_to:
8812 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8813 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008814 case OMPC_from:
8815 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8816 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008817 case OMPC_use_device_ptr:
8818 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8819 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008820 case OMPC_is_device_ptr:
8821 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8822 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008823 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008824 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008825 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008826 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008827 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008828 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008829 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008830 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008831 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008832 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008833 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008834 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008835 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008836 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008837 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008838 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008839 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008840 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008841 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008842 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008843 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008844 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008845 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008846 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008847 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008848 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008849 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008850 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008851 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008852 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008853 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008854 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008855 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008856 llvm_unreachable("Clause is not allowed.");
8857 }
8858 return Res;
8859}
8860
Alexey Bataev90c228f2016-02-08 09:29:13 +00008861ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008862 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008863 ExprResult Res = BuildDeclRefExpr(
8864 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8865 if (!Res.isUsable())
8866 return ExprError();
8867 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8868 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8869 if (!Res.isUsable())
8870 return ExprError();
8871 }
8872 if (VK != VK_LValue && Res.get()->isGLValue()) {
8873 Res = DefaultLvalueConversion(Res.get());
8874 if (!Res.isUsable())
8875 return ExprError();
8876 }
8877 return Res;
8878}
8879
Alexey Bataev60da77e2016-02-29 05:54:20 +00008880static std::pair<ValueDecl *, bool>
8881getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8882 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008883 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8884 RefExpr->containsUnexpandedParameterPack())
8885 return std::make_pair(nullptr, true);
8886
Alexey Bataevd985eda2016-02-10 11:29:16 +00008887 // OpenMP [3.1, C/C++]
8888 // A list item is a variable name.
8889 // OpenMP [2.9.3.3, Restrictions, p.1]
8890 // A variable that is part of another variable (as an array or
8891 // structure element) cannot appear in a private clause.
8892 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008893 enum {
8894 NoArrayExpr = -1,
8895 ArraySubscript = 0,
8896 OMPArraySection = 1
8897 } IsArrayExpr = NoArrayExpr;
8898 if (AllowArraySection) {
8899 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8900 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8901 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8902 Base = TempASE->getBase()->IgnoreParenImpCasts();
8903 RefExpr = Base;
8904 IsArrayExpr = ArraySubscript;
8905 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8906 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8907 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8908 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8909 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8910 Base = TempASE->getBase()->IgnoreParenImpCasts();
8911 RefExpr = Base;
8912 IsArrayExpr = OMPArraySection;
8913 }
8914 }
8915 ELoc = RefExpr->getExprLoc();
8916 ERange = RefExpr->getSourceRange();
8917 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008918 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8919 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8920 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8921 (S.getCurrentThisType().isNull() || !ME ||
8922 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8923 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008924 if (IsArrayExpr != NoArrayExpr)
8925 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8926 << ERange;
8927 else {
8928 S.Diag(ELoc,
8929 AllowArraySection
8930 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8931 : diag::err_omp_expected_var_name_member_expr)
8932 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8933 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008934 return std::make_pair(nullptr, false);
8935 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008936 return std::make_pair(
8937 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008938}
8939
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008940OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8941 SourceLocation StartLoc,
8942 SourceLocation LParenLoc,
8943 SourceLocation EndLoc) {
8944 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008945 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008946 for (auto &RefExpr : VarList) {
8947 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008948 SourceLocation ELoc;
8949 SourceRange ERange;
8950 Expr *SimpleRefExpr = RefExpr;
8951 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008952 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008953 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008954 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008955 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008956 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008957 ValueDecl *D = Res.first;
8958 if (!D)
8959 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008960
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008961 QualType Type = D->getType();
8962 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008963
8964 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8965 // A variable that appears in a private clause must not have an incomplete
8966 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008967 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008968 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008969 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008970
Alexey Bataev758e55e2013-09-06 18:03:48 +00008971 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8972 // in a Construct]
8973 // Variables with the predetermined data-sharing attributes may not be
8974 // listed in data-sharing attributes clauses, except for the cases
8975 // listed below. For these exceptions only, listing a predetermined
8976 // variable in a data-sharing attribute clause is allowed and overrides
8977 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008978 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008979 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008980 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8981 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008982 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008983 continue;
8984 }
8985
Kelvin Libf594a52016-12-17 05:48:59 +00008986 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008987 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008988 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008989 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008990 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8991 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008992 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008993 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008994 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008995 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008996 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008997 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008998 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008999 continue;
9000 }
9001
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009002 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9003 // A list item cannot appear in both a map clause and a data-sharing
9004 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009005 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009006 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009007 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009008 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009009 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009010 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009011 CurrDir == OMPD_target_parallel_for_simd ||
9012 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009013 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009014 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009015 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009016 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9017 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9018 ConflictKind = WhereFoundClauseKind;
9019 return true;
9020 })) {
9021 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009022 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009023 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009024 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009025 ReportOriginalDSA(*this, DSAStack, D, DVar);
9026 continue;
9027 }
9028 }
9029
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009030 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9031 // A variable of class type (or array thereof) that appears in a private
9032 // clause requires an accessible, unambiguous default constructor for the
9033 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009034 // Generate helper private variable and initialize it with the default
9035 // value. The address of the original variable is replaced by the address of
9036 // the new private variable in CodeGen. This new variable is not added to
9037 // IdResolver, so the code in the OpenMP region uses original variable for
9038 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009039 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009040 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9041 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009042 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009043 if (VDPrivate->isInvalidDecl())
9044 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009045 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009046 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009047
Alexey Bataev90c228f2016-02-08 09:29:13 +00009048 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009049 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009050 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009051 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009052 Vars.push_back((VD || CurContext->isDependentContext())
9053 ? RefExpr->IgnoreParens()
9054 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009055 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009056 }
9057
Alexey Bataeved09d242014-05-28 05:53:51 +00009058 if (Vars.empty())
9059 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009060
Alexey Bataev03b340a2014-10-21 03:16:40 +00009061 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9062 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009063}
9064
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009065namespace {
9066class DiagsUninitializedSeveretyRAII {
9067private:
9068 DiagnosticsEngine &Diags;
9069 SourceLocation SavedLoc;
9070 bool IsIgnored;
9071
9072public:
9073 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9074 bool IsIgnored)
9075 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9076 if (!IsIgnored) {
9077 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9078 /*Map*/ diag::Severity::Ignored, Loc);
9079 }
9080 }
9081 ~DiagsUninitializedSeveretyRAII() {
9082 if (!IsIgnored)
9083 Diags.popMappings(SavedLoc);
9084 }
9085};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009086}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009087
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009088OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9089 SourceLocation StartLoc,
9090 SourceLocation LParenLoc,
9091 SourceLocation EndLoc) {
9092 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009093 SmallVector<Expr *, 8> PrivateCopies;
9094 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009095 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009096 bool IsImplicitClause =
9097 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9098 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9099
Alexey Bataeved09d242014-05-28 05:53:51 +00009100 for (auto &RefExpr : VarList) {
9101 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009102 SourceLocation ELoc;
9103 SourceRange ERange;
9104 Expr *SimpleRefExpr = RefExpr;
9105 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009106 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009107 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009108 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009109 PrivateCopies.push_back(nullptr);
9110 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009111 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009112 ValueDecl *D = Res.first;
9113 if (!D)
9114 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009115
Alexey Bataev60da77e2016-02-29 05:54:20 +00009116 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009117 QualType Type = D->getType();
9118 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009119
9120 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9121 // A variable that appears in a private clause must not have an incomplete
9122 // type or a reference type.
9123 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009124 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009125 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009126 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009127
9128 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9129 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009130 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009131 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009132 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009133
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009134 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009135 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009136 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009137 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009138 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009139 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009140 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009141 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9142 // A list item that specifies a given variable may not appear in more
9143 // than one clause on the same directive, except that a variable may be
9144 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009145 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9146 // A list item may appear in a firstprivate or lastprivate clause but not
9147 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009148 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009149 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
9150 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009151 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009152 << getOpenMPClauseName(DVar.CKind)
9153 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009154 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009155 continue;
9156 }
9157
9158 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9159 // in a Construct]
9160 // Variables with the predetermined data-sharing attributes may not be
9161 // listed in data-sharing attributes clauses, except for the cases
9162 // listed below. For these exceptions only, listing a predetermined
9163 // variable in a data-sharing attribute clause is allowed and overrides
9164 // the variable's predetermined data-sharing attributes.
9165 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9166 // in a Construct, C/C++, p.2]
9167 // Variables with const-qualified type having no mutable member may be
9168 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009169 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009170 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9171 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009172 << getOpenMPClauseName(DVar.CKind)
9173 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009174 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009175 continue;
9176 }
9177
9178 // OpenMP [2.9.3.4, Restrictions, p.2]
9179 // A list item that is private within a parallel region must not appear
9180 // in a firstprivate clause on a worksharing construct if any of the
9181 // worksharing regions arising from the worksharing construct ever bind
9182 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009183 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9184 // A list item that is private within a teams region must not appear in a
9185 // firstprivate clause on a distribute construct if any of the distribute
9186 // regions arising from the distribute construct ever bind to any of the
9187 // teams regions arising from the teams construct.
9188 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9189 // A list item that appears in a reduction clause of a teams construct
9190 // must not appear in a firstprivate clause on a distribute construct if
9191 // any of the distribute regions arising from the distribute construct
9192 // ever bind to any of the teams regions arising from the teams construct.
9193 if ((isOpenMPWorksharingDirective(CurrDir) ||
9194 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009195 !isOpenMPParallelDirective(CurrDir) &&
9196 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009197 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009198 if (DVar.CKind != OMPC_shared &&
9199 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009200 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009201 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009202 Diag(ELoc, diag::err_omp_required_access)
9203 << getOpenMPClauseName(OMPC_firstprivate)
9204 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009205 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009206 continue;
9207 }
9208 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009209 // OpenMP [2.9.3.4, Restrictions, p.3]
9210 // A list item that appears in a reduction clause of a parallel construct
9211 // must not appear in a firstprivate clause on a worksharing or task
9212 // construct if any of the worksharing or task regions arising from the
9213 // worksharing or task construct ever bind to any of the parallel regions
9214 // arising from the parallel construct.
9215 // OpenMP [2.9.3.4, Restrictions, p.4]
9216 // A list item that appears in a reduction clause in worksharing
9217 // construct must not appear in a firstprivate clause in a task construct
9218 // encountered during execution of any of the worksharing regions arising
9219 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009220 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009221 DVar = DSAStack->hasInnermostDSA(
9222 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9223 [](OpenMPDirectiveKind K) -> bool {
9224 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009225 isOpenMPWorksharingDirective(K) ||
9226 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009227 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009228 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009229 if (DVar.CKind == OMPC_reduction &&
9230 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009231 isOpenMPWorksharingDirective(DVar.DKind) ||
9232 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009233 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9234 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009235 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009236 continue;
9237 }
9238 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009239
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009240 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9241 // A list item cannot appear in both a map clause and a data-sharing
9242 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009243 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009244 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009245 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009246 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009247 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009248 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009249 CurrDir == OMPD_target_parallel_for_simd ||
9250 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009251 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009252 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009253 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009254 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9255 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9256 ConflictKind = WhereFoundClauseKind;
9257 return true;
9258 })) {
9259 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009260 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009261 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009262 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9263 ReportOriginalDSA(*this, DSAStack, D, DVar);
9264 continue;
9265 }
9266 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009267 }
9268
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009269 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009270 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009271 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009272 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9273 << getOpenMPClauseName(OMPC_firstprivate) << Type
9274 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9275 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009276 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009277 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009278 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009280 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009281 continue;
9282 }
9283
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009284 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009285 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9286 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009287 // Generate helper private variable and initialize it with the value of the
9288 // original variable. The address of the original variable is replaced by
9289 // the address of the new private variable in the CodeGen. This new variable
9290 // is not added to IdResolver, so the code in the OpenMP region uses
9291 // original variable for proper diagnostics and variable capturing.
9292 Expr *VDInitRefExpr = nullptr;
9293 // For arrays generate initializer for single element and replace it by the
9294 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009295 if (Type->isArrayType()) {
9296 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009297 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009298 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009299 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009300 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009301 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009302 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009303 InitializedEntity Entity =
9304 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009305 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9306
9307 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9308 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9309 if (Result.isInvalid())
9310 VDPrivate->setInvalidDecl();
9311 else
9312 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009313 // Remove temp variable declaration.
9314 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009315 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009316 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9317 ".firstprivate.temp");
9318 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9319 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009320 AddInitializerToDecl(VDPrivate,
9321 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009322 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009323 }
9324 if (VDPrivate->isInvalidDecl()) {
9325 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009326 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009327 diag::note_omp_task_predetermined_firstprivate_here);
9328 }
9329 continue;
9330 }
9331 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009332 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009333 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9334 RefExpr->getExprLoc());
9335 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009336 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009337 if (TopDVar.CKind == OMPC_lastprivate)
9338 Ref = TopDVar.PrivateCopy;
9339 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009340 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009341 if (!IsOpenMPCapturedDecl(D))
9342 ExprCaptures.push_back(Ref->getDecl());
9343 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009344 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009345 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009346 Vars.push_back((VD || CurContext->isDependentContext())
9347 ? RefExpr->IgnoreParens()
9348 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009349 PrivateCopies.push_back(VDPrivateRefExpr);
9350 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009351 }
9352
Alexey Bataeved09d242014-05-28 05:53:51 +00009353 if (Vars.empty())
9354 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009355
9356 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009357 Vars, PrivateCopies, Inits,
9358 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009359}
9360
Alexander Musman1bb328c2014-06-04 13:06:39 +00009361OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9362 SourceLocation StartLoc,
9363 SourceLocation LParenLoc,
9364 SourceLocation EndLoc) {
9365 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009366 SmallVector<Expr *, 8> SrcExprs;
9367 SmallVector<Expr *, 8> DstExprs;
9368 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009369 SmallVector<Decl *, 4> ExprCaptures;
9370 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009371 for (auto &RefExpr : VarList) {
9372 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009373 SourceLocation ELoc;
9374 SourceRange ERange;
9375 Expr *SimpleRefExpr = RefExpr;
9376 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009377 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009378 // It will be analyzed later.
9379 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009380 SrcExprs.push_back(nullptr);
9381 DstExprs.push_back(nullptr);
9382 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009383 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009384 ValueDecl *D = Res.first;
9385 if (!D)
9386 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009387
Alexey Bataev74caaf22016-02-20 04:09:36 +00009388 QualType Type = D->getType();
9389 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009390
9391 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9392 // A variable that appears in a lastprivate clause must not have an
9393 // incomplete type or a reference type.
9394 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009395 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009396 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009397 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009398
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009399 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009400 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9401 // in a Construct]
9402 // Variables with the predetermined data-sharing attributes may not be
9403 // listed in data-sharing attributes clauses, except for the cases
9404 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009405 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9406 // A list item may appear in a firstprivate or lastprivate clause but not
9407 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009408 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009409 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009410 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009411 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9412 Diag(ELoc, diag::err_omp_wrong_dsa)
9413 << getOpenMPClauseName(DVar.CKind)
9414 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009415 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009416 continue;
9417 }
9418
Alexey Bataevf29276e2014-06-18 04:14:57 +00009419 // OpenMP [2.14.3.5, Restrictions, p.2]
9420 // A list item that is private within a parallel region, or that appears in
9421 // the reduction clause of a parallel construct, must not appear in a
9422 // lastprivate clause on a worksharing construct if any of the corresponding
9423 // worksharing regions ever binds to any of the corresponding parallel
9424 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009425 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009426 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009427 !isOpenMPParallelDirective(CurrDir) &&
9428 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009429 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009430 if (DVar.CKind != OMPC_shared) {
9431 Diag(ELoc, diag::err_omp_required_access)
9432 << getOpenMPClauseName(OMPC_lastprivate)
9433 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009434 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009435 continue;
9436 }
9437 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009438
Alexander Musman1bb328c2014-06-04 13:06:39 +00009439 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009440 // A variable of class type (or array thereof) that appears in a
9441 // lastprivate clause requires an accessible, unambiguous default
9442 // constructor for the class type, unless the list item is also specified
9443 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009444 // A variable of class type (or array thereof) that appears in a
9445 // lastprivate clause requires an accessible, unambiguous copy assignment
9446 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009447 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009448 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009449 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009450 D->hasAttrs() ? &D->getAttrs() : nullptr);
9451 auto *PseudoSrcExpr =
9452 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009453 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009454 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009455 D->hasAttrs() ? &D->getAttrs() : nullptr);
9456 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009457 // For arrays generate assignment operation for single element and replace
9458 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009459 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009460 PseudoDstExpr, PseudoSrcExpr);
9461 if (AssignmentOp.isInvalid())
9462 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009463 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009464 /*DiscardedValue=*/true);
9465 if (AssignmentOp.isInvalid())
9466 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009467
Alexey Bataev74caaf22016-02-20 04:09:36 +00009468 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009469 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009470 if (TopDVar.CKind == OMPC_firstprivate)
9471 Ref = TopDVar.PrivateCopy;
9472 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009473 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009474 if (!IsOpenMPCapturedDecl(D))
9475 ExprCaptures.push_back(Ref->getDecl());
9476 }
9477 if (TopDVar.CKind == OMPC_firstprivate ||
9478 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009479 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009480 ExprResult RefRes = DefaultLvalueConversion(Ref);
9481 if (!RefRes.isUsable())
9482 continue;
9483 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009484 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9485 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009486 if (!PostUpdateRes.isUsable())
9487 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009488 ExprPostUpdates.push_back(
9489 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009490 }
9491 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009492 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009493 Vars.push_back((VD || CurContext->isDependentContext())
9494 ? RefExpr->IgnoreParens()
9495 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009496 SrcExprs.push_back(PseudoSrcExpr);
9497 DstExprs.push_back(PseudoDstExpr);
9498 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009499 }
9500
9501 if (Vars.empty())
9502 return nullptr;
9503
9504 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009505 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009506 buildPreInits(Context, ExprCaptures),
9507 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009508}
9509
Alexey Bataev758e55e2013-09-06 18:03:48 +00009510OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9511 SourceLocation StartLoc,
9512 SourceLocation LParenLoc,
9513 SourceLocation EndLoc) {
9514 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009515 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009516 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009517 SourceLocation ELoc;
9518 SourceRange ERange;
9519 Expr *SimpleRefExpr = RefExpr;
9520 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009521 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009522 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009523 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009524 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009525 ValueDecl *D = Res.first;
9526 if (!D)
9527 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009528
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009529 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009530 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9531 // in a Construct]
9532 // Variables with the predetermined data-sharing attributes may not be
9533 // listed in data-sharing attributes clauses, except for the cases
9534 // listed below. For these exceptions only, listing a predetermined
9535 // variable in a data-sharing attribute clause is allowed and overrides
9536 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009537 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009538 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9539 DVar.RefExpr) {
9540 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9541 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009542 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009543 continue;
9544 }
9545
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009546 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009547 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009548 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009549 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009550 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9551 ? RefExpr->IgnoreParens()
9552 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009553 }
9554
Alexey Bataeved09d242014-05-28 05:53:51 +00009555 if (Vars.empty())
9556 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009557
9558 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9559}
9560
Alexey Bataevc5e02582014-06-16 07:08:35 +00009561namespace {
9562class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9563 DSAStackTy *Stack;
9564
9565public:
9566 bool VisitDeclRefExpr(DeclRefExpr *E) {
9567 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009568 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009569 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9570 return false;
9571 if (DVar.CKind != OMPC_unknown)
9572 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009573 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9574 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009575 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009576 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009577 return true;
9578 return false;
9579 }
9580 return false;
9581 }
9582 bool VisitStmt(Stmt *S) {
9583 for (auto Child : S->children()) {
9584 if (Child && Visit(Child))
9585 return true;
9586 }
9587 return false;
9588 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009589 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009590};
Alexey Bataev23b69422014-06-18 07:08:49 +00009591} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009592
Alexey Bataev60da77e2016-02-29 05:54:20 +00009593namespace {
9594// Transform MemberExpression for specified FieldDecl of current class to
9595// DeclRefExpr to specified OMPCapturedExprDecl.
9596class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9597 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9598 ValueDecl *Field;
9599 DeclRefExpr *CapturedExpr;
9600
9601public:
9602 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9603 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9604
9605 ExprResult TransformMemberExpr(MemberExpr *E) {
9606 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9607 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009608 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009609 return CapturedExpr;
9610 }
9611 return BaseTransform::TransformMemberExpr(E);
9612 }
9613 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9614};
9615} // namespace
9616
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009617template <typename T>
9618static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9619 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9620 for (auto &Set : Lookups) {
9621 for (auto *D : Set) {
9622 if (auto Res = Gen(cast<ValueDecl>(D)))
9623 return Res;
9624 }
9625 }
9626 return T();
9627}
9628
9629static ExprResult
9630buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9631 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9632 const DeclarationNameInfo &ReductionId, QualType Ty,
9633 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9634 if (ReductionIdScopeSpec.isInvalid())
9635 return ExprError();
9636 SmallVector<UnresolvedSet<8>, 4> Lookups;
9637 if (S) {
9638 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9639 Lookup.suppressDiagnostics();
9640 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9641 auto *D = Lookup.getRepresentativeDecl();
9642 do {
9643 S = S->getParent();
9644 } while (S && !S->isDeclScope(D));
9645 if (S)
9646 S = S->getParent();
9647 Lookups.push_back(UnresolvedSet<8>());
9648 Lookups.back().append(Lookup.begin(), Lookup.end());
9649 Lookup.clear();
9650 }
9651 } else if (auto *ULE =
9652 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9653 Lookups.push_back(UnresolvedSet<8>());
9654 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009655 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009656 if (D == PrevD)
9657 Lookups.push_back(UnresolvedSet<8>());
9658 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9659 Lookups.back().addDecl(DRD);
9660 PrevD = D;
9661 }
9662 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009663 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9664 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009665 Ty->containsUnexpandedParameterPack() ||
9666 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9667 return !D->isInvalidDecl() &&
9668 (D->getType()->isDependentType() ||
9669 D->getType()->isInstantiationDependentType() ||
9670 D->getType()->containsUnexpandedParameterPack());
9671 })) {
9672 UnresolvedSet<8> ResSet;
9673 for (auto &Set : Lookups) {
9674 ResSet.append(Set.begin(), Set.end());
9675 // The last item marks the end of all declarations at the specified scope.
9676 ResSet.addDecl(Set[Set.size() - 1]);
9677 }
9678 return UnresolvedLookupExpr::Create(
9679 SemaRef.Context, /*NamingClass=*/nullptr,
9680 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9681 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9682 }
9683 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9684 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9685 if (!D->isInvalidDecl() &&
9686 SemaRef.Context.hasSameType(D->getType(), Ty))
9687 return D;
9688 return nullptr;
9689 }))
9690 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9691 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9692 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9693 if (!D->isInvalidDecl() &&
9694 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9695 !Ty.isMoreQualifiedThan(D->getType()))
9696 return D;
9697 return nullptr;
9698 })) {
9699 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9700 /*DetectVirtual=*/false);
9701 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9702 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9703 VD->getType().getUnqualifiedType()))) {
9704 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9705 /*DiagID=*/0) !=
9706 Sema::AR_inaccessible) {
9707 SemaRef.BuildBasePathArray(Paths, BasePath);
9708 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9709 }
9710 }
9711 }
9712 }
9713 if (ReductionIdScopeSpec.isSet()) {
9714 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9715 return ExprError();
9716 }
9717 return ExprEmpty();
9718}
9719
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009720namespace {
9721/// Data for the reduction-based clauses.
9722struct ReductionData {
9723 /// List of original reduction items.
9724 SmallVector<Expr *, 8> Vars;
9725 /// List of private copies of the reduction items.
9726 SmallVector<Expr *, 8> Privates;
9727 /// LHS expressions for the reduction_op expressions.
9728 SmallVector<Expr *, 8> LHSs;
9729 /// RHS expressions for the reduction_op expressions.
9730 SmallVector<Expr *, 8> RHSs;
9731 /// Reduction operation expression.
9732 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009733 /// Taskgroup descriptors for the corresponding reduction items in
9734 /// in_reduction clauses.
9735 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009736 /// List of captures for clause.
9737 SmallVector<Decl *, 4> ExprCaptures;
9738 /// List of postupdate expressions.
9739 SmallVector<Expr *, 4> ExprPostUpdates;
9740 ReductionData() = delete;
9741 /// Reserves required memory for the reduction data.
9742 ReductionData(unsigned Size) {
9743 Vars.reserve(Size);
9744 Privates.reserve(Size);
9745 LHSs.reserve(Size);
9746 RHSs.reserve(Size);
9747 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009748 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009749 ExprCaptures.reserve(Size);
9750 ExprPostUpdates.reserve(Size);
9751 }
9752 /// Stores reduction item and reduction operation only (required for dependent
9753 /// reduction item).
9754 void push(Expr *Item, Expr *ReductionOp) {
9755 Vars.emplace_back(Item);
9756 Privates.emplace_back(nullptr);
9757 LHSs.emplace_back(nullptr);
9758 RHSs.emplace_back(nullptr);
9759 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009760 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009761 }
9762 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009763 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9764 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009765 Vars.emplace_back(Item);
9766 Privates.emplace_back(Private);
9767 LHSs.emplace_back(LHS);
9768 RHSs.emplace_back(RHS);
9769 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009770 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009771 }
9772};
9773} // namespace
9774
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009775static bool CheckOMPArraySectionConstantForReduction(
9776 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9777 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9778 const Expr *Length = OASE->getLength();
9779 if (Length == nullptr) {
9780 // For array sections of the form [1:] or [:], we would need to analyze
9781 // the lower bound...
9782 if (OASE->getColonLoc().isValid())
9783 return false;
9784
9785 // This is an array subscript which has implicit length 1!
9786 SingleElement = true;
9787 ArraySizes.push_back(llvm::APSInt::get(1));
9788 } else {
9789 llvm::APSInt ConstantLengthValue;
9790 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9791 return false;
9792
9793 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9794 ArraySizes.push_back(ConstantLengthValue);
9795 }
9796
9797 // Get the base of this array section and walk up from there.
9798 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9799
9800 // We require length = 1 for all array sections except the right-most to
9801 // guarantee that the memory region is contiguous and has no holes in it.
9802 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9803 Length = TempOASE->getLength();
9804 if (Length == nullptr) {
9805 // For array sections of the form [1:] or [:], we would need to analyze
9806 // the lower bound...
9807 if (OASE->getColonLoc().isValid())
9808 return false;
9809
9810 // This is an array subscript which has implicit length 1!
9811 ArraySizes.push_back(llvm::APSInt::get(1));
9812 } else {
9813 llvm::APSInt ConstantLengthValue;
9814 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9815 ConstantLengthValue.getSExtValue() != 1)
9816 return false;
9817
9818 ArraySizes.push_back(ConstantLengthValue);
9819 }
9820 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9821 }
9822
9823 // If we have a single element, we don't need to add the implicit lengths.
9824 if (!SingleElement) {
9825 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9826 // Has implicit length 1!
9827 ArraySizes.push_back(llvm::APSInt::get(1));
9828 Base = TempASE->getBase()->IgnoreParenImpCasts();
9829 }
9830 }
9831
9832 // This array section can be privatized as a single value or as a constant
9833 // sized array.
9834 return true;
9835}
9836
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009837static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009838 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9839 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9840 SourceLocation ColonLoc, SourceLocation EndLoc,
9841 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009842 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009843 auto DN = ReductionId.getName();
9844 auto OOK = DN.getCXXOverloadedOperator();
9845 BinaryOperatorKind BOK = BO_Comma;
9846
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009847 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009848 // OpenMP [2.14.3.6, reduction clause]
9849 // C
9850 // reduction-identifier is either an identifier or one of the following
9851 // operators: +, -, *, &, |, ^, && and ||
9852 // C++
9853 // reduction-identifier is either an id-expression or one of the following
9854 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009855 switch (OOK) {
9856 case OO_Plus:
9857 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009858 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009859 break;
9860 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009861 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009862 break;
9863 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009864 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009865 break;
9866 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009867 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009868 break;
9869 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009870 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009871 break;
9872 case OO_AmpAmp:
9873 BOK = BO_LAnd;
9874 break;
9875 case OO_PipePipe:
9876 BOK = BO_LOr;
9877 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009878 case OO_New:
9879 case OO_Delete:
9880 case OO_Array_New:
9881 case OO_Array_Delete:
9882 case OO_Slash:
9883 case OO_Percent:
9884 case OO_Tilde:
9885 case OO_Exclaim:
9886 case OO_Equal:
9887 case OO_Less:
9888 case OO_Greater:
9889 case OO_LessEqual:
9890 case OO_GreaterEqual:
9891 case OO_PlusEqual:
9892 case OO_MinusEqual:
9893 case OO_StarEqual:
9894 case OO_SlashEqual:
9895 case OO_PercentEqual:
9896 case OO_CaretEqual:
9897 case OO_AmpEqual:
9898 case OO_PipeEqual:
9899 case OO_LessLess:
9900 case OO_GreaterGreater:
9901 case OO_LessLessEqual:
9902 case OO_GreaterGreaterEqual:
9903 case OO_EqualEqual:
9904 case OO_ExclaimEqual:
9905 case OO_PlusPlus:
9906 case OO_MinusMinus:
9907 case OO_Comma:
9908 case OO_ArrowStar:
9909 case OO_Arrow:
9910 case OO_Call:
9911 case OO_Subscript:
9912 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009913 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009914 case NUM_OVERLOADED_OPERATORS:
9915 llvm_unreachable("Unexpected reduction identifier");
9916 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009917 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009918 if (II->isStr("max"))
9919 BOK = BO_GT;
9920 else if (II->isStr("min"))
9921 BOK = BO_LT;
9922 }
9923 break;
9924 }
9925 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009926 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009927 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009928 else
9929 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009930 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009931
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009932 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9933 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009934 for (auto RefExpr : VarList) {
9935 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009936 // OpenMP [2.1, C/C++]
9937 // A list item is a variable or array section, subject to the restrictions
9938 // specified in Section 2.4 on page 42 and in each of the sections
9939 // describing clauses and directives for which a list appears.
9940 // OpenMP [2.14.3.3, Restrictions, p.1]
9941 // A variable that is part of another variable (as an array or
9942 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009943 if (!FirstIter && IR != ER)
9944 ++IR;
9945 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009946 SourceLocation ELoc;
9947 SourceRange ERange;
9948 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009949 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009950 /*AllowArraySection=*/true);
9951 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009952 // Try to find 'declare reduction' corresponding construct before using
9953 // builtin/overloaded operators.
9954 QualType Type = Context.DependentTy;
9955 CXXCastPath BasePath;
9956 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009957 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009958 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009959 Expr *ReductionOp = nullptr;
9960 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009961 (DeclareReductionRef.isUnset() ||
9962 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009963 ReductionOp = DeclareReductionRef.get();
9964 // It will be analyzed later.
9965 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009966 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009967 ValueDecl *D = Res.first;
9968 if (!D)
9969 continue;
9970
Alexey Bataev88202be2017-07-27 13:20:36 +00009971 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009972 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009973 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9974 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9975 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009976 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009977 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009978 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9979 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9980 Type = ATy->getElementType();
9981 else
9982 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009983 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009984 } else
9985 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9986 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009987
Alexey Bataevc5e02582014-06-16 07:08:35 +00009988 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9989 // A variable that appears in a private clause must not have an incomplete
9990 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009991 if (S.RequireCompleteType(ELoc, Type,
9992 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009993 continue;
9994 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009995 // A list item that appears in a reduction clause must not be
9996 // const-qualified.
9997 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009998 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009999 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010000 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10001 VarDecl::DeclarationOnly;
10002 S.Diag(D->getLocation(),
10003 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010004 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010005 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010006 continue;
10007 }
10008 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10009 // If a list-item is a reference type then it must bind to the same object
10010 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010011 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010012 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010013 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010014 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010015 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010016 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10017 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010018 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010019 continue;
10020 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010021 }
10022 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010023
Alexey Bataevc5e02582014-06-16 07:08:35 +000010024 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10025 // in a Construct]
10026 // Variables with the predetermined data-sharing attributes may not be
10027 // listed in data-sharing attributes clauses, except for the cases
10028 // listed below. For these exceptions only, listing a predetermined
10029 // variable in a data-sharing attribute clause is allowed and overrides
10030 // the variable's predetermined data-sharing attributes.
10031 // OpenMP [2.14.3.6, Restrictions, p.3]
10032 // Any number of reduction clauses can be specified on the directive,
10033 // but a list item can appear only once in the reduction clauses for that
10034 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010035 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010036 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010037 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010038 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010039 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010040 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010041 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010042 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010043 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010044 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010045 << getOpenMPClauseName(DVar.CKind)
10046 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010047 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010048 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010049 }
10050
10051 // OpenMP [2.14.3.6, Restrictions, p.1]
10052 // A list item that appears in a reduction clause of a worksharing
10053 // construct must be shared in the parallel regions to which any of the
10054 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010055 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010056 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010057 !isOpenMPParallelDirective(CurrDir) &&
10058 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010059 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010060 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010061 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010062 << getOpenMPClauseName(OMPC_reduction)
10063 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010064 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010065 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010066 }
10067 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010068
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010069 // Try to find 'declare reduction' corresponding construct before using
10070 // builtin/overloaded operators.
10071 CXXCastPath BasePath;
10072 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010073 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010074 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10075 if (DeclareReductionRef.isInvalid())
10076 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010077 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010078 (DeclareReductionRef.isUnset() ||
10079 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010080 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010081 continue;
10082 }
10083 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10084 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010085 S.Diag(ReductionId.getLocStart(),
10086 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010087 << Type << ReductionIdRange;
10088 continue;
10089 }
10090
10091 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10092 // The type of a list item that appears in a reduction clause must be valid
10093 // for the reduction-identifier. For a max or min reduction in C, the type
10094 // of the list item must be an allowed arithmetic data type: char, int,
10095 // float, double, or _Bool, possibly modified with long, short, signed, or
10096 // unsigned. For a max or min reduction in C++, the type of the list item
10097 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10098 // double, or bool, possibly modified with long, short, signed, or unsigned.
10099 if (DeclareReductionRef.isUnset()) {
10100 if ((BOK == BO_GT || BOK == BO_LT) &&
10101 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010102 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10103 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010104 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010105 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010106 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10107 VarDecl::DeclarationOnly;
10108 S.Diag(D->getLocation(),
10109 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010110 << D;
10111 }
10112 continue;
10113 }
10114 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010115 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010116 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10117 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010118 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010119 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10120 VarDecl::DeclarationOnly;
10121 S.Diag(D->getLocation(),
10122 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010123 << D;
10124 }
10125 continue;
10126 }
10127 }
10128
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010129 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010130 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010131 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010132 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010133 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010134 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010135
10136 // Try if we can determine constant lengths for all array sections and avoid
10137 // the VLA.
10138 bool ConstantLengthOASE = false;
10139 if (OASE) {
10140 bool SingleElement;
10141 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10142 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10143 Context, OASE, SingleElement, ArraySizes);
10144
10145 // If we don't have a single element, we must emit a constant array type.
10146 if (ConstantLengthOASE && !SingleElement) {
10147 for (auto &Size : ArraySizes) {
10148 PrivateTy = Context.getConstantArrayType(
10149 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10150 }
10151 }
10152 }
10153
10154 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010155 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010156 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010157 if (!Context.getTargetInfo().isVLASupported() &&
10158 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10159 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10160 S.Diag(ELoc, diag::note_vla_unsupported);
10161 continue;
10162 }
David Majnemer9d168222016-08-05 17:44:54 +000010163 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010164 // Create pseudo array type for private copy. The size for this array will
10165 // be generated during codegen.
10166 // For array subscripts or single variables Private Ty is the same as Type
10167 // (type of the variable or single array element).
10168 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010169 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010170 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010171 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010172 } else if (!ASE && !OASE &&
10173 Context.getAsArrayType(D->getType().getNonReferenceType()))
10174 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010175 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010176 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010177 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010178 // Add initializer for private variable.
10179 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010180 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10181 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010182 if (DeclareReductionRef.isUsable()) {
10183 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10184 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10185 if (DRD->getInitializer()) {
10186 Init = DRDRef;
10187 RHSVD->setInit(DRDRef);
10188 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010189 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010190 } else {
10191 switch (BOK) {
10192 case BO_Add:
10193 case BO_Xor:
10194 case BO_Or:
10195 case BO_LOr:
10196 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10197 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010198 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010199 break;
10200 case BO_Mul:
10201 case BO_LAnd:
10202 if (Type->isScalarType() || Type->isAnyComplexType()) {
10203 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010204 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010205 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010206 break;
10207 case BO_And: {
10208 // '&' reduction op - initializer is '~0'.
10209 QualType OrigType = Type;
10210 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10211 Type = ComplexTy->getElementType();
10212 if (Type->isRealFloatingType()) {
10213 llvm::APFloat InitValue =
10214 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10215 /*isIEEE=*/true);
10216 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10217 Type, ELoc);
10218 } else if (Type->isScalarType()) {
10219 auto Size = Context.getTypeSize(Type);
10220 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10221 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10222 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10223 }
10224 if (Init && OrigType->isAnyComplexType()) {
10225 // Init = 0xFFFF + 0xFFFFi;
10226 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010227 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010228 }
10229 Type = OrigType;
10230 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010231 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010232 case BO_LT:
10233 case BO_GT: {
10234 // 'min' reduction op - initializer is 'Largest representable number in
10235 // the reduction list item type'.
10236 // 'max' reduction op - initializer is 'Least representable number in
10237 // the reduction list item type'.
10238 if (Type->isIntegerType() || Type->isPointerType()) {
10239 bool IsSigned = Type->hasSignedIntegerRepresentation();
10240 auto Size = Context.getTypeSize(Type);
10241 QualType IntTy =
10242 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10243 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010244 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10245 : llvm::APInt::getMinValue(Size)
10246 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10247 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010248 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10249 if (Type->isPointerType()) {
10250 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010251 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010252 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010253 if (CastExpr.isInvalid())
10254 continue;
10255 Init = CastExpr.get();
10256 }
10257 } else if (Type->isRealFloatingType()) {
10258 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10259 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10260 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10261 Type, ELoc);
10262 }
10263 break;
10264 }
10265 case BO_PtrMemD:
10266 case BO_PtrMemI:
10267 case BO_MulAssign:
10268 case BO_Div:
10269 case BO_Rem:
10270 case BO_Sub:
10271 case BO_Shl:
10272 case BO_Shr:
10273 case BO_LE:
10274 case BO_GE:
10275 case BO_EQ:
10276 case BO_NE:
10277 case BO_AndAssign:
10278 case BO_XorAssign:
10279 case BO_OrAssign:
10280 case BO_Assign:
10281 case BO_AddAssign:
10282 case BO_SubAssign:
10283 case BO_DivAssign:
10284 case BO_RemAssign:
10285 case BO_ShlAssign:
10286 case BO_ShrAssign:
10287 case BO_Comma:
10288 llvm_unreachable("Unexpected reduction operation");
10289 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010290 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010291 if (Init && DeclareReductionRef.isUnset())
10292 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10293 else if (!Init)
10294 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010295 if (RHSVD->isInvalidDecl())
10296 continue;
10297 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010298 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10299 << Type << ReductionIdRange;
10300 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10301 VarDecl::DeclarationOnly;
10302 S.Diag(D->getLocation(),
10303 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010304 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010305 continue;
10306 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010307 // Store initializer for single element in private copy. Will be used during
10308 // codegen.
10309 PrivateVD->setInit(RHSVD->getInit());
10310 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010311 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010312 ExprResult ReductionOp;
10313 if (DeclareReductionRef.isUsable()) {
10314 QualType RedTy = DeclareReductionRef.get()->getType();
10315 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010316 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10317 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010318 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010319 LHS = S.DefaultLvalueConversion(LHS.get());
10320 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010321 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10322 CK_UncheckedDerivedToBase, LHS.get(),
10323 &BasePath, LHS.get()->getValueKind());
10324 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10325 CK_UncheckedDerivedToBase, RHS.get(),
10326 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010327 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010328 FunctionProtoType::ExtProtoInfo EPI;
10329 QualType Params[] = {PtrRedTy, PtrRedTy};
10330 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10331 auto *OVE = new (Context) OpaqueValueExpr(
10332 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010333 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010334 Expr *Args[] = {LHS.get(), RHS.get()};
10335 ReductionOp = new (Context)
10336 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10337 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010338 ReductionOp = S.BuildBinOp(
10339 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010340 if (ReductionOp.isUsable()) {
10341 if (BOK != BO_LT && BOK != BO_GT) {
10342 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010343 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10344 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010345 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010346 auto *ConditionalOp = new (Context)
10347 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10348 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010349 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010350 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10351 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010352 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010353 if (ReductionOp.isUsable())
10354 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010355 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010356 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010357 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010358 }
10359
Alexey Bataevfa312f32017-07-21 18:48:21 +000010360 // OpenMP [2.15.4.6, Restrictions, p.2]
10361 // A list item that appears in an in_reduction clause of a task construct
10362 // must appear in a task_reduction clause of a construct associated with a
10363 // taskgroup region that includes the participating task in its taskgroup
10364 // set. The construct associated with the innermost region that meets this
10365 // condition must specify the same reduction-identifier as the in_reduction
10366 // clause.
10367 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010368 SourceRange ParentSR;
10369 BinaryOperatorKind ParentBOK;
10370 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010371 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010372 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010373 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10374 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010375 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010376 Stack->getTopMostTaskgroupReductionData(
10377 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010378 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10379 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10380 if (!IsParentBOK && !IsParentReductionOp) {
10381 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10382 continue;
10383 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010384 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10385 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10386 IsParentReductionOp) {
10387 bool EmitError = true;
10388 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10389 llvm::FoldingSetNodeID RedId, ParentRedId;
10390 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10391 DeclareReductionRef.get()->Profile(RedId, Context,
10392 /*Canonical=*/true);
10393 EmitError = RedId != ParentRedId;
10394 }
10395 if (EmitError) {
10396 S.Diag(ReductionId.getLocStart(),
10397 diag::err_omp_reduction_identifier_mismatch)
10398 << ReductionIdRange << RefExpr->getSourceRange();
10399 S.Diag(ParentSR.getBegin(),
10400 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010401 << ParentSR
10402 << (IsParentBOK ? ParentBOKDSA.RefExpr
10403 : ParentReductionOpDSA.RefExpr)
10404 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010405 continue;
10406 }
10407 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010408 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10409 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010410 }
10411
Alexey Bataev60da77e2016-02-29 05:54:20 +000010412 DeclRefExpr *Ref = nullptr;
10413 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010414 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010415 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010416 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010417 VarsExpr =
10418 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10419 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010420 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010421 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010422 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010423 if (!S.IsOpenMPCapturedDecl(D)) {
10424 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010425 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010426 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010427 if (!RefRes.isUsable())
10428 continue;
10429 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010430 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10431 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010432 if (!PostUpdateRes.isUsable())
10433 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010434 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10435 Stack->getCurrentDirective() == OMPD_taskgroup) {
10436 S.Diag(RefExpr->getExprLoc(),
10437 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010438 << RefExpr->getSourceRange();
10439 continue;
10440 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010441 RD.ExprPostUpdates.emplace_back(
10442 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010443 }
10444 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010445 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010446 // All reduction items are still marked as reduction (to do not increase
10447 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010448 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010449 if (CurrDir == OMPD_taskgroup) {
10450 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010451 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10452 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010453 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010454 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010455 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010456 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10457 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010458 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010459 return RD.Vars.empty();
10460}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010461
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010462OMPClause *Sema::ActOnOpenMPReductionClause(
10463 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10464 SourceLocation ColonLoc, SourceLocation EndLoc,
10465 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10466 ArrayRef<Expr *> UnresolvedReductions) {
10467 ReductionData RD(VarList.size());
10468
Alexey Bataev169d96a2017-07-18 20:17:46 +000010469 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10470 StartLoc, LParenLoc, ColonLoc, EndLoc,
10471 ReductionIdScopeSpec, ReductionId,
10472 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010473 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010474
Alexey Bataevc5e02582014-06-16 07:08:35 +000010475 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010476 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10477 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10478 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10479 buildPreInits(Context, RD.ExprCaptures),
10480 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010481}
10482
Alexey Bataev169d96a2017-07-18 20:17:46 +000010483OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10484 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10485 SourceLocation ColonLoc, SourceLocation EndLoc,
10486 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10487 ArrayRef<Expr *> UnresolvedReductions) {
10488 ReductionData RD(VarList.size());
10489
10490 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10491 VarList, StartLoc, LParenLoc, ColonLoc,
10492 EndLoc, ReductionIdScopeSpec, ReductionId,
10493 UnresolvedReductions, RD))
10494 return nullptr;
10495
10496 return OMPTaskReductionClause::Create(
10497 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10498 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10499 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10500 buildPreInits(Context, RD.ExprCaptures),
10501 buildPostUpdate(*this, RD.ExprPostUpdates));
10502}
10503
Alexey Bataevfa312f32017-07-21 18:48:21 +000010504OMPClause *Sema::ActOnOpenMPInReductionClause(
10505 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10506 SourceLocation ColonLoc, SourceLocation EndLoc,
10507 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10508 ArrayRef<Expr *> UnresolvedReductions) {
10509 ReductionData RD(VarList.size());
10510
10511 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10512 StartLoc, LParenLoc, ColonLoc, EndLoc,
10513 ReductionIdScopeSpec, ReductionId,
10514 UnresolvedReductions, RD))
10515 return nullptr;
10516
10517 return OMPInReductionClause::Create(
10518 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10519 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010520 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010521 buildPreInits(Context, RD.ExprCaptures),
10522 buildPostUpdate(*this, RD.ExprPostUpdates));
10523}
10524
Alexey Bataevecba70f2016-04-12 11:02:11 +000010525bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10526 SourceLocation LinLoc) {
10527 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10528 LinKind == OMPC_LINEAR_unknown) {
10529 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10530 return true;
10531 }
10532 return false;
10533}
10534
10535bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10536 OpenMPLinearClauseKind LinKind,
10537 QualType Type) {
10538 auto *VD = dyn_cast_or_null<VarDecl>(D);
10539 // A variable must not have an incomplete type or a reference type.
10540 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10541 return true;
10542 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10543 !Type->isReferenceType()) {
10544 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10545 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10546 return true;
10547 }
10548 Type = Type.getNonReferenceType();
10549
10550 // A list item must not be const-qualified.
10551 if (Type.isConstant(Context)) {
10552 Diag(ELoc, diag::err_omp_const_variable)
10553 << getOpenMPClauseName(OMPC_linear);
10554 if (D) {
10555 bool IsDecl =
10556 !VD ||
10557 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10558 Diag(D->getLocation(),
10559 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10560 << D;
10561 }
10562 return true;
10563 }
10564
10565 // A list item must be of integral or pointer type.
10566 Type = Type.getUnqualifiedType().getCanonicalType();
10567 const auto *Ty = Type.getTypePtrOrNull();
10568 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10569 !Ty->isPointerType())) {
10570 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10571 if (D) {
10572 bool IsDecl =
10573 !VD ||
10574 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10575 Diag(D->getLocation(),
10576 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10577 << D;
10578 }
10579 return true;
10580 }
10581 return false;
10582}
10583
Alexey Bataev182227b2015-08-20 10:54:39 +000010584OMPClause *Sema::ActOnOpenMPLinearClause(
10585 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10586 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10587 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010588 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010589 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010590 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010591 SmallVector<Decl *, 4> ExprCaptures;
10592 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010593 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010594 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010595 for (auto &RefExpr : VarList) {
10596 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010597 SourceLocation ELoc;
10598 SourceRange ERange;
10599 Expr *SimpleRefExpr = RefExpr;
10600 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10601 /*AllowArraySection=*/false);
10602 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010603 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010604 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010605 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010606 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010607 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010608 ValueDecl *D = Res.first;
10609 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010610 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010611
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010612 QualType Type = D->getType();
10613 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010614
10615 // OpenMP [2.14.3.7, linear clause]
10616 // A list-item cannot appear in more than one linear clause.
10617 // A list-item that appears in a linear clause cannot appear in any
10618 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010619 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010620 if (DVar.RefExpr) {
10621 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10622 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010623 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010624 continue;
10625 }
10626
Alexey Bataevecba70f2016-04-12 11:02:11 +000010627 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010628 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010629 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010630
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010631 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010632 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10633 D->hasAttrs() ? &D->getAttrs() : nullptr);
10634 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010635 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010636 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010637 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010638 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010639 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010640 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10641 if (!IsOpenMPCapturedDecl(D)) {
10642 ExprCaptures.push_back(Ref->getDecl());
10643 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10644 ExprResult RefRes = DefaultLvalueConversion(Ref);
10645 if (!RefRes.isUsable())
10646 continue;
10647 ExprResult PostUpdateRes =
10648 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10649 SimpleRefExpr, RefRes.get());
10650 if (!PostUpdateRes.isUsable())
10651 continue;
10652 ExprPostUpdates.push_back(
10653 IgnoredValueConversions(PostUpdateRes.get()).get());
10654 }
10655 }
10656 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010657 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010658 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010659 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010660 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010661 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010662 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010663 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10664
10665 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010666 Vars.push_back((VD || CurContext->isDependentContext())
10667 ? RefExpr->IgnoreParens()
10668 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010669 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010670 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010671 }
10672
10673 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010674 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010675
10676 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010677 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010678 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10679 !Step->isInstantiationDependent() &&
10680 !Step->containsUnexpandedParameterPack()) {
10681 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010682 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010683 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010684 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010685 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010686
Alexander Musman3276a272015-03-21 10:12:56 +000010687 // Build var to save the step value.
10688 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010689 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010690 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010691 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010692 ExprResult CalcStep =
10693 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010694 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010695
Alexander Musman8dba6642014-04-22 13:09:42 +000010696 // Warn about zero linear step (it would be probably better specified as
10697 // making corresponding variables 'const').
10698 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010699 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10700 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010701 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10702 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010703 if (!IsConstant && CalcStep.isUsable()) {
10704 // Calculate the step beforehand instead of doing this on each iteration.
10705 // (This is not used if the number of iterations may be kfold-ed).
10706 CalcStepExpr = CalcStep.get();
10707 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010708 }
10709
Alexey Bataev182227b2015-08-20 10:54:39 +000010710 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10711 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010712 StepExpr, CalcStepExpr,
10713 buildPreInits(Context, ExprCaptures),
10714 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010715}
10716
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010717static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10718 Expr *NumIterations, Sema &SemaRef,
10719 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010720 // Walk the vars and build update/final expressions for the CodeGen.
10721 SmallVector<Expr *, 8> Updates;
10722 SmallVector<Expr *, 8> Finals;
10723 Expr *Step = Clause.getStep();
10724 Expr *CalcStep = Clause.getCalcStep();
10725 // OpenMP [2.14.3.7, linear clause]
10726 // If linear-step is not specified it is assumed to be 1.
10727 if (Step == nullptr)
10728 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010729 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010730 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010731 }
Alexander Musman3276a272015-03-21 10:12:56 +000010732 bool HasErrors = false;
10733 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010734 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010735 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010736 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010737 SourceLocation ELoc;
10738 SourceRange ERange;
10739 Expr *SimpleRefExpr = RefExpr;
10740 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10741 /*AllowArraySection=*/false);
10742 ValueDecl *D = Res.first;
10743 if (Res.second || !D) {
10744 Updates.push_back(nullptr);
10745 Finals.push_back(nullptr);
10746 HasErrors = true;
10747 continue;
10748 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010749 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000010750 // OpenMP [2.15.11, distribute simd Construct]
10751 // A list item may not appear in a linear clause, unless it is the loop
10752 // iteration variable.
10753 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
10754 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
10755 SemaRef.Diag(ELoc,
10756 diag::err_omp_linear_distribute_var_non_loop_iteration);
10757 Updates.push_back(nullptr);
10758 Finals.push_back(nullptr);
10759 HasErrors = true;
10760 continue;
10761 }
Alexander Musman3276a272015-03-21 10:12:56 +000010762 Expr *InitExpr = *CurInit;
10763
10764 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010765 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010766 Expr *CapturedRef;
10767 if (LinKind == OMPC_LINEAR_uval)
10768 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10769 else
10770 CapturedRef =
10771 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10772 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10773 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010774
10775 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010776 ExprResult Update;
10777 if (!Info.first) {
10778 Update =
10779 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10780 InitExpr, IV, Step, /* Subtract */ false);
10781 } else
10782 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010783 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10784 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010785
10786 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010787 ExprResult Final;
10788 if (!Info.first) {
10789 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10790 InitExpr, NumIterations, Step,
10791 /* Subtract */ false);
10792 } else
10793 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010794 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10795 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010796
Alexander Musman3276a272015-03-21 10:12:56 +000010797 if (!Update.isUsable() || !Final.isUsable()) {
10798 Updates.push_back(nullptr);
10799 Finals.push_back(nullptr);
10800 HasErrors = true;
10801 } else {
10802 Updates.push_back(Update.get());
10803 Finals.push_back(Final.get());
10804 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010805 ++CurInit;
10806 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010807 }
10808 Clause.setUpdates(Updates);
10809 Clause.setFinals(Finals);
10810 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010811}
10812
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010813OMPClause *Sema::ActOnOpenMPAlignedClause(
10814 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10815 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10816
10817 SmallVector<Expr *, 8> Vars;
10818 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010819 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10820 SourceLocation ELoc;
10821 SourceRange ERange;
10822 Expr *SimpleRefExpr = RefExpr;
10823 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10824 /*AllowArraySection=*/false);
10825 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010826 // It will be analyzed later.
10827 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010828 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010829 ValueDecl *D = Res.first;
10830 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010831 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010832
Alexey Bataev1efd1662016-03-29 10:59:56 +000010833 QualType QType = D->getType();
10834 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010835
10836 // OpenMP [2.8.1, simd construct, Restrictions]
10837 // The type of list items appearing in the aligned clause must be
10838 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010839 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010840 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010841 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010842 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010843 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010844 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010845 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010846 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010847 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010848 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010849 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010850 continue;
10851 }
10852
10853 // OpenMP [2.8.1, simd construct, Restrictions]
10854 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010855 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010856 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010857 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10858 << getOpenMPClauseName(OMPC_aligned);
10859 continue;
10860 }
10861
Alexey Bataev1efd1662016-03-29 10:59:56 +000010862 DeclRefExpr *Ref = nullptr;
10863 if (!VD && IsOpenMPCapturedDecl(D))
10864 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10865 Vars.push_back(DefaultFunctionArrayConversion(
10866 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10867 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010868 }
10869
10870 // OpenMP [2.8.1, simd construct, Description]
10871 // The parameter of the aligned clause, alignment, must be a constant
10872 // positive integer expression.
10873 // If no optional parameter is specified, implementation-defined default
10874 // alignments for SIMD instructions on the target platforms are assumed.
10875 if (Alignment != nullptr) {
10876 ExprResult AlignResult =
10877 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10878 if (AlignResult.isInvalid())
10879 return nullptr;
10880 Alignment = AlignResult.get();
10881 }
10882 if (Vars.empty())
10883 return nullptr;
10884
10885 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10886 EndLoc, Vars, Alignment);
10887}
10888
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010889OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10890 SourceLocation StartLoc,
10891 SourceLocation LParenLoc,
10892 SourceLocation EndLoc) {
10893 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010894 SmallVector<Expr *, 8> SrcExprs;
10895 SmallVector<Expr *, 8> DstExprs;
10896 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010897 for (auto &RefExpr : VarList) {
10898 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10899 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010900 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010901 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010902 SrcExprs.push_back(nullptr);
10903 DstExprs.push_back(nullptr);
10904 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010905 continue;
10906 }
10907
Alexey Bataeved09d242014-05-28 05:53:51 +000010908 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010909 // OpenMP [2.1, C/C++]
10910 // A list item is a variable name.
10911 // OpenMP [2.14.4.1, Restrictions, p.1]
10912 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010913 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010914 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010915 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10916 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010917 continue;
10918 }
10919
10920 Decl *D = DE->getDecl();
10921 VarDecl *VD = cast<VarDecl>(D);
10922
10923 QualType Type = VD->getType();
10924 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10925 // It will be analyzed later.
10926 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010927 SrcExprs.push_back(nullptr);
10928 DstExprs.push_back(nullptr);
10929 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010930 continue;
10931 }
10932
10933 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10934 // A list item that appears in a copyin clause must be threadprivate.
10935 if (!DSAStack->isThreadPrivate(VD)) {
10936 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010937 << getOpenMPClauseName(OMPC_copyin)
10938 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010939 continue;
10940 }
10941
10942 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10943 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010944 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010945 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010946 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010947 auto *SrcVD =
10948 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10949 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010950 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010951 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10952 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010953 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10954 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010955 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010956 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010957 // For arrays generate assignment operation for single element and replace
10958 // it by the original array element in CodeGen.
10959 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10960 PseudoDstExpr, PseudoSrcExpr);
10961 if (AssignmentOp.isInvalid())
10962 continue;
10963 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10964 /*DiscardedValue=*/true);
10965 if (AssignmentOp.isInvalid())
10966 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010967
10968 DSAStack->addDSA(VD, DE, OMPC_copyin);
10969 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010970 SrcExprs.push_back(PseudoSrcExpr);
10971 DstExprs.push_back(PseudoDstExpr);
10972 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010973 }
10974
Alexey Bataeved09d242014-05-28 05:53:51 +000010975 if (Vars.empty())
10976 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010977
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010978 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10979 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010980}
10981
Alexey Bataevbae9a792014-06-27 10:37:06 +000010982OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10983 SourceLocation StartLoc,
10984 SourceLocation LParenLoc,
10985 SourceLocation EndLoc) {
10986 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010987 SmallVector<Expr *, 8> SrcExprs;
10988 SmallVector<Expr *, 8> DstExprs;
10989 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010990 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010991 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10992 SourceLocation ELoc;
10993 SourceRange ERange;
10994 Expr *SimpleRefExpr = RefExpr;
10995 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10996 /*AllowArraySection=*/false);
10997 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010998 // It will be analyzed later.
10999 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011000 SrcExprs.push_back(nullptr);
11001 DstExprs.push_back(nullptr);
11002 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011003 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011004 ValueDecl *D = Res.first;
11005 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011006 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011007
Alexey Bataeve122da12016-03-17 10:50:17 +000011008 QualType Type = D->getType();
11009 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011010
11011 // OpenMP [2.14.4.2, Restrictions, p.2]
11012 // A list item that appears in a copyprivate clause may not appear in a
11013 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011014 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11015 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011016 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11017 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011018 Diag(ELoc, diag::err_omp_wrong_dsa)
11019 << getOpenMPClauseName(DVar.CKind)
11020 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011021 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011022 continue;
11023 }
11024
11025 // OpenMP [2.11.4.2, Restrictions, p.1]
11026 // All list items that appear in a copyprivate clause must be either
11027 // threadprivate or private in the enclosing context.
11028 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011029 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011030 if (DVar.CKind == OMPC_shared) {
11031 Diag(ELoc, diag::err_omp_required_access)
11032 << getOpenMPClauseName(OMPC_copyprivate)
11033 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011034 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011035 continue;
11036 }
11037 }
11038 }
11039
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011040 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011041 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011042 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011043 << getOpenMPClauseName(OMPC_copyprivate) << Type
11044 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011045 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011046 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011047 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011048 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011049 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011050 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011051 continue;
11052 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011053
Alexey Bataevbae9a792014-06-27 10:37:06 +000011054 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11055 // A variable of class type (or array thereof) that appears in a
11056 // copyin clause requires an accessible, unambiguous copy assignment
11057 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011058 Type = Context.getBaseElementType(Type.getNonReferenceType())
11059 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011060 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011061 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11062 D->hasAttrs() ? &D->getAttrs() : nullptr);
11063 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011064 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011065 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11066 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011067 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011068 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011069 PseudoDstExpr, PseudoSrcExpr);
11070 if (AssignmentOp.isInvalid())
11071 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011072 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011073 /*DiscardedValue=*/true);
11074 if (AssignmentOp.isInvalid())
11075 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011076
11077 // No need to mark vars as copyprivate, they are already threadprivate or
11078 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011079 assert(VD || IsOpenMPCapturedDecl(D));
11080 Vars.push_back(
11081 VD ? RefExpr->IgnoreParens()
11082 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011083 SrcExprs.push_back(PseudoSrcExpr);
11084 DstExprs.push_back(PseudoDstExpr);
11085 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011086 }
11087
11088 if (Vars.empty())
11089 return nullptr;
11090
Alexey Bataeva63048e2015-03-23 06:18:07 +000011091 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11092 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011093}
11094
Alexey Bataev6125da92014-07-21 11:26:11 +000011095OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11096 SourceLocation StartLoc,
11097 SourceLocation LParenLoc,
11098 SourceLocation EndLoc) {
11099 if (VarList.empty())
11100 return nullptr;
11101
11102 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11103}
Alexey Bataevdea47612014-07-23 07:46:59 +000011104
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011105OMPClause *
11106Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11107 SourceLocation DepLoc, SourceLocation ColonLoc,
11108 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11109 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011110 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011111 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011112 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011113 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011114 return nullptr;
11115 }
11116 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011117 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11118 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011119 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011120 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011121 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11122 /*Last=*/OMPC_DEPEND_unknown, Except)
11123 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011124 return nullptr;
11125 }
11126 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011127 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011128 llvm::APSInt DepCounter(/*BitWidth=*/32);
11129 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11130 if (DepKind == OMPC_DEPEND_sink) {
11131 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11132 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11133 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011134 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011135 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011136 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11137 DSAStack->getParentOrderedRegionParam()) {
11138 for (auto &RefExpr : VarList) {
11139 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000011140 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011141 // It will be analyzed later.
11142 Vars.push_back(RefExpr);
11143 continue;
11144 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011145
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011146 SourceLocation ELoc = RefExpr->getExprLoc();
11147 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11148 if (DepKind == OMPC_DEPEND_sink) {
11149 if (DepCounter >= TotalDepCount) {
11150 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11151 continue;
11152 }
11153 ++DepCounter;
11154 // OpenMP [2.13.9, Summary]
11155 // depend(dependence-type : vec), where dependence-type is:
11156 // 'sink' and where vec is the iteration vector, which has the form:
11157 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11158 // where n is the value specified by the ordered clause in the loop
11159 // directive, xi denotes the loop iteration variable of the i-th nested
11160 // loop associated with the loop directive, and di is a constant
11161 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000011162 if (CurContext->isDependentContext()) {
11163 // It will be analyzed later.
11164 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011165 continue;
11166 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011167 SimpleExpr = SimpleExpr->IgnoreImplicit();
11168 OverloadedOperatorKind OOK = OO_None;
11169 SourceLocation OOLoc;
11170 Expr *LHS = SimpleExpr;
11171 Expr *RHS = nullptr;
11172 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11173 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11174 OOLoc = BO->getOperatorLoc();
11175 LHS = BO->getLHS()->IgnoreParenImpCasts();
11176 RHS = BO->getRHS()->IgnoreParenImpCasts();
11177 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11178 OOK = OCE->getOperator();
11179 OOLoc = OCE->getOperatorLoc();
11180 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11181 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11182 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11183 OOK = MCE->getMethodDecl()
11184 ->getNameInfo()
11185 .getName()
11186 .getCXXOverloadedOperator();
11187 OOLoc = MCE->getCallee()->getExprLoc();
11188 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11189 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11190 }
11191 SourceLocation ELoc;
11192 SourceRange ERange;
11193 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11194 /*AllowArraySection=*/false);
11195 if (Res.second) {
11196 // It will be analyzed later.
11197 Vars.push_back(RefExpr);
11198 }
11199 ValueDecl *D = Res.first;
11200 if (!D)
11201 continue;
11202
11203 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11204 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11205 continue;
11206 }
11207 if (RHS) {
11208 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11209 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11210 if (RHSRes.isInvalid())
11211 continue;
11212 }
11213 if (!CurContext->isDependentContext() &&
11214 DSAStack->getParentOrderedRegionParam() &&
11215 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000011216 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11217 DepCounter.getZExtValue());
11218 if (VD) {
11219 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11220 << 1 << VD;
11221 } else {
11222 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11223 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011224 continue;
11225 }
11226 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011227 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011228 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011229 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000011230 (ASE &&
11231 !ASE->getBase()
11232 ->getType()
11233 .getNonReferenceType()
11234 ->isPointerType() &&
11235 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011236 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11237 << RefExpr->getSourceRange();
11238 continue;
11239 }
11240 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11241 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000011242 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011243 RefExpr->IgnoreParenImpCasts());
11244 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11245 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11246 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11247 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011248 continue;
11249 }
11250 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011251 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11252 }
11253
11254 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11255 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011256 DSAStack->getParentOrderedRegionParam() &&
11257 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11258 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011259 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11260 }
11261 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11262 Vars.empty())
11263 return nullptr;
11264 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011265 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11266 DepKind, DepLoc, ColonLoc, Vars);
11267 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11268 DSAStack->addDoacrossDependClause(C, OpsOffs);
11269 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011270}
Michael Wonge710d542015-08-07 16:16:36 +000011271
11272OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11273 SourceLocation LParenLoc,
11274 SourceLocation EndLoc) {
11275 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011276 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011277
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011278 // OpenMP [2.9.1, Restrictions]
11279 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011280 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11281 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011282 return nullptr;
11283
Alexey Bataev931e19b2017-10-02 16:32:39 +000011284 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011285 OpenMPDirectiveKind CaptureRegion =
11286 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11287 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev931e19b2017-10-02 16:32:39 +000011288 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11289 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11290 HelperValStmt = buildPreInits(Context, Captures);
11291 }
11292
11293 return new (Context)
11294 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011295}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011296
Kelvin Li0bff7af2015-11-23 05:32:03 +000011297static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11298 DSAStackTy *Stack, QualType QTy) {
11299 NamedDecl *ND;
11300 if (QTy->isIncompleteType(&ND)) {
11301 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11302 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011303 }
11304 return true;
11305}
11306
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011307/// \brief Return true if it can be proven that the provided array expression
11308/// (array section or array subscript) does NOT specify the whole size of the
11309/// array whose base type is \a BaseQTy.
11310static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11311 const Expr *E,
11312 QualType BaseQTy) {
11313 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11314
11315 // If this is an array subscript, it refers to the whole size if the size of
11316 // the dimension is constant and equals 1. Also, an array section assumes the
11317 // format of an array subscript if no colon is used.
11318 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11319 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11320 return ATy->getSize().getSExtValue() != 1;
11321 // Size can't be evaluated statically.
11322 return false;
11323 }
11324
11325 assert(OASE && "Expecting array section if not an array subscript.");
11326 auto *LowerBound = OASE->getLowerBound();
11327 auto *Length = OASE->getLength();
11328
11329 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011330 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011331 if (LowerBound) {
11332 llvm::APSInt ConstLowerBound;
11333 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11334 return false; // Can't get the integer value as a constant.
11335 if (ConstLowerBound.getSExtValue())
11336 return true;
11337 }
11338
11339 // If we don't have a length we covering the whole dimension.
11340 if (!Length)
11341 return false;
11342
11343 // If the base is a pointer, we don't have a way to get the size of the
11344 // pointee.
11345 if (BaseQTy->isPointerType())
11346 return false;
11347
11348 // We can only check if the length is the same as the size of the dimension
11349 // if we have a constant array.
11350 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11351 if (!CATy)
11352 return false;
11353
11354 llvm::APSInt ConstLength;
11355 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11356 return false; // Can't get the integer value as a constant.
11357
11358 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11359}
11360
11361// Return true if it can be proven that the provided array expression (array
11362// section or array subscript) does NOT specify a single element of the array
11363// whose base type is \a BaseQTy.
11364static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011365 const Expr *E,
11366 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011367 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11368
11369 // An array subscript always refer to a single element. Also, an array section
11370 // assumes the format of an array subscript if no colon is used.
11371 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11372 return false;
11373
11374 assert(OASE && "Expecting array section if not an array subscript.");
11375 auto *Length = OASE->getLength();
11376
11377 // If we don't have a length we have to check if the array has unitary size
11378 // for this dimension. Also, we should always expect a length if the base type
11379 // is pointer.
11380 if (!Length) {
11381 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11382 return ATy->getSize().getSExtValue() != 1;
11383 // We cannot assume anything.
11384 return false;
11385 }
11386
11387 // Check if the length evaluates to 1.
11388 llvm::APSInt ConstLength;
11389 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11390 return false; // Can't get the integer value as a constant.
11391
11392 return ConstLength.getSExtValue() != 1;
11393}
11394
Samuel Antao661c0902016-05-26 17:39:58 +000011395// Return the expression of the base of the mappable expression or null if it
11396// cannot be determined and do all the necessary checks to see if the expression
11397// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011398// components of the expression.
11399static Expr *CheckMapClauseExpressionBase(
11400 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011401 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11402 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011403 SourceLocation ELoc = E->getExprLoc();
11404 SourceRange ERange = E->getSourceRange();
11405
11406 // The base of elements of list in a map clause have to be either:
11407 // - a reference to variable or field.
11408 // - a member expression.
11409 // - an array expression.
11410 //
11411 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11412 // reference to 'r'.
11413 //
11414 // If we have:
11415 //
11416 // struct SS {
11417 // Bla S;
11418 // foo() {
11419 // #pragma omp target map (S.Arr[:12]);
11420 // }
11421 // }
11422 //
11423 // We want to retrieve the member expression 'this->S';
11424
11425 Expr *RelevantExpr = nullptr;
11426
Samuel Antao5de996e2016-01-22 20:21:36 +000011427 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11428 // If a list item is an array section, it must specify contiguous storage.
11429 //
11430 // For this restriction it is sufficient that we make sure only references
11431 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011432 // exist except in the rightmost expression (unless they cover the whole
11433 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011434 //
11435 // r.ArrS[3:5].Arr[6:7]
11436 //
11437 // r.ArrS[3:5].x
11438 //
11439 // but these would be valid:
11440 // r.ArrS[3].Arr[6:7]
11441 //
11442 // r.ArrS[3].x
11443
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011444 bool AllowUnitySizeArraySection = true;
11445 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011446
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011447 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011448 E = E->IgnoreParenImpCasts();
11449
11450 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11451 if (!isa<VarDecl>(CurE->getDecl()))
11452 break;
11453
11454 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011455
11456 // If we got a reference to a declaration, we should not expect any array
11457 // section before that.
11458 AllowUnitySizeArraySection = false;
11459 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011460
11461 // Record the component.
11462 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
11463 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000011464 continue;
11465 }
11466
11467 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11468 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11469
11470 if (isa<CXXThisExpr>(BaseE))
11471 // We found a base expression: this->Val.
11472 RelevantExpr = CurE;
11473 else
11474 E = BaseE;
11475
11476 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11477 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11478 << CurE->getSourceRange();
11479 break;
11480 }
11481
11482 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11483
11484 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11485 // A bit-field cannot appear in a map clause.
11486 //
11487 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011488 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11489 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011490 break;
11491 }
11492
11493 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11494 // If the type of a list item is a reference to a type T then the type
11495 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011496 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011497
11498 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11499 // A list item cannot be a variable that is a member of a structure with
11500 // a union type.
11501 //
11502 if (auto *RT = CurType->getAs<RecordType>())
11503 if (RT->isUnionType()) {
11504 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11505 << CurE->getSourceRange();
11506 break;
11507 }
11508
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011509 // If we got a member expression, we should not expect any array section
11510 // before that:
11511 //
11512 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11513 // If a list item is an element of a structure, only the rightmost symbol
11514 // of the variable reference can be an array section.
11515 //
11516 AllowUnitySizeArraySection = false;
11517 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011518
11519 // Record the component.
11520 CurComponents.push_back(
11521 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000011522 continue;
11523 }
11524
11525 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11526 E = CurE->getBase()->IgnoreParenImpCasts();
11527
11528 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11529 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11530 << 0 << CurE->getSourceRange();
11531 break;
11532 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011533
11534 // If we got an array subscript that express the whole dimension we
11535 // can have any array expressions before. If it only expressing part of
11536 // the dimension, we can only have unitary-size array expressions.
11537 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11538 E->getType()))
11539 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011540
11541 // Record the component - we don't have any declaration associated.
11542 CurComponents.push_back(
11543 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011544 continue;
11545 }
11546
11547 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011548 E = CurE->getBase()->IgnoreParenImpCasts();
11549
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011550 auto CurType =
11551 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11552
Samuel Antao5de996e2016-01-22 20:21:36 +000011553 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11554 // If the type of a list item is a reference to a type T then the type
11555 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011556 if (CurType->isReferenceType())
11557 CurType = CurType->getPointeeType();
11558
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011559 bool IsPointer = CurType->isAnyPointerType();
11560
11561 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011562 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11563 << 0 << CurE->getSourceRange();
11564 break;
11565 }
11566
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011567 bool NotWhole =
11568 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11569 bool NotUnity =
11570 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11571
Samuel Antaodab51bb2016-07-18 23:22:11 +000011572 if (AllowWholeSizeArraySection) {
11573 // Any array section is currently allowed. Allowing a whole size array
11574 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011575 //
11576 // If this array section refers to the whole dimension we can still
11577 // accept other array sections before this one, except if the base is a
11578 // pointer. Otherwise, only unitary sections are accepted.
11579 if (NotWhole || IsPointer)
11580 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011581 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011582 // A unity or whole array section is not allowed and that is not
11583 // compatible with the properties of the current array section.
11584 SemaRef.Diag(
11585 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11586 << CurE->getSourceRange();
11587 break;
11588 }
Samuel Antao90927002016-04-26 14:54:23 +000011589
11590 // Record the component - we don't have any declaration associated.
11591 CurComponents.push_back(
11592 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011593 continue;
11594 }
11595
11596 // If nothing else worked, this is not a valid map clause expression.
11597 SemaRef.Diag(ELoc,
11598 diag::err_omp_expected_named_var_member_or_array_expression)
11599 << ERange;
11600 break;
11601 }
11602
11603 return RelevantExpr;
11604}
11605
11606// Return true if expression E associated with value VD has conflicts with other
11607// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011608static bool CheckMapConflicts(
11609 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11610 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011611 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11612 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011613 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011614 SourceLocation ELoc = E->getExprLoc();
11615 SourceRange ERange = E->getSourceRange();
11616
11617 // In order to easily check the conflicts we need to match each component of
11618 // the expression under test with the components of the expressions that are
11619 // already in the stack.
11620
Samuel Antao5de996e2016-01-22 20:21:36 +000011621 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011622 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011623 "Map clause expression with unexpected base!");
11624
11625 // Variables to help detecting enclosing problems in data environment nests.
11626 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011627 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011628
Samuel Antao90927002016-04-26 14:54:23 +000011629 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11630 VD, CurrentRegionOnly,
11631 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011632 StackComponents,
11633 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011634
Samuel Antao5de996e2016-01-22 20:21:36 +000011635 assert(!StackComponents.empty() &&
11636 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011637 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011638 "Map clause expression with unexpected base!");
11639
Samuel Antao90927002016-04-26 14:54:23 +000011640 // The whole expression in the stack.
11641 auto *RE = StackComponents.front().getAssociatedExpression();
11642
Samuel Antao5de996e2016-01-22 20:21:36 +000011643 // Expressions must start from the same base. Here we detect at which
11644 // point both expressions diverge from each other and see if we can
11645 // detect if the memory referred to both expressions is contiguous and
11646 // do not overlap.
11647 auto CI = CurComponents.rbegin();
11648 auto CE = CurComponents.rend();
11649 auto SI = StackComponents.rbegin();
11650 auto SE = StackComponents.rend();
11651 for (; CI != CE && SI != SE; ++CI, ++SI) {
11652
11653 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11654 // At most one list item can be an array item derived from a given
11655 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011656 if (CurrentRegionOnly &&
11657 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11658 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11659 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11660 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11661 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011662 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011663 << CI->getAssociatedExpression()->getSourceRange();
11664 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11665 diag::note_used_here)
11666 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011667 return true;
11668 }
11669
11670 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011671 if (CI->getAssociatedExpression()->getStmtClass() !=
11672 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011673 break;
11674
11675 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011676 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011677 break;
11678 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011679 // Check if the extra components of the expressions in the enclosing
11680 // data environment are redundant for the current base declaration.
11681 // If they are, the maps completely overlap, which is legal.
11682 for (; SI != SE; ++SI) {
11683 QualType Type;
11684 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011685 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011686 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011687 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11688 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011689 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11690 Type =
11691 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11692 }
11693 if (Type.isNull() || Type->isAnyPointerType() ||
11694 CheckArrayExpressionDoesNotReferToWholeSize(
11695 SemaRef, SI->getAssociatedExpression(), Type))
11696 break;
11697 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011698
11699 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11700 // List items of map clauses in the same construct must not share
11701 // original storage.
11702 //
11703 // If the expressions are exactly the same or one is a subset of the
11704 // other, it means they are sharing storage.
11705 if (CI == CE && SI == SE) {
11706 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011707 if (CKind == OMPC_map)
11708 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11709 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011710 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011711 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11712 << ERange;
11713 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011714 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11715 << RE->getSourceRange();
11716 return true;
11717 } else {
11718 // If we find the same expression in the enclosing data environment,
11719 // that is legal.
11720 IsEnclosedByDataEnvironmentExpr = true;
11721 return false;
11722 }
11723 }
11724
Samuel Antao90927002016-04-26 14:54:23 +000011725 QualType DerivedType =
11726 std::prev(CI)->getAssociatedDeclaration()->getType();
11727 SourceLocation DerivedLoc =
11728 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011729
11730 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11731 // If the type of a list item is a reference to a type T then the type
11732 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011733 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011734
11735 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11736 // A variable for which the type is pointer and an array section
11737 // derived from that variable must not appear as list items of map
11738 // clauses of the same construct.
11739 //
11740 // Also, cover one of the cases in:
11741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11742 // If any part of the original storage of a list item has corresponding
11743 // storage in the device data environment, all of the original storage
11744 // must have corresponding storage in the device data environment.
11745 //
11746 if (DerivedType->isAnyPointerType()) {
11747 if (CI == CE || SI == SE) {
11748 SemaRef.Diag(
11749 DerivedLoc,
11750 diag::err_omp_pointer_mapped_along_with_derived_section)
11751 << DerivedLoc;
11752 } else {
11753 assert(CI != CE && SI != SE);
11754 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11755 << DerivedLoc;
11756 }
11757 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11758 << RE->getSourceRange();
11759 return true;
11760 }
11761
11762 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11763 // List items of map clauses in the same construct must not share
11764 // original storage.
11765 //
11766 // An expression is a subset of the other.
11767 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011768 if (CKind == OMPC_map)
11769 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11770 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011771 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011772 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11773 << ERange;
11774 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011775 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11776 << RE->getSourceRange();
11777 return true;
11778 }
11779
11780 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011781 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011782 if (!CurrentRegionOnly && SI != SE)
11783 EnclosingExpr = RE;
11784
11785 // The current expression is a subset of the expression in the data
11786 // environment.
11787 IsEnclosedByDataEnvironmentExpr |=
11788 (!CurrentRegionOnly && CI != CE && SI == SE);
11789
11790 return false;
11791 });
11792
11793 if (CurrentRegionOnly)
11794 return FoundError;
11795
11796 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11797 // If any part of the original storage of a list item has corresponding
11798 // storage in the device data environment, all of the original storage must
11799 // have corresponding storage in the device data environment.
11800 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11801 // If a list item is an element of a structure, and a different element of
11802 // the structure has a corresponding list item in the device data environment
11803 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011804 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011805 // data environment prior to the task encountering the construct.
11806 //
11807 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11808 SemaRef.Diag(ELoc,
11809 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11810 << ERange;
11811 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11812 << EnclosingExpr->getSourceRange();
11813 return true;
11814 }
11815
11816 return FoundError;
11817}
11818
Samuel Antao661c0902016-05-26 17:39:58 +000011819namespace {
11820// Utility struct that gathers all the related lists associated with a mappable
11821// expression.
11822struct MappableVarListInfo final {
11823 // The list of expressions.
11824 ArrayRef<Expr *> VarList;
11825 // The list of processed expressions.
11826 SmallVector<Expr *, 16> ProcessedVarList;
11827 // The mappble components for each expression.
11828 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11829 // The base declaration of the variable.
11830 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11831
11832 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11833 // We have a list of components and base declarations for each entry in the
11834 // variable list.
11835 VarComponents.reserve(VarList.size());
11836 VarBaseDeclarations.reserve(VarList.size());
11837 }
11838};
11839}
11840
11841// Check the validity of the provided variable list for the provided clause kind
11842// \a CKind. In the check process the valid expressions, and mappable expression
11843// components and variables are extracted and used to fill \a Vars,
11844// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11845// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11846static void
11847checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11848 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11849 SourceLocation StartLoc,
11850 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11851 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011852 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11853 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011854 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011855
Samuel Antao90927002016-04-26 14:54:23 +000011856 // Keep track of the mappable components and base declarations in this clause.
11857 // Each entry in the list is going to have a list of components associated. We
11858 // record each set of the components so that we can build the clause later on.
11859 // In the end we should have the same amount of declarations and component
11860 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011861
Samuel Antao661c0902016-05-26 17:39:58 +000011862 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011863 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011864 SourceLocation ELoc = RE->getExprLoc();
11865
Kelvin Li0bff7af2015-11-23 05:32:03 +000011866 auto *VE = RE->IgnoreParenLValueCasts();
11867
11868 if (VE->isValueDependent() || VE->isTypeDependent() ||
11869 VE->isInstantiationDependent() ||
11870 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011871 // We can only analyze this information once the missing information is
11872 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011873 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011874 continue;
11875 }
11876
11877 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011878
Samuel Antao5de996e2016-01-22 20:21:36 +000011879 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011880 SemaRef.Diag(ELoc,
11881 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011882 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011883 continue;
11884 }
11885
Samuel Antao90927002016-04-26 14:54:23 +000011886 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11887 ValueDecl *CurDeclaration = nullptr;
11888
11889 // Obtain the array or member expression bases if required. Also, fill the
11890 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011891 auto *BE =
11892 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011893 if (!BE)
11894 continue;
11895
Samuel Antao90927002016-04-26 14:54:23 +000011896 assert(!CurComponents.empty() &&
11897 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011898
Samuel Antao90927002016-04-26 14:54:23 +000011899 // For the following checks, we rely on the base declaration which is
11900 // expected to be associated with the last component. The declaration is
11901 // expected to be a variable or a field (if 'this' is being mapped).
11902 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11903 assert(CurDeclaration && "Null decl on map clause.");
11904 assert(
11905 CurDeclaration->isCanonicalDecl() &&
11906 "Expecting components to have associated only canonical declarations.");
11907
11908 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11909 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011910
11911 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011912 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011913
11914 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011915 // threadprivate variables cannot appear in a map clause.
11916 // OpenMP 4.5 [2.10.5, target update Construct]
11917 // threadprivate variables cannot appear in a from clause.
11918 if (VD && DSAS->isThreadPrivate(VD)) {
11919 auto DVar = DSAS->getTopDSA(VD, false);
11920 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11921 << getOpenMPClauseName(CKind);
11922 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011923 continue;
11924 }
11925
Samuel Antao5de996e2016-01-22 20:21:36 +000011926 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11927 // A list item cannot appear in both a map clause and a data-sharing
11928 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011929
Samuel Antao5de996e2016-01-22 20:21:36 +000011930 // Check conflicts with other map clause expressions. We check the conflicts
11931 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011932 // environment, because the restrictions are different. We only have to
11933 // check conflicts across regions for the map clauses.
11934 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11935 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011936 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011937 if (CKind == OMPC_map &&
11938 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11939 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011940 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011941
Samuel Antao661c0902016-05-26 17:39:58 +000011942 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011943 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11944 // If the type of a list item is a reference to a type T then the type will
11945 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011946 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011947
Samuel Antao661c0902016-05-26 17:39:58 +000011948 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11949 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011951 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011952 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11953 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011954 continue;
11955
Samuel Antao661c0902016-05-26 17:39:58 +000011956 if (CKind == OMPC_map) {
11957 // target enter data
11958 // OpenMP [2.10.2, Restrictions, p. 99]
11959 // A map-type must be specified in all map clauses and must be either
11960 // to or alloc.
11961 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11962 if (DKind == OMPD_target_enter_data &&
11963 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11964 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11965 << (IsMapTypeImplicit ? 1 : 0)
11966 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11967 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011968 continue;
11969 }
Samuel Antao661c0902016-05-26 17:39:58 +000011970
11971 // target exit_data
11972 // OpenMP [2.10.3, Restrictions, p. 102]
11973 // A map-type must be specified in all map clauses and must be either
11974 // from, release, or delete.
11975 if (DKind == OMPD_target_exit_data &&
11976 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11977 MapType == OMPC_MAP_delete)) {
11978 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11979 << (IsMapTypeImplicit ? 1 : 0)
11980 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11981 << getOpenMPDirectiveName(DKind);
11982 continue;
11983 }
11984
11985 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11986 // A list item cannot appear in both a map clause and a data-sharing
11987 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011988 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011989 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011990 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011991 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11992 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011993 auto DVar = DSAS->getTopDSA(VD, false);
11994 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011995 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011996 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011997 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011998 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11999 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12000 continue;
12001 }
12002 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012003 }
12004
Samuel Antao90927002016-04-26 14:54:23 +000012005 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012006 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012007
12008 // Store the components in the stack so that they can be used to check
12009 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012010 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12011 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012012
12013 // Save the components and declaration to create the clause. For purposes of
12014 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012015 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012016 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12017 MVLI.VarComponents.back().append(CurComponents.begin(),
12018 CurComponents.end());
12019 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12020 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012021 }
Samuel Antao661c0902016-05-26 17:39:58 +000012022}
12023
12024OMPClause *
12025Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12026 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12027 SourceLocation MapLoc, SourceLocation ColonLoc,
12028 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12029 SourceLocation LParenLoc, SourceLocation EndLoc) {
12030 MappableVarListInfo MVLI(VarList);
12031 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12032 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012033
Samuel Antao5de996e2016-01-22 20:21:36 +000012034 // We need to produce a map clause even if we don't have variables so that
12035 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012036 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12037 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12038 MVLI.VarComponents, MapTypeModifier, MapType,
12039 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012040}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012041
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012042QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12043 TypeResult ParsedType) {
12044 assert(ParsedType.isUsable());
12045
12046 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12047 if (ReductionType.isNull())
12048 return QualType();
12049
12050 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12051 // A type name in a declare reduction directive cannot be a function type, an
12052 // array type, a reference type, or a type qualified with const, volatile or
12053 // restrict.
12054 if (ReductionType.hasQualifiers()) {
12055 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12056 return QualType();
12057 }
12058
12059 if (ReductionType->isFunctionType()) {
12060 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12061 return QualType();
12062 }
12063 if (ReductionType->isReferenceType()) {
12064 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12065 return QualType();
12066 }
12067 if (ReductionType->isArrayType()) {
12068 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12069 return QualType();
12070 }
12071 return ReductionType;
12072}
12073
12074Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12075 Scope *S, DeclContext *DC, DeclarationName Name,
12076 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12077 AccessSpecifier AS, Decl *PrevDeclInScope) {
12078 SmallVector<Decl *, 8> Decls;
12079 Decls.reserve(ReductionTypes.size());
12080
12081 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012082 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012083 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12084 // A reduction-identifier may not be re-declared in the current scope for the
12085 // same type or for a type that is compatible according to the base language
12086 // rules.
12087 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12088 OMPDeclareReductionDecl *PrevDRD = nullptr;
12089 bool InCompoundScope = true;
12090 if (S != nullptr) {
12091 // Find previous declaration with the same name not referenced in other
12092 // declarations.
12093 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12094 InCompoundScope =
12095 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12096 LookupName(Lookup, S);
12097 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12098 /*AllowInlineNamespace=*/false);
12099 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12100 auto Filter = Lookup.makeFilter();
12101 while (Filter.hasNext()) {
12102 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12103 if (InCompoundScope) {
12104 auto I = UsedAsPrevious.find(PrevDecl);
12105 if (I == UsedAsPrevious.end())
12106 UsedAsPrevious[PrevDecl] = false;
12107 if (auto *D = PrevDecl->getPrevDeclInScope())
12108 UsedAsPrevious[D] = true;
12109 }
12110 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12111 PrevDecl->getLocation();
12112 }
12113 Filter.done();
12114 if (InCompoundScope) {
12115 for (auto &PrevData : UsedAsPrevious) {
12116 if (!PrevData.second) {
12117 PrevDRD = PrevData.first;
12118 break;
12119 }
12120 }
12121 }
12122 } else if (PrevDeclInScope != nullptr) {
12123 auto *PrevDRDInScope = PrevDRD =
12124 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12125 do {
12126 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12127 PrevDRDInScope->getLocation();
12128 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12129 } while (PrevDRDInScope != nullptr);
12130 }
12131 for (auto &TyData : ReductionTypes) {
12132 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12133 bool Invalid = false;
12134 if (I != PreviousRedeclTypes.end()) {
12135 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12136 << TyData.first;
12137 Diag(I->second, diag::note_previous_definition);
12138 Invalid = true;
12139 }
12140 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12141 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12142 Name, TyData.first, PrevDRD);
12143 DC->addDecl(DRD);
12144 DRD->setAccess(AS);
12145 Decls.push_back(DRD);
12146 if (Invalid)
12147 DRD->setInvalidDecl();
12148 else
12149 PrevDRD = DRD;
12150 }
12151
12152 return DeclGroupPtrTy::make(
12153 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12154}
12155
12156void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12157 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12158
12159 // Enter new function scope.
12160 PushFunctionScope();
12161 getCurFunction()->setHasBranchProtectedScope();
12162 getCurFunction()->setHasOMPDeclareReductionCombiner();
12163
12164 if (S != nullptr)
12165 PushDeclContext(S, DRD);
12166 else
12167 CurContext = DRD;
12168
Faisal Valid143a0c2017-04-01 21:30:49 +000012169 PushExpressionEvaluationContext(
12170 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012171
12172 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012173 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12174 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12175 // uses semantics of argument handles by value, but it should be passed by
12176 // reference. C lang does not support references, so pass all parameters as
12177 // pointers.
12178 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012179 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012180 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012181 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12182 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12183 // uses semantics of argument handles by value, but it should be passed by
12184 // reference. C lang does not support references, so pass all parameters as
12185 // pointers.
12186 // Create 'T omp_out;' variable.
12187 auto *OmpOutParm =
12188 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12189 if (S != nullptr) {
12190 PushOnScopeChains(OmpInParm, S);
12191 PushOnScopeChains(OmpOutParm, S);
12192 } else {
12193 DRD->addDecl(OmpInParm);
12194 DRD->addDecl(OmpOutParm);
12195 }
12196}
12197
12198void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12199 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12200 DiscardCleanupsInEvaluationContext();
12201 PopExpressionEvaluationContext();
12202
12203 PopDeclContext();
12204 PopFunctionScopeInfo();
12205
12206 if (Combiner != nullptr)
12207 DRD->setCombiner(Combiner);
12208 else
12209 DRD->setInvalidDecl();
12210}
12211
Alexey Bataev070f43a2017-09-06 14:49:58 +000012212VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012213 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12214
12215 // Enter new function scope.
12216 PushFunctionScope();
12217 getCurFunction()->setHasBranchProtectedScope();
12218
12219 if (S != nullptr)
12220 PushDeclContext(S, DRD);
12221 else
12222 CurContext = DRD;
12223
Faisal Valid143a0c2017-04-01 21:30:49 +000012224 PushExpressionEvaluationContext(
12225 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012226
12227 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012228 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12229 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12230 // uses semantics of argument handles by value, but it should be passed by
12231 // reference. C lang does not support references, so pass all parameters as
12232 // pointers.
12233 // Create 'T omp_priv;' variable.
12234 auto *OmpPrivParm =
12235 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012236 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12237 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12238 // uses semantics of argument handles by value, but it should be passed by
12239 // reference. C lang does not support references, so pass all parameters as
12240 // pointers.
12241 // Create 'T omp_orig;' variable.
12242 auto *OmpOrigParm =
12243 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012244 if (S != nullptr) {
12245 PushOnScopeChains(OmpPrivParm, S);
12246 PushOnScopeChains(OmpOrigParm, S);
12247 } else {
12248 DRD->addDecl(OmpPrivParm);
12249 DRD->addDecl(OmpOrigParm);
12250 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012251 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012252}
12253
Alexey Bataev070f43a2017-09-06 14:49:58 +000012254void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12255 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012256 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12257 DiscardCleanupsInEvaluationContext();
12258 PopExpressionEvaluationContext();
12259
12260 PopDeclContext();
12261 PopFunctionScopeInfo();
12262
Alexey Bataev070f43a2017-09-06 14:49:58 +000012263 if (Initializer != nullptr) {
12264 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12265 } else if (OmpPrivParm->hasInit()) {
12266 DRD->setInitializer(OmpPrivParm->getInit(),
12267 OmpPrivParm->isDirectInit()
12268 ? OMPDeclareReductionDecl::DirectInit
12269 : OMPDeclareReductionDecl::CopyInit);
12270 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012271 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012272 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012273}
12274
12275Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12276 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12277 for (auto *D : DeclReductions.get()) {
12278 if (IsValid) {
12279 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12280 if (S != nullptr)
12281 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12282 } else
12283 D->setInvalidDecl();
12284 }
12285 return DeclReductions;
12286}
12287
David Majnemer9d168222016-08-05 17:44:54 +000012288OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012289 SourceLocation StartLoc,
12290 SourceLocation LParenLoc,
12291 SourceLocation EndLoc) {
12292 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012293 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012294
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012295 // OpenMP [teams Constrcut, Restrictions]
12296 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012297 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12298 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012299 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012300
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012301 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012302 OpenMPDirectiveKind CaptureRegion =
12303 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12304 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012305 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12306 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12307 HelperValStmt = buildPreInits(Context, Captures);
12308 }
12309
12310 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12311 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012312}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012313
12314OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12315 SourceLocation StartLoc,
12316 SourceLocation LParenLoc,
12317 SourceLocation EndLoc) {
12318 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012319 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012320
12321 // OpenMP [teams Constrcut, Restrictions]
12322 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012323 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12324 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012325 return nullptr;
12326
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012327 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012328 OpenMPDirectiveKind CaptureRegion =
12329 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12330 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012331 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12332 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12333 HelperValStmt = buildPreInits(Context, Captures);
12334 }
12335
12336 return new (Context) OMPThreadLimitClause(
12337 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012338}
Alexey Bataeva0569352015-12-01 10:17:31 +000012339
12340OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12341 SourceLocation StartLoc,
12342 SourceLocation LParenLoc,
12343 SourceLocation EndLoc) {
12344 Expr *ValExpr = Priority;
12345
12346 // OpenMP [2.9.1, task Constrcut]
12347 // The priority-value is a non-negative numerical scalar expression.
12348 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12349 /*StrictlyPositive=*/false))
12350 return nullptr;
12351
12352 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12353}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012354
12355OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12356 SourceLocation StartLoc,
12357 SourceLocation LParenLoc,
12358 SourceLocation EndLoc) {
12359 Expr *ValExpr = Grainsize;
12360
12361 // OpenMP [2.9.2, taskloop Constrcut]
12362 // The parameter of the grainsize clause must be a positive integer
12363 // expression.
12364 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12365 /*StrictlyPositive=*/true))
12366 return nullptr;
12367
12368 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12369}
Alexey Bataev382967a2015-12-08 12:06:20 +000012370
12371OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12372 SourceLocation StartLoc,
12373 SourceLocation LParenLoc,
12374 SourceLocation EndLoc) {
12375 Expr *ValExpr = NumTasks;
12376
12377 // OpenMP [2.9.2, taskloop Constrcut]
12378 // The parameter of the num_tasks clause must be a positive integer
12379 // expression.
12380 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12381 /*StrictlyPositive=*/true))
12382 return nullptr;
12383
12384 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12385}
12386
Alexey Bataev28c75412015-12-15 08:19:24 +000012387OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12388 SourceLocation LParenLoc,
12389 SourceLocation EndLoc) {
12390 // OpenMP [2.13.2, critical construct, Description]
12391 // ... where hint-expression is an integer constant expression that evaluates
12392 // to a valid lock hint.
12393 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12394 if (HintExpr.isInvalid())
12395 return nullptr;
12396 return new (Context)
12397 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12398}
12399
Carlo Bertollib4adf552016-01-15 18:50:31 +000012400OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12401 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12402 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12403 SourceLocation EndLoc) {
12404 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12405 std::string Values;
12406 Values += "'";
12407 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12408 Values += "'";
12409 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12410 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12411 return nullptr;
12412 }
12413 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012414 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012415 if (ChunkSize) {
12416 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12417 !ChunkSize->isInstantiationDependent() &&
12418 !ChunkSize->containsUnexpandedParameterPack()) {
12419 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12420 ExprResult Val =
12421 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12422 if (Val.isInvalid())
12423 return nullptr;
12424
12425 ValExpr = Val.get();
12426
12427 // OpenMP [2.7.1, Restrictions]
12428 // chunk_size must be a loop invariant integer expression with a positive
12429 // value.
12430 llvm::APSInt Result;
12431 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12432 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12433 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12434 << "dist_schedule" << ChunkSize->getSourceRange();
12435 return nullptr;
12436 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012437 } else if (getOpenMPCaptureRegionForClause(
12438 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12439 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012440 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000012441 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12442 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12443 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012444 }
12445 }
12446 }
12447
12448 return new (Context)
12449 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012450 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012451}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012452
12453OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12454 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12455 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12456 SourceLocation KindLoc, SourceLocation EndLoc) {
12457 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012458 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012459 std::string Value;
12460 SourceLocation Loc;
12461 Value += "'";
12462 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12463 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012464 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012465 Loc = MLoc;
12466 } else {
12467 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012468 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012469 Loc = KindLoc;
12470 }
12471 Value += "'";
12472 Diag(Loc, diag::err_omp_unexpected_clause_value)
12473 << Value << getOpenMPClauseName(OMPC_defaultmap);
12474 return nullptr;
12475 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012476 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012477
12478 return new (Context)
12479 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12480}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012481
12482bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12483 DeclContext *CurLexicalContext = getCurLexicalContext();
12484 if (!CurLexicalContext->isFileContext() &&
12485 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012486 !CurLexicalContext->isExternCXXContext() &&
12487 !isa<CXXRecordDecl>(CurLexicalContext) &&
12488 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12489 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12490 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012491 Diag(Loc, diag::err_omp_region_not_file_context);
12492 return false;
12493 }
12494 if (IsInOpenMPDeclareTargetContext) {
12495 Diag(Loc, diag::err_omp_enclosed_declare_target);
12496 return false;
12497 }
12498
12499 IsInOpenMPDeclareTargetContext = true;
12500 return true;
12501}
12502
12503void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12504 assert(IsInOpenMPDeclareTargetContext &&
12505 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12506
12507 IsInOpenMPDeclareTargetContext = false;
12508}
12509
David Majnemer9d168222016-08-05 17:44:54 +000012510void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12511 CXXScopeSpec &ScopeSpec,
12512 const DeclarationNameInfo &Id,
12513 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12514 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012515 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12516 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12517
12518 if (Lookup.isAmbiguous())
12519 return;
12520 Lookup.suppressDiagnostics();
12521
12522 if (!Lookup.isSingleResult()) {
12523 if (TypoCorrection Corrected =
12524 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12525 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12526 CTK_ErrorRecovery)) {
12527 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12528 << Id.getName());
12529 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12530 return;
12531 }
12532
12533 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12534 return;
12535 }
12536
12537 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12538 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12539 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12540 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12541
12542 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12543 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12544 ND->addAttr(A);
12545 if (ASTMutationListener *ML = Context.getASTMutationListener())
12546 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12547 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12548 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12549 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12550 << Id.getName();
12551 }
12552 } else
12553 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12554}
12555
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012556static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12557 Sema &SemaRef, Decl *D) {
12558 if (!D)
12559 return;
12560 Decl *LD = nullptr;
12561 if (isa<TagDecl>(D)) {
12562 LD = cast<TagDecl>(D)->getDefinition();
12563 } else if (isa<VarDecl>(D)) {
12564 LD = cast<VarDecl>(D)->getDefinition();
12565
12566 // If this is an implicit variable that is legal and we do not need to do
12567 // anything.
12568 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012569 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12570 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12571 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012572 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012573 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012574 return;
12575 }
12576
12577 } else if (isa<FunctionDecl>(D)) {
12578 const FunctionDecl *FD = nullptr;
12579 if (cast<FunctionDecl>(D)->hasBody(FD))
12580 LD = const_cast<FunctionDecl *>(FD);
12581
12582 // If the definition is associated with the current declaration in the
12583 // target region (it can be e.g. a lambda) that is legal and we do not need
12584 // to do anything else.
12585 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012586 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12587 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12588 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012589 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012590 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012591 return;
12592 }
12593 }
12594 if (!LD)
12595 LD = D;
12596 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12597 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12598 // Outlined declaration is not declared target.
12599 if (LD->isOutOfLine()) {
12600 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12601 SemaRef.Diag(SL, diag::note_used_here) << SR;
12602 } else {
12603 DeclContext *DC = LD->getDeclContext();
12604 while (DC) {
12605 if (isa<FunctionDecl>(DC) &&
12606 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12607 break;
12608 DC = DC->getParent();
12609 }
12610 if (DC)
12611 return;
12612
12613 // Is not declared in target context.
12614 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12615 SemaRef.Diag(SL, diag::note_used_here) << SR;
12616 }
12617 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012618 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12619 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12620 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012621 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012622 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012623 }
12624}
12625
12626static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12627 Sema &SemaRef, DSAStackTy *Stack,
12628 ValueDecl *VD) {
12629 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12630 return true;
12631 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12632 return false;
12633 return true;
12634}
12635
12636void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12637 if (!D || D->isInvalidDecl())
12638 return;
12639 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12640 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12641 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12642 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12643 if (DSAStack->isThreadPrivate(VD)) {
12644 Diag(SL, diag::err_omp_threadprivate_in_target);
12645 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12646 return;
12647 }
12648 }
12649 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12650 // Problem if any with var declared with incomplete type will be reported
12651 // as normal, so no need to check it here.
12652 if ((E || !VD->getType()->isIncompleteType()) &&
12653 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12654 // Mark decl as declared target to prevent further diagnostic.
12655 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012656 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12657 Context, OMPDeclareTargetDeclAttr::MT_To);
12658 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012659 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012660 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012661 }
12662 return;
12663 }
12664 }
12665 if (!E) {
12666 // Checking declaration inside declare target region.
12667 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12668 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012669 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12670 Context, OMPDeclareTargetDeclAttr::MT_To);
12671 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012672 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012673 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012674 }
12675 return;
12676 }
12677 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12678}
Samuel Antao661c0902016-05-26 17:39:58 +000012679
12680OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12681 SourceLocation StartLoc,
12682 SourceLocation LParenLoc,
12683 SourceLocation EndLoc) {
12684 MappableVarListInfo MVLI(VarList);
12685 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12686 if (MVLI.ProcessedVarList.empty())
12687 return nullptr;
12688
12689 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12690 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12691 MVLI.VarComponents);
12692}
Samuel Antaoec172c62016-05-26 17:49:04 +000012693
12694OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12695 SourceLocation StartLoc,
12696 SourceLocation LParenLoc,
12697 SourceLocation EndLoc) {
12698 MappableVarListInfo MVLI(VarList);
12699 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12700 if (MVLI.ProcessedVarList.empty())
12701 return nullptr;
12702
12703 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12704 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12705 MVLI.VarComponents);
12706}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012707
12708OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12709 SourceLocation StartLoc,
12710 SourceLocation LParenLoc,
12711 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012712 MappableVarListInfo MVLI(VarList);
12713 SmallVector<Expr *, 8> PrivateCopies;
12714 SmallVector<Expr *, 8> Inits;
12715
Carlo Bertolli2404b172016-07-13 15:37:16 +000012716 for (auto &RefExpr : VarList) {
12717 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12718 SourceLocation ELoc;
12719 SourceRange ERange;
12720 Expr *SimpleRefExpr = RefExpr;
12721 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12722 if (Res.second) {
12723 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012724 MVLI.ProcessedVarList.push_back(RefExpr);
12725 PrivateCopies.push_back(nullptr);
12726 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012727 }
12728 ValueDecl *D = Res.first;
12729 if (!D)
12730 continue;
12731
12732 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012733 Type = Type.getNonReferenceType().getUnqualifiedType();
12734
12735 auto *VD = dyn_cast<VarDecl>(D);
12736
12737 // Item should be a pointer or reference to pointer.
12738 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012739 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12740 << 0 << RefExpr->getSourceRange();
12741 continue;
12742 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012743
12744 // Build the private variable and the expression that refers to it.
12745 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12746 D->hasAttrs() ? &D->getAttrs() : nullptr);
12747 if (VDPrivate->isInvalidDecl())
12748 continue;
12749
12750 CurContext->addDecl(VDPrivate);
12751 auto VDPrivateRefExpr = buildDeclRefExpr(
12752 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12753
12754 // Add temporary variable to initialize the private copy of the pointer.
12755 auto *VDInit =
12756 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12757 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12758 RefExpr->getExprLoc());
12759 AddInitializerToDecl(VDPrivate,
12760 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012761 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012762
12763 // If required, build a capture to implement the privatization initialized
12764 // with the current list item value.
12765 DeclRefExpr *Ref = nullptr;
12766 if (!VD)
12767 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12768 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12769 PrivateCopies.push_back(VDPrivateRefExpr);
12770 Inits.push_back(VDInitRefExpr);
12771
12772 // We need to add a data sharing attribute for this variable to make sure it
12773 // is correctly captured. A variable that shows up in a use_device_ptr has
12774 // similar properties of a first private variable.
12775 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12776
12777 // Create a mappable component for the list item. List items in this clause
12778 // only need a component.
12779 MVLI.VarBaseDeclarations.push_back(D);
12780 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12781 MVLI.VarComponents.back().push_back(
12782 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012783 }
12784
Samuel Antaocc10b852016-07-28 14:23:26 +000012785 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012786 return nullptr;
12787
Samuel Antaocc10b852016-07-28 14:23:26 +000012788 return OMPUseDevicePtrClause::Create(
12789 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12790 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012791}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012792
12793OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12794 SourceLocation StartLoc,
12795 SourceLocation LParenLoc,
12796 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012797 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012798 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012799 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012800 SourceLocation ELoc;
12801 SourceRange ERange;
12802 Expr *SimpleRefExpr = RefExpr;
12803 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12804 if (Res.second) {
12805 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012806 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012807 }
12808 ValueDecl *D = Res.first;
12809 if (!D)
12810 continue;
12811
12812 QualType Type = D->getType();
12813 // item should be a pointer or array or reference to pointer or array
12814 if (!Type.getNonReferenceType()->isPointerType() &&
12815 !Type.getNonReferenceType()->isArrayType()) {
12816 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12817 << 0 << RefExpr->getSourceRange();
12818 continue;
12819 }
Samuel Antao6890b092016-07-28 14:25:09 +000012820
12821 // Check if the declaration in the clause does not show up in any data
12822 // sharing attribute.
12823 auto DVar = DSAStack->getTopDSA(D, false);
12824 if (isOpenMPPrivate(DVar.CKind)) {
12825 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12826 << getOpenMPClauseName(DVar.CKind)
12827 << getOpenMPClauseName(OMPC_is_device_ptr)
12828 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12829 ReportOriginalDSA(*this, DSAStack, D, DVar);
12830 continue;
12831 }
12832
12833 Expr *ConflictExpr;
12834 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012835 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012836 [&ConflictExpr](
12837 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12838 OpenMPClauseKind) -> bool {
12839 ConflictExpr = R.front().getAssociatedExpression();
12840 return true;
12841 })) {
12842 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12843 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12844 << ConflictExpr->getSourceRange();
12845 continue;
12846 }
12847
12848 // Store the components in the stack so that they can be used to check
12849 // against other clauses later on.
12850 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12851 DSAStack->addMappableExpressionComponents(
12852 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12853
12854 // Record the expression we've just processed.
12855 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12856
12857 // Create a mappable component for the list item. List items in this clause
12858 // only need a component. We use a null declaration to signal fields in
12859 // 'this'.
12860 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12861 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12862 "Unexpected device pointer expression!");
12863 MVLI.VarBaseDeclarations.push_back(
12864 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12865 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12866 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012867 }
12868
Samuel Antao6890b092016-07-28 14:25:09 +000012869 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012870 return nullptr;
12871
Samuel Antao6890b092016-07-28 14:25:09 +000012872 return OMPIsDevicePtrClause::Create(
12873 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12874 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012875}