blob: eaf0f930f7da4feeedcf71964e70b257a4c09370 [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,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
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();
Kelvin Li59e3d192017-11-30 18:52:06 +00001509 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001510 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());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001935 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001936 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00001937 if (!FD)
1938 return;
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 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00001961 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001962 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001963 ImplicitMap.emplace_back(E);
1964 return;
1965 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001966
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001967 auto ELoc = E->getExprLoc();
1968 // OpenMP [2.9.3.6, Restrictions, p.2]
1969 // A list item that appears in a reduction clause of the innermost
1970 // enclosing worksharing or parallel construct may not be accessed in
1971 // an explicit task.
1972 DVar = Stack->hasInnermostDSA(
1973 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1974 [](OpenMPDirectiveKind K) -> bool {
1975 return isOpenMPParallelDirective(K) ||
1976 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1977 },
1978 /*FromParent=*/true);
1979 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1980 ErrorFound = true;
1981 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1982 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1983 return;
1984 }
1985
1986 // Define implicit data-sharing attributes for task.
1987 DVar = Stack->getImplicitDSA(FD, false);
1988 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1989 !Stack->isLoopControlVariable(FD).first)
1990 ImplicitFirstprivate.push_back(E);
1991 return;
1992 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00001993 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001994 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataevb7a9b742017-12-05 19:20:09 +00001995 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
1996 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00001997 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001998 auto *VD = cast<ValueDecl>(
1999 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2000 if (!Stack->checkMappableExprComponentListsForDecl(
2001 VD, /*CurrentRegionOnly=*/true,
2002 [&CurComponents](
2003 OMPClauseMappableExprCommon::MappableExprComponentListRef
2004 StackComponents,
2005 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002006 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002007 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002008 for (const auto &SC : llvm::reverse(StackComponents)) {
2009 // Do both expressions have the same kind?
2010 if (CCI->getAssociatedExpression()->getStmtClass() !=
2011 SC.getAssociatedExpression()->getStmtClass())
2012 if (!(isa<OMPArraySectionExpr>(
2013 SC.getAssociatedExpression()) &&
2014 isa<ArraySubscriptExpr>(
2015 CCI->getAssociatedExpression())))
2016 return false;
2017
2018 Decl *CCD = CCI->getAssociatedDeclaration();
2019 Decl *SCD = SC.getAssociatedDeclaration();
2020 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2021 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2022 if (SCD != CCD)
2023 return false;
2024 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002025 if (CCI == CCE)
2026 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002027 }
2028 return true;
2029 })) {
2030 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002031 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002032 } else
2033 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002034 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002035 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002036 for (auto *C : S->clauses()) {
2037 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002038 // for task|target directives.
2039 // Skip analysis of arguments of implicitly defined map clause for target
2040 // directives.
2041 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2042 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002043 for (auto *CC : C->children()) {
2044 if (CC)
2045 Visit(CC);
2046 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002047 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002048 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002049 }
2050 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002051 for (auto *C : S->children()) {
2052 if (C && !isa<OMPExecutableDirective>(C))
2053 Visit(C);
2054 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002055 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002056
2057 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002058 ArrayRef<Expr *> getImplicitFirstprivate() const {
2059 return ImplicitFirstprivate;
2060 }
2061 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002062 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002063 return VarsWithInheritedDSA;
2064 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002065
Alexey Bataev7ff55242014-06-19 09:13:45 +00002066 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2067 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002068};
Alexey Bataeved09d242014-05-28 05:53:51 +00002069} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002070
Alexey Bataevbae9a792014-06-27 10:37:06 +00002071void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002072 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002073 case OMPD_parallel:
2074 case OMPD_parallel_for:
2075 case OMPD_parallel_for_simd:
2076 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002077 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002078 case OMPD_teams_distribute:
2079 case OMPD_teams_distribute_simd: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002080 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002081 QualType KmpInt32PtrTy =
2082 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002083 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002084 std::make_pair(".global_tid.", KmpInt32PtrTy),
2085 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2086 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002087 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002088 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2089 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002090 break;
2091 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002092 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002093 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002094 case OMPD_target_parallel_for:
2095 case OMPD_target_parallel_for_simd: {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002096 Sema::CapturedParamNameType ParamsTarget[] = {
2097 std::make_pair(StringRef(), QualType()) // __context with shared vars
2098 };
2099 // Start a captured region for 'target' with no implicit parameters.
2100 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2101 ParamsTarget);
2102 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2103 QualType KmpInt32PtrTy =
2104 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002105 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002106 std::make_pair(".global_tid.", KmpInt32PtrTy),
2107 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2108 std::make_pair(StringRef(), QualType()) // __context with shared vars
2109 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002110 // Start a captured region for 'teams' or 'parallel'. Both regions have
2111 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002112 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002113 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002114 break;
2115 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002116 case OMPD_simd:
2117 case OMPD_for:
2118 case OMPD_for_simd:
2119 case OMPD_sections:
2120 case OMPD_section:
2121 case OMPD_single:
2122 case OMPD_master:
2123 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002124 case OMPD_taskgroup:
2125 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002126 case OMPD_distribute_simd:
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 Li02532872016-08-05 14:37:37 +00002201 case OMPD_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00002202 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002203 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002204 case OMPD_target_teams_distribute_parallel_for_simd:
2205 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002206 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2207 QualType KmpInt32PtrTy =
2208 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2209 Sema::CapturedParamNameType Params[] = {
2210 std::make_pair(".global_tid.", KmpInt32PtrTy),
2211 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2212 std::make_pair(".previous.lb.", Context.getSizeType()),
2213 std::make_pair(".previous.ub.", Context.getSizeType()),
2214 std::make_pair(StringRef(), QualType()) // __context with shared vars
2215 };
2216 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2217 Params);
2218 break;
2219 }
Alexey Bataev46506272017-12-05 17:41:34 +00002220 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002221 case OMPD_teams_distribute_parallel_for_simd: {
Carlo Bertolli62fae152017-11-20 20:46:39 +00002222 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2223 QualType KmpInt32PtrTy =
2224 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2225
2226 Sema::CapturedParamNameType ParamsTeams[] = {
2227 std::make_pair(".global_tid.", KmpInt32PtrTy),
2228 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2229 std::make_pair(StringRef(), QualType()) // __context with shared vars
2230 };
2231 // Start a captured region for 'target' with no implicit parameters.
2232 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2233 ParamsTeams);
2234
2235 Sema::CapturedParamNameType ParamsParallel[] = {
2236 std::make_pair(".global_tid.", KmpInt32PtrTy),
2237 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2238 std::make_pair(".previous.lb.", Context.getSizeType()),
2239 std::make_pair(".previous.ub.", Context.getSizeType()),
2240 std::make_pair(StringRef(), QualType()) // __context with shared vars
2241 };
2242 // Start a captured region for 'teams' or 'parallel'. Both regions have
2243 // the same implicit parameters.
2244 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2245 ParamsParallel);
2246 break;
2247 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002248 case OMPD_target_update:
2249 case OMPD_target_enter_data:
2250 case OMPD_target_exit_data: {
2251 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2252 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2253 FunctionProtoType::ExtProtoInfo EPI;
2254 EPI.Variadic = true;
2255 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2256 Sema::CapturedParamNameType Params[] = {
2257 std::make_pair(".global_tid.", KmpInt32Ty),
2258 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2259 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2260 std::make_pair(".copy_fn.",
2261 Context.getPointerType(CopyFnType).withConst()),
2262 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2263 std::make_pair(StringRef(), QualType()) // __context with shared vars
2264 };
2265 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2266 Params);
2267 // Mark this captured region as inlined, because we don't use outlined
2268 // function directly.
2269 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2270 AlwaysInlineAttr::CreateImplicit(
2271 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2272 break;
2273 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002274 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002275 case OMPD_taskyield:
2276 case OMPD_barrier:
2277 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002278 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002279 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002280 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002281 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002282 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002283 case OMPD_declare_target:
2284 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002285 llvm_unreachable("OpenMP Directive is not allowed");
2286 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002287 llvm_unreachable("Unknown OpenMP directive");
2288 }
2289}
2290
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002291int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2292 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2293 getOpenMPCaptureRegions(CaptureRegions, DKind);
2294 return CaptureRegions.size();
2295}
2296
Alexey Bataev3392d762016-02-16 11:18:12 +00002297static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002298 Expr *CaptureExpr, bool WithInit,
2299 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002300 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002301 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002302 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002303 QualType Ty = Init->getType();
2304 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2305 if (S.getLangOpts().CPlusPlus)
2306 Ty = C.getLValueReferenceType(Ty);
2307 else {
2308 Ty = C.getPointerType(Ty);
2309 ExprResult Res =
2310 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2311 if (!Res.isUsable())
2312 return nullptr;
2313 Init = Res.get();
2314 }
Alexey Bataev61205072016-03-02 04:57:40 +00002315 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002316 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002317 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2318 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002319 if (!WithInit)
2320 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002321 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002322 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002323 return CED;
2324}
2325
Alexey Bataev61205072016-03-02 04:57:40 +00002326static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2327 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002328 OMPCapturedExprDecl *CD;
2329 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2330 CD = cast<OMPCapturedExprDecl>(VD);
2331 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002332 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2333 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002334 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002335 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002336}
2337
Alexey Bataev5a3af132016-03-29 08:58:54 +00002338static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2339 if (!Ref) {
2340 auto *CD =
2341 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2342 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2343 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2344 CaptureExpr->getExprLoc());
2345 }
2346 ExprResult Res = Ref;
2347 if (!S.getLangOpts().CPlusPlus &&
2348 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2349 Ref->getType()->isPointerType())
2350 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2351 if (!Res.isUsable())
2352 return ExprError();
2353 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002354}
2355
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002356namespace {
2357// OpenMP directives parsed in this section are represented as a
2358// CapturedStatement with an associated statement. If a syntax error
2359// is detected during the parsing of the associated statement, the
2360// compiler must abort processing and close the CapturedStatement.
2361//
2362// Combined directives such as 'target parallel' have more than one
2363// nested CapturedStatements. This RAII ensures that we unwind out
2364// of all the nested CapturedStatements when an error is found.
2365class CaptureRegionUnwinderRAII {
2366private:
2367 Sema &S;
2368 bool &ErrorFound;
2369 OpenMPDirectiveKind DKind;
2370
2371public:
2372 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2373 OpenMPDirectiveKind DKind)
2374 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2375 ~CaptureRegionUnwinderRAII() {
2376 if (ErrorFound) {
2377 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2378 while (--ThisCaptureLevel >= 0)
2379 S.ActOnCapturedRegionError();
2380 }
2381 }
2382};
2383} // namespace
2384
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002385StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2386 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002387 bool ErrorFound = false;
2388 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2389 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002390 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002391 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002392 return StmtError();
2393 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002394
Alexey Bataev2ba67042017-11-28 21:11:44 +00002395 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2396 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002397 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002398 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002399 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002400 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002401 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002402 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002403 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2404 Clause->getClauseKind() == OMPC_in_reduction) {
2405 // Capture taskgroup task_reduction descriptors inside the tasking regions
2406 // with the corresponding in_reduction items.
2407 auto *IRC = cast<OMPInReductionClause>(Clause);
2408 for (auto *E : IRC->taskgroup_descriptors())
2409 if (E)
2410 MarkDeclarationsReferencedInExpr(E);
2411 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002412 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002413 Clause->getClauseKind() == OMPC_copyprivate ||
2414 (getLangOpts().OpenMPUseTLS &&
2415 getASTContext().getTargetInfo().isTLSSupported() &&
2416 Clause->getClauseKind() == OMPC_copyin)) {
2417 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002418 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002419 for (auto *VarRef : Clause->children()) {
2420 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002421 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002422 }
2423 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002424 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002425 } else if (CaptureRegions.size() > 1 ||
2426 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002427 if (auto *C = OMPClauseWithPreInit::get(Clause))
2428 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002429 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2430 if (auto *E = C->getPostUpdateExpr())
2431 MarkDeclarationsReferencedInExpr(E);
2432 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002433 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002434 if (Clause->getClauseKind() == OMPC_schedule)
2435 SC = cast<OMPScheduleClause>(Clause);
2436 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002437 OC = cast<OMPOrderedClause>(Clause);
2438 else if (Clause->getClauseKind() == OMPC_linear)
2439 LCs.push_back(cast<OMPLinearClause>(Clause));
2440 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002441 // OpenMP, 2.7.1 Loop Construct, Restrictions
2442 // The nonmonotonic modifier cannot be specified if an ordered clause is
2443 // specified.
2444 if (SC &&
2445 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2446 SC->getSecondScheduleModifier() ==
2447 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2448 OC) {
2449 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2450 ? SC->getFirstScheduleModifierLoc()
2451 : SC->getSecondScheduleModifierLoc(),
2452 diag::err_omp_schedule_nonmonotonic_ordered)
2453 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2454 ErrorFound = true;
2455 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002456 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2457 for (auto *C : LCs) {
2458 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2459 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2460 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002461 ErrorFound = true;
2462 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002463 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2464 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2465 OC->getNumForLoops()) {
2466 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2467 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2468 ErrorFound = true;
2469 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002470 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002471 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002472 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002473 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002474 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002475 // Mark all variables in private list clauses as used in inner region.
2476 // Required for proper codegen of combined directives.
2477 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002478 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002479 for (auto *C : PICs) {
2480 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2481 // Find the particular capture region for the clause if the
2482 // directive is a combined one with multiple capture regions.
2483 // If the directive is not a combined one, the capture region
2484 // associated with the clause is OMPD_unknown and is generated
2485 // only once.
2486 if (CaptureRegion == ThisCaptureRegion ||
2487 CaptureRegion == OMPD_unknown) {
2488 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2489 for (auto *D : DS->decls())
2490 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2491 }
2492 }
2493 }
2494 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002495 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002496 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002497 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002498}
2499
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002500static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2501 OpenMPDirectiveKind CancelRegion,
2502 SourceLocation StartLoc) {
2503 // CancelRegion is only needed for cancel and cancellation_point.
2504 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2505 return false;
2506
2507 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2508 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2509 return false;
2510
2511 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2512 << getOpenMPDirectiveName(CancelRegion);
2513 return true;
2514}
2515
2516static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002517 OpenMPDirectiveKind CurrentRegion,
2518 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002519 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002520 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002521 if (Stack->getCurScope()) {
2522 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002523 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002524 bool NestingProhibited = false;
2525 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002526 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002527 enum {
2528 NoRecommend,
2529 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002530 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002531 ShouldBeInTargetRegion,
2532 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002533 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002534 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002535 // OpenMP [2.16, Nesting of Regions]
2536 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002537 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002538 // An ordered construct with the simd clause is the only OpenMP
2539 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002540 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002541 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2542 // message.
2543 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2544 ? diag::err_omp_prohibited_region_simd
2545 : diag::warn_omp_nesting_simd);
2546 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002547 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002548 if (ParentRegion == OMPD_atomic) {
2549 // OpenMP [2.16, Nesting of Regions]
2550 // OpenMP constructs may not be nested inside an atomic region.
2551 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2552 return true;
2553 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002554 if (CurrentRegion == OMPD_section) {
2555 // OpenMP [2.7.2, sections Construct, Restrictions]
2556 // Orphaned section directives are prohibited. That is, the section
2557 // directives must appear within the sections construct and must not be
2558 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002559 if (ParentRegion != OMPD_sections &&
2560 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002561 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2562 << (ParentRegion != OMPD_unknown)
2563 << getOpenMPDirectiveName(ParentRegion);
2564 return true;
2565 }
2566 return false;
2567 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002568 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002569 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002570 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002571 if (ParentRegion == OMPD_unknown &&
2572 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002573 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002574 if (CurrentRegion == OMPD_cancellation_point ||
2575 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002576 // OpenMP [2.16, Nesting of Regions]
2577 // A cancellation point construct for which construct-type-clause is
2578 // taskgroup must be nested inside a task construct. A cancellation
2579 // point construct for which construct-type-clause is not taskgroup must
2580 // be closely nested inside an OpenMP construct that matches the type
2581 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002582 // A cancel construct for which construct-type-clause is taskgroup must be
2583 // nested inside a task construct. A cancel construct for which
2584 // construct-type-clause is not taskgroup must be closely nested inside an
2585 // OpenMP construct that matches the type specified in
2586 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002587 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002588 !((CancelRegion == OMPD_parallel &&
2589 (ParentRegion == OMPD_parallel ||
2590 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002591 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002592 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002593 ParentRegion == OMPD_target_parallel_for ||
2594 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002595 ParentRegion == OMPD_teams_distribute_parallel_for ||
2596 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002597 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2598 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002599 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2600 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002601 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002602 // OpenMP [2.16, Nesting of Regions]
2603 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002604 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002605 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002606 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002607 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2608 // OpenMP [2.16, Nesting of Regions]
2609 // A critical region may not be nested (closely or otherwise) inside a
2610 // critical region with the same name. Note that this restriction is not
2611 // sufficient to prevent deadlock.
2612 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002613 bool DeadLock = Stack->hasDirective(
2614 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2615 const DeclarationNameInfo &DNI,
2616 SourceLocation Loc) -> bool {
2617 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2618 PreviousCriticalLoc = Loc;
2619 return true;
2620 } else
2621 return false;
2622 },
2623 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002624 if (DeadLock) {
2625 SemaRef.Diag(StartLoc,
2626 diag::err_omp_prohibited_region_critical_same_name)
2627 << CurrentName.getName();
2628 if (PreviousCriticalLoc.isValid())
2629 SemaRef.Diag(PreviousCriticalLoc,
2630 diag::note_omp_previous_critical_region);
2631 return true;
2632 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002633 } else if (CurrentRegion == OMPD_barrier) {
2634 // OpenMP [2.16, Nesting of Regions]
2635 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002636 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002637 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2638 isOpenMPTaskingDirective(ParentRegion) ||
2639 ParentRegion == OMPD_master ||
2640 ParentRegion == OMPD_critical ||
2641 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002642 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002643 !isOpenMPParallelDirective(CurrentRegion) &&
2644 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002645 // OpenMP [2.16, Nesting of Regions]
2646 // A worksharing region may not be closely nested inside a worksharing,
2647 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002648 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2649 isOpenMPTaskingDirective(ParentRegion) ||
2650 ParentRegion == OMPD_master ||
2651 ParentRegion == OMPD_critical ||
2652 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002653 Recommend = ShouldBeInParallelRegion;
2654 } else if (CurrentRegion == OMPD_ordered) {
2655 // OpenMP [2.16, Nesting of Regions]
2656 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002657 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002658 // An ordered region must be closely nested inside a loop region (or
2659 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002660 // OpenMP [2.8.1,simd Construct, Restrictions]
2661 // An ordered construct with the simd clause is the only OpenMP construct
2662 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002663 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002664 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002665 !(isOpenMPSimdDirective(ParentRegion) ||
2666 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002667 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002668 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002669 // OpenMP [2.16, Nesting of Regions]
2670 // If specified, a teams construct must be contained within a target
2671 // construct.
2672 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002673 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002674 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002675 }
Kelvin Libf594a52016-12-17 05:48:59 +00002676 if (!NestingProhibited &&
2677 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2678 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2679 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002680 // OpenMP [2.16, Nesting of Regions]
2681 // distribute, parallel, parallel sections, parallel workshare, and the
2682 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2683 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002684 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2685 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002686 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002687 }
David Majnemer9d168222016-08-05 17:44:54 +00002688 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002689 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002690 // OpenMP 4.5 [2.17 Nesting of Regions]
2691 // The region associated with the distribute construct must be strictly
2692 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002693 NestingProhibited =
2694 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002695 Recommend = ShouldBeInTeamsRegion;
2696 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002697 if (!NestingProhibited &&
2698 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2699 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2700 // OpenMP 4.5 [2.17 Nesting of Regions]
2701 // If a target, target update, target data, target enter data, or
2702 // target exit data construct is encountered during execution of a
2703 // target region, the behavior is unspecified.
2704 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002705 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2706 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002707 if (isOpenMPTargetExecutionDirective(K)) {
2708 OffendingRegion = K;
2709 return true;
2710 } else
2711 return false;
2712 },
2713 false /* don't skip top directive */);
2714 CloseNesting = false;
2715 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002716 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002717 if (OrphanSeen) {
2718 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2719 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2720 } else {
2721 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2722 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2723 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2724 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002725 return true;
2726 }
2727 }
2728 return false;
2729}
2730
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002731static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2732 ArrayRef<OMPClause *> Clauses,
2733 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2734 bool ErrorFound = false;
2735 unsigned NamedModifiersNumber = 0;
2736 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2737 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002738 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002739 for (const auto *C : Clauses) {
2740 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2741 // At most one if clause without a directive-name-modifier can appear on
2742 // the directive.
2743 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2744 if (FoundNameModifiers[CurNM]) {
2745 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2746 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2747 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2748 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002749 } else if (CurNM != OMPD_unknown) {
2750 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002751 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002752 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002753 FoundNameModifiers[CurNM] = IC;
2754 if (CurNM == OMPD_unknown)
2755 continue;
2756 // Check if the specified name modifier is allowed for the current
2757 // directive.
2758 // At most one if clause with the particular directive-name-modifier can
2759 // appear on the directive.
2760 bool MatchFound = false;
2761 for (auto NM : AllowedNameModifiers) {
2762 if (CurNM == NM) {
2763 MatchFound = true;
2764 break;
2765 }
2766 }
2767 if (!MatchFound) {
2768 S.Diag(IC->getNameModifierLoc(),
2769 diag::err_omp_wrong_if_directive_name_modifier)
2770 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2771 ErrorFound = true;
2772 }
2773 }
2774 }
2775 // If any if clause on the directive includes a directive-name-modifier then
2776 // all if clauses on the directive must include a directive-name-modifier.
2777 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2778 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2779 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2780 diag::err_omp_no_more_if_clause);
2781 } else {
2782 std::string Values;
2783 std::string Sep(", ");
2784 unsigned AllowedCnt = 0;
2785 unsigned TotalAllowedNum =
2786 AllowedNameModifiers.size() - NamedModifiersNumber;
2787 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2788 ++Cnt) {
2789 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2790 if (!FoundNameModifiers[NM]) {
2791 Values += "'";
2792 Values += getOpenMPDirectiveName(NM);
2793 Values += "'";
2794 if (AllowedCnt + 2 == TotalAllowedNum)
2795 Values += " or ";
2796 else if (AllowedCnt + 1 != TotalAllowedNum)
2797 Values += Sep;
2798 ++AllowedCnt;
2799 }
2800 }
2801 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2802 diag::err_omp_unnamed_if_clause)
2803 << (TotalAllowedNum > 1) << Values;
2804 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002805 for (auto Loc : NameModifierLoc) {
2806 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2807 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002808 ErrorFound = true;
2809 }
2810 return ErrorFound;
2811}
2812
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002813StmtResult Sema::ActOnOpenMPExecutableDirective(
2814 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2815 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2816 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002817 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002818 // First check CancelRegion which is then used in checkNestingOfRegions.
2819 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2820 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002821 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002822 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002823
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002824 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002825 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002826 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002827 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002828 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002829 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2830
2831 // Check default data sharing attributes for referenced variables.
2832 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002833 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2834 Stmt *S = AStmt;
2835 while (--ThisCaptureLevel >= 0)
2836 S = cast<CapturedStmt>(S)->getCapturedStmt();
2837 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002838 if (DSAChecker.isErrorFound())
2839 return StmtError();
2840 // Generate list of implicitly defined firstprivate variables.
2841 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002842
Alexey Bataev88202be2017-07-27 13:20:36 +00002843 SmallVector<Expr *, 4> ImplicitFirstprivates(
2844 DSAChecker.getImplicitFirstprivate().begin(),
2845 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002846 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2847 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002848 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2849 for (auto *C : Clauses) {
2850 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2851 for (auto *E : IRC->taskgroup_descriptors())
2852 if (E)
2853 ImplicitFirstprivates.emplace_back(E);
2854 }
2855 }
2856 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002857 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002858 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2859 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002860 ClausesWithImplicit.push_back(Implicit);
2861 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002862 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002863 } else
2864 ErrorFound = true;
2865 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002866 if (!ImplicitMaps.empty()) {
2867 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2868 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2869 SourceLocation(), SourceLocation(), ImplicitMaps,
2870 SourceLocation(), SourceLocation(), SourceLocation())) {
2871 ClausesWithImplicit.emplace_back(Implicit);
2872 ErrorFound |=
2873 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2874 } else
2875 ErrorFound = true;
2876 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002877 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002878
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002879 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002880 switch (Kind) {
2881 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002882 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2883 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002884 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002885 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002886 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002887 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2888 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002889 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002890 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002891 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2892 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002893 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002894 case OMPD_for_simd:
2895 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2896 EndLoc, VarsWithInheritedDSA);
2897 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002898 case OMPD_sections:
2899 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2900 EndLoc);
2901 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002902 case OMPD_section:
2903 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002904 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002905 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2906 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002907 case OMPD_single:
2908 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2909 EndLoc);
2910 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002911 case OMPD_master:
2912 assert(ClausesWithImplicit.empty() &&
2913 "No clauses are allowed for 'omp master' directive");
2914 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2915 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002916 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002917 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2918 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002919 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002920 case OMPD_parallel_for:
2921 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2922 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002923 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002924 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002925 case OMPD_parallel_for_simd:
2926 Res = ActOnOpenMPParallelForSimdDirective(
2927 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002928 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002929 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002930 case OMPD_parallel_sections:
2931 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2932 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002933 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002934 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002935 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002936 Res =
2937 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002938 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002939 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002940 case OMPD_taskyield:
2941 assert(ClausesWithImplicit.empty() &&
2942 "No clauses are allowed for 'omp taskyield' directive");
2943 assert(AStmt == nullptr &&
2944 "No associated statement allowed for 'omp taskyield' directive");
2945 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2946 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002947 case OMPD_barrier:
2948 assert(ClausesWithImplicit.empty() &&
2949 "No clauses are allowed for 'omp barrier' directive");
2950 assert(AStmt == nullptr &&
2951 "No associated statement allowed for 'omp barrier' directive");
2952 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2953 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002954 case OMPD_taskwait:
2955 assert(ClausesWithImplicit.empty() &&
2956 "No clauses are allowed for 'omp taskwait' directive");
2957 assert(AStmt == nullptr &&
2958 "No associated statement allowed for 'omp taskwait' directive");
2959 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2960 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002961 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002962 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2963 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002964 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002965 case OMPD_flush:
2966 assert(AStmt == nullptr &&
2967 "No associated statement allowed for 'omp flush' directive");
2968 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2969 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002970 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002971 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2972 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002973 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002974 case OMPD_atomic:
2975 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2976 EndLoc);
2977 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002978 case OMPD_teams:
2979 Res =
2980 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2981 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002982 case OMPD_target:
2983 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2984 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002985 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002986 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002987 case OMPD_target_parallel:
2988 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2989 StartLoc, EndLoc);
2990 AllowedNameModifiers.push_back(OMPD_target);
2991 AllowedNameModifiers.push_back(OMPD_parallel);
2992 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002993 case OMPD_target_parallel_for:
2994 Res = ActOnOpenMPTargetParallelForDirective(
2995 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2996 AllowedNameModifiers.push_back(OMPD_target);
2997 AllowedNameModifiers.push_back(OMPD_parallel);
2998 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002999 case OMPD_cancellation_point:
3000 assert(ClausesWithImplicit.empty() &&
3001 "No clauses are allowed for 'omp cancellation point' directive");
3002 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3003 "cancellation point' directive");
3004 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3005 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003006 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003007 assert(AStmt == nullptr &&
3008 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003009 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3010 CancelRegion);
3011 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003012 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003013 case OMPD_target_data:
3014 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3015 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003016 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003017 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003018 case OMPD_target_enter_data:
3019 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003020 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003021 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3022 break;
Samuel Antao72590762016-01-19 20:04:50 +00003023 case OMPD_target_exit_data:
3024 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003025 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003026 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3027 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003028 case OMPD_taskloop:
3029 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3030 EndLoc, VarsWithInheritedDSA);
3031 AllowedNameModifiers.push_back(OMPD_taskloop);
3032 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003033 case OMPD_taskloop_simd:
3034 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3035 EndLoc, VarsWithInheritedDSA);
3036 AllowedNameModifiers.push_back(OMPD_taskloop);
3037 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003038 case OMPD_distribute:
3039 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3040 EndLoc, VarsWithInheritedDSA);
3041 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003042 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003043 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3044 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003045 AllowedNameModifiers.push_back(OMPD_target_update);
3046 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003047 case OMPD_distribute_parallel_for:
3048 Res = ActOnOpenMPDistributeParallelForDirective(
3049 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3050 AllowedNameModifiers.push_back(OMPD_parallel);
3051 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003052 case OMPD_distribute_parallel_for_simd:
3053 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3054 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3055 AllowedNameModifiers.push_back(OMPD_parallel);
3056 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003057 case OMPD_distribute_simd:
3058 Res = ActOnOpenMPDistributeSimdDirective(
3059 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3060 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003061 case OMPD_target_parallel_for_simd:
3062 Res = ActOnOpenMPTargetParallelForSimdDirective(
3063 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3064 AllowedNameModifiers.push_back(OMPD_target);
3065 AllowedNameModifiers.push_back(OMPD_parallel);
3066 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003067 case OMPD_target_simd:
3068 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3069 EndLoc, VarsWithInheritedDSA);
3070 AllowedNameModifiers.push_back(OMPD_target);
3071 break;
Kelvin Li02532872016-08-05 14:37:37 +00003072 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003073 Res = ActOnOpenMPTeamsDistributeDirective(
3074 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003075 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003076 case OMPD_teams_distribute_simd:
3077 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3078 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3079 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003080 case OMPD_teams_distribute_parallel_for_simd:
3081 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3082 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3083 AllowedNameModifiers.push_back(OMPD_parallel);
3084 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003085 case OMPD_teams_distribute_parallel_for:
3086 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3087 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3088 AllowedNameModifiers.push_back(OMPD_parallel);
3089 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003090 case OMPD_target_teams:
3091 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3092 EndLoc);
3093 AllowedNameModifiers.push_back(OMPD_target);
3094 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003095 case OMPD_target_teams_distribute:
3096 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3097 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3098 AllowedNameModifiers.push_back(OMPD_target);
3099 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003100 case OMPD_target_teams_distribute_parallel_for:
3101 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3102 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3103 AllowedNameModifiers.push_back(OMPD_target);
3104 AllowedNameModifiers.push_back(OMPD_parallel);
3105 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003106 case OMPD_target_teams_distribute_parallel_for_simd:
3107 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3108 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3109 AllowedNameModifiers.push_back(OMPD_target);
3110 AllowedNameModifiers.push_back(OMPD_parallel);
3111 break;
Kelvin Lida681182017-01-10 18:08:18 +00003112 case OMPD_target_teams_distribute_simd:
3113 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3114 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3115 AllowedNameModifiers.push_back(OMPD_target);
3116 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003117 case OMPD_declare_target:
3118 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003119 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003120 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003121 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003122 llvm_unreachable("OpenMP Directive is not allowed");
3123 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003124 llvm_unreachable("Unknown OpenMP directive");
3125 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003126
Alexey Bataev4acb8592014-07-07 13:01:15 +00003127 for (auto P : VarsWithInheritedDSA) {
3128 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3129 << P.first << P.second->getSourceRange();
3130 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003131 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3132
3133 if (!AllowedNameModifiers.empty())
3134 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3135 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003136
Alexey Bataeved09d242014-05-28 05:53:51 +00003137 if (ErrorFound)
3138 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003139 return Res;
3140}
3141
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003142Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3143 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003144 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003145 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3146 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003147 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003148 assert(Linears.size() == LinModifiers.size());
3149 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003150 if (!DG || DG.get().isNull())
3151 return DeclGroupPtrTy();
3152
3153 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003154 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003155 return DG;
3156 }
3157 auto *ADecl = DG.get().getSingleDecl();
3158 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3159 ADecl = FTD->getTemplatedDecl();
3160
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003161 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3162 if (!FD) {
3163 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003164 return DeclGroupPtrTy();
3165 }
3166
Alexey Bataev2af33e32016-04-07 12:45:37 +00003167 // OpenMP [2.8.2, declare simd construct, Description]
3168 // The parameter of the simdlen clause must be a constant positive integer
3169 // expression.
3170 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003171 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003172 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003173 // OpenMP [2.8.2, declare simd construct, Description]
3174 // The special this pointer can be used as if was one of the arguments to the
3175 // function in any of the linear, aligned, or uniform clauses.
3176 // The uniform clause declares one or more arguments to have an invariant
3177 // value for all concurrent invocations of the function in the execution of a
3178 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003179 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3180 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003181 for (auto *E : Uniforms) {
3182 E = E->IgnoreParenImpCasts();
3183 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3184 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3185 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3186 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003187 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3188 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003189 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003190 }
3191 if (isa<CXXThisExpr>(E)) {
3192 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003193 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003194 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003195 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3196 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003197 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003198 // OpenMP [2.8.2, declare simd construct, Description]
3199 // The aligned clause declares that the object to which each list item points
3200 // is aligned to the number of bytes expressed in the optional parameter of
3201 // the aligned clause.
3202 // The special this pointer can be used as if was one of the arguments to the
3203 // function in any of the linear, aligned, or uniform clauses.
3204 // The type of list items appearing in the aligned clause must be array,
3205 // pointer, reference to array, or reference to pointer.
3206 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3207 Expr *AlignedThis = nullptr;
3208 for (auto *E : Aligneds) {
3209 E = E->IgnoreParenImpCasts();
3210 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3211 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3212 auto *CanonPVD = PVD->getCanonicalDecl();
3213 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3214 FD->getParamDecl(PVD->getFunctionScopeIndex())
3215 ->getCanonicalDecl() == CanonPVD) {
3216 // OpenMP [2.8.1, simd construct, Restrictions]
3217 // A list-item cannot appear in more than one aligned clause.
3218 if (AlignedArgs.count(CanonPVD) > 0) {
3219 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3220 << 1 << E->getSourceRange();
3221 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3222 diag::note_omp_explicit_dsa)
3223 << getOpenMPClauseName(OMPC_aligned);
3224 continue;
3225 }
3226 AlignedArgs[CanonPVD] = E;
3227 QualType QTy = PVD->getType()
3228 .getNonReferenceType()
3229 .getUnqualifiedType()
3230 .getCanonicalType();
3231 const Type *Ty = QTy.getTypePtrOrNull();
3232 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3233 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3234 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3235 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3236 }
3237 continue;
3238 }
3239 }
3240 if (isa<CXXThisExpr>(E)) {
3241 if (AlignedThis) {
3242 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3243 << 2 << E->getSourceRange();
3244 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3245 << getOpenMPClauseName(OMPC_aligned);
3246 }
3247 AlignedThis = E;
3248 continue;
3249 }
3250 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3251 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3252 }
3253 // The optional parameter of the aligned clause, alignment, must be a constant
3254 // positive integer expression. If no optional parameter is specified,
3255 // implementation-defined default alignments for SIMD instructions on the
3256 // target platforms are assumed.
3257 SmallVector<Expr *, 4> NewAligns;
3258 for (auto *E : Alignments) {
3259 ExprResult Align;
3260 if (E)
3261 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3262 NewAligns.push_back(Align.get());
3263 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003264 // OpenMP [2.8.2, declare simd construct, Description]
3265 // The linear clause declares one or more list items to be private to a SIMD
3266 // lane and to have a linear relationship with respect to the iteration space
3267 // of a loop.
3268 // The special this pointer can be used as if was one of the arguments to the
3269 // function in any of the linear, aligned, or uniform clauses.
3270 // When a linear-step expression is specified in a linear clause it must be
3271 // either a constant integer expression or an integer-typed parameter that is
3272 // specified in a uniform clause on the directive.
3273 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3274 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3275 auto MI = LinModifiers.begin();
3276 for (auto *E : Linears) {
3277 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3278 ++MI;
3279 E = E->IgnoreParenImpCasts();
3280 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3281 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3282 auto *CanonPVD = PVD->getCanonicalDecl();
3283 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3284 FD->getParamDecl(PVD->getFunctionScopeIndex())
3285 ->getCanonicalDecl() == CanonPVD) {
3286 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3287 // A list-item cannot appear in more than one linear clause.
3288 if (LinearArgs.count(CanonPVD) > 0) {
3289 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3290 << getOpenMPClauseName(OMPC_linear)
3291 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3292 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3293 diag::note_omp_explicit_dsa)
3294 << getOpenMPClauseName(OMPC_linear);
3295 continue;
3296 }
3297 // Each argument can appear in at most one uniform or linear clause.
3298 if (UniformedArgs.count(CanonPVD) > 0) {
3299 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3300 << getOpenMPClauseName(OMPC_linear)
3301 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3302 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3303 diag::note_omp_explicit_dsa)
3304 << getOpenMPClauseName(OMPC_uniform);
3305 continue;
3306 }
3307 LinearArgs[CanonPVD] = E;
3308 if (E->isValueDependent() || E->isTypeDependent() ||
3309 E->isInstantiationDependent() ||
3310 E->containsUnexpandedParameterPack())
3311 continue;
3312 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3313 PVD->getOriginalType());
3314 continue;
3315 }
3316 }
3317 if (isa<CXXThisExpr>(E)) {
3318 if (UniformedLinearThis) {
3319 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3320 << getOpenMPClauseName(OMPC_linear)
3321 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3322 << E->getSourceRange();
3323 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3324 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3325 : OMPC_linear);
3326 continue;
3327 }
3328 UniformedLinearThis = E;
3329 if (E->isValueDependent() || E->isTypeDependent() ||
3330 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3331 continue;
3332 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3333 E->getType());
3334 continue;
3335 }
3336 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3337 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3338 }
3339 Expr *Step = nullptr;
3340 Expr *NewStep = nullptr;
3341 SmallVector<Expr *, 4> NewSteps;
3342 for (auto *E : Steps) {
3343 // Skip the same step expression, it was checked already.
3344 if (Step == E || !E) {
3345 NewSteps.push_back(E ? NewStep : nullptr);
3346 continue;
3347 }
3348 Step = E;
3349 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3350 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3351 auto *CanonPVD = PVD->getCanonicalDecl();
3352 if (UniformedArgs.count(CanonPVD) == 0) {
3353 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3354 << Step->getSourceRange();
3355 } else if (E->isValueDependent() || E->isTypeDependent() ||
3356 E->isInstantiationDependent() ||
3357 E->containsUnexpandedParameterPack() ||
3358 CanonPVD->getType()->hasIntegerRepresentation())
3359 NewSteps.push_back(Step);
3360 else {
3361 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3362 << Step->getSourceRange();
3363 }
3364 continue;
3365 }
3366 NewStep = Step;
3367 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3368 !Step->isInstantiationDependent() &&
3369 !Step->containsUnexpandedParameterPack()) {
3370 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3371 .get();
3372 if (NewStep)
3373 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3374 }
3375 NewSteps.push_back(NewStep);
3376 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003377 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3378 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003379 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003380 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3381 const_cast<Expr **>(Linears.data()), Linears.size(),
3382 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3383 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003384 ADecl->addAttr(NewAttr);
3385 return ConvertDeclToDeclGroup(ADecl);
3386}
3387
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003388StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3389 Stmt *AStmt,
3390 SourceLocation StartLoc,
3391 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003392 if (!AStmt)
3393 return StmtError();
3394
Alexey Bataev9959db52014-05-06 10:08:46 +00003395 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3396 // 1.2.2 OpenMP Language Terminology
3397 // Structured block - An executable statement with a single entry at the
3398 // top and a single exit at the bottom.
3399 // The point of exit cannot be a branch out of the structured block.
3400 // longjmp() and throw() must not violate the entry/exit criteria.
3401 CS->getCapturedDecl()->setNothrow();
3402
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003403 getCurFunction()->setHasBranchProtectedScope();
3404
Alexey Bataev25e5b442015-09-15 12:52:43 +00003405 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3406 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003407}
3408
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003409namespace {
3410/// \brief Helper class for checking canonical form of the OpenMP loops and
3411/// extracting iteration space of each loop in the loop nest, that will be used
3412/// for IR generation.
3413class OpenMPIterationSpaceChecker {
3414 /// \brief Reference to Sema.
3415 Sema &SemaRef;
3416 /// \brief A location for diagnostics (when there is no some better location).
3417 SourceLocation DefaultLoc;
3418 /// \brief A location for diagnostics (when increment is not compatible).
3419 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003420 /// \brief A source location for referring to loop init later.
3421 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003422 /// \brief A source location for referring to condition later.
3423 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003424 /// \brief A source location for referring to increment later.
3425 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003426 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003427 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003428 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003429 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003430 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003431 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003432 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003433 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003434 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003435 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003436 /// \brief This flag is true when condition is one of:
3437 /// Var < UB
3438 /// Var <= UB
3439 /// UB > Var
3440 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003441 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003442 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003443 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003444 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003445 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003446
3447public:
3448 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003449 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003450 /// \brief Check init-expr for canonical loop form and save loop counter
3451 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003452 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003453 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3454 /// for less/greater and for strict/non-strict comparison.
3455 bool CheckCond(Expr *S);
3456 /// \brief Check incr-expr for canonical loop form and return true if it
3457 /// does not conform, otherwise save loop step (#Step).
3458 bool CheckInc(Expr *S);
3459 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003460 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003461 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003463 /// \brief Source range of the loop init.
3464 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3465 /// \brief Source range of the loop condition.
3466 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3467 /// \brief Source range of the loop increment.
3468 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3469 /// \brief True if the step should be subtracted.
3470 bool ShouldSubtractStep() const { return SubtractStep; }
3471 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003472 Expr *
3473 BuildNumIterations(Scope *S, const bool LimitedType,
3474 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003475 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003476 Expr *BuildPreCond(Scope *S, Expr *Cond,
3477 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003478 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003479 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3480 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003481 /// \brief Build reference expression to the private counter be used for
3482 /// codegen.
3483 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003484 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003485 Expr *BuildCounterInit() const;
3486 /// \brief Build step of the counter be used for codegen.
3487 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003488 /// \brief Return true if any expression is dependent.
3489 bool Dependent() const;
3490
3491private:
3492 /// \brief Check the right-hand side of an assignment in the increment
3493 /// expression.
3494 bool CheckIncRHS(Expr *RHS);
3495 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003496 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003497 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003498 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003499 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003500 /// \brief Helper to set loop increment.
3501 bool SetStep(Expr *NewStep, bool Subtract);
3502};
3503
3504bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003505 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003506 assert(!LB && !UB && !Step);
3507 return false;
3508 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003509 return LCDecl->getType()->isDependentType() ||
3510 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3511 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003512}
3513
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003514bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3515 Expr *NewLCRefExpr,
3516 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003517 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003518 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003519 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003520 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003521 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003522 LCDecl = getCanonicalDecl(NewLCDecl);
3523 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003524 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3525 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003526 if ((Ctor->isCopyOrMoveConstructor() ||
3527 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3528 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003529 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003530 LB = NewLB;
3531 return false;
3532}
3533
3534bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003535 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003536 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003537 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3538 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003539 if (!NewUB)
3540 return true;
3541 UB = NewUB;
3542 TestIsLessOp = LessOp;
3543 TestIsStrictOp = StrictOp;
3544 ConditionSrcRange = SR;
3545 ConditionLoc = SL;
3546 return false;
3547}
3548
3549bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3550 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003551 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003552 if (!NewStep)
3553 return true;
3554 if (!NewStep->isValueDependent()) {
3555 // Check that the step is integer expression.
3556 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003557 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3558 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003559 if (Val.isInvalid())
3560 return true;
3561 NewStep = Val.get();
3562
3563 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3564 // If test-expr is of form var relational-op b and relational-op is < or
3565 // <= then incr-expr must cause var to increase on each iteration of the
3566 // loop. If test-expr is of form var relational-op b and relational-op is
3567 // > or >= then incr-expr must cause var to decrease on each iteration of
3568 // the loop.
3569 // If test-expr is of form b relational-op var and relational-op is < or
3570 // <= then incr-expr must cause var to decrease on each iteration of the
3571 // loop. If test-expr is of form b relational-op var and relational-op is
3572 // > or >= then incr-expr must cause var to increase on each iteration of
3573 // the loop.
3574 llvm::APSInt Result;
3575 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3576 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3577 bool IsConstNeg =
3578 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003579 bool IsConstPos =
3580 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003581 bool IsConstZero = IsConstant && !Result.getBoolValue();
3582 if (UB && (IsConstZero ||
3583 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003584 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003585 SemaRef.Diag(NewStep->getExprLoc(),
3586 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003587 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003588 SemaRef.Diag(ConditionLoc,
3589 diag::note_omp_loop_cond_requres_compatible_incr)
3590 << TestIsLessOp << ConditionSrcRange;
3591 return true;
3592 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003593 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003594 NewStep =
3595 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3596 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003597 Subtract = !Subtract;
3598 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003599 }
3600
3601 Step = NewStep;
3602 SubtractStep = Subtract;
3603 return false;
3604}
3605
Alexey Bataev9c821032015-04-30 04:23:23 +00003606bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003607 // Check init-expr for canonical loop form and save loop counter
3608 // variable - #Var and its initialization value - #LB.
3609 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3610 // var = lb
3611 // integer-type var = lb
3612 // random-access-iterator-type var = lb
3613 // pointer-type var = lb
3614 //
3615 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003616 if (EmitDiags) {
3617 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3618 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003619 return true;
3620 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003621 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3622 if (!ExprTemp->cleanupsHaveSideEffects())
3623 S = ExprTemp->getSubExpr();
3624
Alexander Musmana5f070a2014-10-01 06:03:56 +00003625 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003626 if (Expr *E = dyn_cast<Expr>(S))
3627 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003628 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003629 if (BO->getOpcode() == BO_Assign) {
3630 auto *LHS = BO->getLHS()->IgnoreParens();
3631 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3632 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3633 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3634 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3635 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3636 }
3637 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3638 if (ME->isArrow() &&
3639 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3640 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3641 }
3642 }
David Majnemer9d168222016-08-05 17:44:54 +00003643 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003644 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003645 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003646 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003647 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003648 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003649 SemaRef.Diag(S->getLocStart(),
3650 diag::ext_omp_loop_not_canonical_init)
3651 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003652 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003653 }
3654 }
3655 }
David Majnemer9d168222016-08-05 17:44:54 +00003656 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003657 if (CE->getOperator() == OO_Equal) {
3658 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003659 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003660 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3661 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3662 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3663 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3664 }
3665 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3666 if (ME->isArrow() &&
3667 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3668 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3669 }
3670 }
3671 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003672
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003673 if (Dependent() || SemaRef.CurContext->isDependentContext())
3674 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003675 if (EmitDiags) {
3676 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3677 << S->getSourceRange();
3678 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003679 return true;
3680}
3681
Alexey Bataev23b69422014-06-18 07:08:49 +00003682/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003683/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003684static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003685 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003686 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003687 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003688 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3689 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003690 if ((Ctor->isCopyOrMoveConstructor() ||
3691 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3692 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003693 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003694 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003695 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003697 }
3698 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3699 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3700 return getCanonicalDecl(ME->getMemberDecl());
3701 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003702}
3703
3704bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3705 // Check test-expr for canonical form, save upper-bound UB, flags for
3706 // less/greater and for strict/non-strict comparison.
3707 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3708 // var relational-op b
3709 // b relational-op var
3710 //
3711 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003712 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003713 return true;
3714 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003715 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003716 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003717 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003718 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003719 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003720 return SetUB(BO->getRHS(),
3721 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3722 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3723 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003724 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003725 return SetUB(BO->getLHS(),
3726 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3727 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3728 BO->getSourceRange(), BO->getOperatorLoc());
3729 }
David Majnemer9d168222016-08-05 17:44:54 +00003730 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003731 if (CE->getNumArgs() == 2) {
3732 auto Op = CE->getOperator();
3733 switch (Op) {
3734 case OO_Greater:
3735 case OO_GreaterEqual:
3736 case OO_Less:
3737 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003738 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003739 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3740 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3741 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003742 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003743 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3744 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3745 CE->getOperatorLoc());
3746 break;
3747 default:
3748 break;
3749 }
3750 }
3751 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003752 if (Dependent() || SemaRef.CurContext->isDependentContext())
3753 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003754 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003755 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003756 return true;
3757}
3758
3759bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3760 // RHS of canonical loop form increment can be:
3761 // var + incr
3762 // incr + var
3763 // var - incr
3764 //
3765 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003766 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003767 if (BO->isAdditiveOp()) {
3768 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003769 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003770 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003771 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003772 return SetStep(BO->getLHS(), false);
3773 }
David Majnemer9d168222016-08-05 17:44:54 +00003774 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003775 bool IsAdd = CE->getOperator() == OO_Plus;
3776 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003777 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003778 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003779 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003780 return SetStep(CE->getArg(0), false);
3781 }
3782 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003783 if (Dependent() || SemaRef.CurContext->isDependentContext())
3784 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003785 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003786 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003787 return true;
3788}
3789
3790bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3791 // Check incr-expr for canonical loop form and return true if it
3792 // does not conform.
3793 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3794 // ++var
3795 // var++
3796 // --var
3797 // var--
3798 // var += incr
3799 // var -= incr
3800 // var = var + incr
3801 // var = incr + var
3802 // var = var - incr
3803 //
3804 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003805 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003806 return true;
3807 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003808 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3809 if (!ExprTemp->cleanupsHaveSideEffects())
3810 S = ExprTemp->getSubExpr();
3811
Alexander Musmana5f070a2014-10-01 06:03:56 +00003812 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003813 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003814 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003815 if (UO->isIncrementDecrementOp() &&
3816 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003817 return SetStep(SemaRef
3818 .ActOnIntegerConstant(UO->getLocStart(),
3819 (UO->isDecrementOp() ? -1 : 1))
3820 .get(),
3821 false);
3822 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003823 switch (BO->getOpcode()) {
3824 case BO_AddAssign:
3825 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003826 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003827 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3828 break;
3829 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003830 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003831 return CheckIncRHS(BO->getRHS());
3832 break;
3833 default:
3834 break;
3835 }
David Majnemer9d168222016-08-05 17:44:54 +00003836 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003837 switch (CE->getOperator()) {
3838 case OO_PlusPlus:
3839 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003840 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003841 return SetStep(SemaRef
3842 .ActOnIntegerConstant(
3843 CE->getLocStart(),
3844 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3845 .get(),
3846 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003847 break;
3848 case OO_PlusEqual:
3849 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003850 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003851 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3852 break;
3853 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003854 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003855 return CheckIncRHS(CE->getArg(1));
3856 break;
3857 default:
3858 break;
3859 }
3860 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003861 if (Dependent() || SemaRef.CurContext->isDependentContext())
3862 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003863 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003864 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003865 return true;
3866}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003867
Alexey Bataev5a3af132016-03-29 08:58:54 +00003868static ExprResult
3869tryBuildCapture(Sema &SemaRef, Expr *Capture,
3870 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003871 if (SemaRef.CurContext->isDependentContext())
3872 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003873 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3874 return SemaRef.PerformImplicitConversion(
3875 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3876 /*AllowExplicit=*/true);
3877 auto I = Captures.find(Capture);
3878 if (I != Captures.end())
3879 return buildCapture(SemaRef, Capture, I->second);
3880 DeclRefExpr *Ref = nullptr;
3881 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3882 Captures[Capture] = Ref;
3883 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003884}
3885
Alexander Musmana5f070a2014-10-01 06:03:56 +00003886/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003887Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3888 Scope *S, const bool LimitedType,
3889 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003890 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003891 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003892 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003893 SemaRef.getLangOpts().CPlusPlus) {
3894 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003895 auto *UBExpr = TestIsLessOp ? UB : LB;
3896 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003897 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3898 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003899 if (!Upper || !Lower)
3900 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003901
3902 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3903
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003904 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003905 // BuildBinOp already emitted error, this one is to point user to upper
3906 // and lower bound, and to tell what is passed to 'operator-'.
3907 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3908 << Upper->getSourceRange() << Lower->getSourceRange();
3909 return nullptr;
3910 }
3911 }
3912
3913 if (!Diff.isUsable())
3914 return nullptr;
3915
3916 // Upper - Lower [- 1]
3917 if (TestIsStrictOp)
3918 Diff = SemaRef.BuildBinOp(
3919 S, DefaultLoc, BO_Sub, Diff.get(),
3920 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3921 if (!Diff.isUsable())
3922 return nullptr;
3923
3924 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003925 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3926 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003927 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003928 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003929 if (!Diff.isUsable())
3930 return nullptr;
3931
3932 // Parentheses (for dumping/debugging purposes only).
3933 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3934 if (!Diff.isUsable())
3935 return nullptr;
3936
3937 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003938 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003939 if (!Diff.isUsable())
3940 return nullptr;
3941
Alexander Musman174b3ca2014-10-06 11:16:29 +00003942 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003943 QualType Type = Diff.get()->getType();
3944 auto &C = SemaRef.Context;
3945 bool UseVarType = VarType->hasIntegerRepresentation() &&
3946 C.getTypeSize(Type) > C.getTypeSize(VarType);
3947 if (!Type->isIntegerType() || UseVarType) {
3948 unsigned NewSize =
3949 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3950 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3951 : Type->hasSignedIntegerRepresentation();
3952 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003953 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3954 Diff = SemaRef.PerformImplicitConversion(
3955 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3956 if (!Diff.isUsable())
3957 return nullptr;
3958 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003959 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003960 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003961 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3962 if (NewSize != C.getTypeSize(Type)) {
3963 if (NewSize < C.getTypeSize(Type)) {
3964 assert(NewSize == 64 && "incorrect loop var size");
3965 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3966 << InitSrcRange << ConditionSrcRange;
3967 }
3968 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003969 NewSize, Type->hasSignedIntegerRepresentation() ||
3970 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003971 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3972 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3973 Sema::AA_Converting, true);
3974 if (!Diff.isUsable())
3975 return nullptr;
3976 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003977 }
3978 }
3979
Alexander Musmana5f070a2014-10-01 06:03:56 +00003980 return Diff.get();
3981}
3982
Alexey Bataev5a3af132016-03-29 08:58:54 +00003983Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3984 Scope *S, Expr *Cond,
3985 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003986 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3987 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3988 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003989
Alexey Bataev5a3af132016-03-29 08:58:54 +00003990 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3991 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3992 if (!NewLB.isUsable() || !NewUB.isUsable())
3993 return nullptr;
3994
Alexey Bataev62dbb972015-04-22 11:59:37 +00003995 auto CondExpr = SemaRef.BuildBinOp(
3996 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3997 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003998 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003999 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004000 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4001 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004002 CondExpr = SemaRef.PerformImplicitConversion(
4003 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4004 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004005 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004006 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4007 // Otherwise use original loop conditon and evaluate it in runtime.
4008 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4009}
4010
Alexander Musmana5f070a2014-10-01 06:03:56 +00004011/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004012DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004013 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004014 auto *VD = dyn_cast<VarDecl>(LCDecl);
4015 if (!VD) {
4016 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4017 auto *Ref = buildDeclRefExpr(
4018 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004019 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4020 // If the loop control decl is explicitly marked as private, do not mark it
4021 // as captured again.
4022 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4023 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004024 return Ref;
4025 }
4026 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004027 DefaultLoc);
4028}
4029
4030Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004031 if (LCDecl && !LCDecl->isInvalidDecl()) {
4032 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004033 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004034 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4035 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004036 if (PrivateVar->isInvalidDecl())
4037 return nullptr;
4038 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4039 }
4040 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004041}
4042
Samuel Antao4c8035b2016-12-12 18:00:20 +00004043/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4045
4046/// \brief Build step of the counter be used for codegen.
4047Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4048
4049/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004050struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004051 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004052 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004053 /// \brief This expression calculates the number of iterations in the loop.
4054 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004055 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004056 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004057 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004058 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004059 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004060 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004061 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004062 /// \brief This is step for the #CounterVar used to generate its update:
4063 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004064 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004065 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004066 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004067 /// \brief Source range of the loop init.
4068 SourceRange InitSrcRange;
4069 /// \brief Source range of the loop condition.
4070 SourceRange CondSrcRange;
4071 /// \brief Source range of the loop increment.
4072 SourceRange IncSrcRange;
4073};
4074
Alexey Bataev23b69422014-06-18 07:08:49 +00004075} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004076
Alexey Bataev9c821032015-04-30 04:23:23 +00004077void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4078 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4079 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004080 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4081 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004082 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4083 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004084 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4085 if (auto *D = ISC.GetLoopDecl()) {
4086 auto *VD = dyn_cast<VarDecl>(D);
4087 if (!VD) {
4088 if (auto *Private = IsOpenMPCapturedDecl(D))
4089 VD = Private;
4090 else {
4091 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4092 /*WithInit=*/false);
4093 VD = cast<VarDecl>(Ref->getDecl());
4094 }
4095 }
4096 DSAStack->addLoopControlVariable(D, VD);
4097 }
4098 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004099 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004100 }
4101}
4102
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004103/// \brief Called on a for stmt to check and extract its iteration space
4104/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004105static bool CheckOpenMPIterationSpace(
4106 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4107 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004108 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004109 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004110 LoopIterationSpace &ResultIterSpace,
4111 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004112 // OpenMP [2.6, Canonical Loop Form]
4113 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004114 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004115 if (!For) {
4116 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004117 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4118 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4119 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4120 if (NestedLoopCount > 1) {
4121 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4122 SemaRef.Diag(DSA.getConstructLoc(),
4123 diag::note_omp_collapse_ordered_expr)
4124 << 2 << CollapseLoopCountExpr->getSourceRange()
4125 << OrderedLoopCountExpr->getSourceRange();
4126 else if (CollapseLoopCountExpr)
4127 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4128 diag::note_omp_collapse_ordered_expr)
4129 << 0 << CollapseLoopCountExpr->getSourceRange();
4130 else
4131 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4132 diag::note_omp_collapse_ordered_expr)
4133 << 1 << OrderedLoopCountExpr->getSourceRange();
4134 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004135 return true;
4136 }
4137 assert(For->getBody());
4138
4139 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4140
4141 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004142 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004143 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004144 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004145
4146 bool HasErrors = false;
4147
4148 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004149 if (auto *LCDecl = ISC.GetLoopDecl()) {
4150 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004151
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004152 // OpenMP [2.6, Canonical Loop Form]
4153 // Var is one of the following:
4154 // A variable of signed or unsigned integer type.
4155 // For C++, a variable of a random access iterator type.
4156 // For C, a variable of a pointer type.
4157 auto VarType = LCDecl->getType().getNonReferenceType();
4158 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4159 !VarType->isPointerType() &&
4160 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4161 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4162 << SemaRef.getLangOpts().CPlusPlus;
4163 HasErrors = true;
4164 }
4165
4166 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4167 // a Construct
4168 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4169 // parallel for construct is (are) private.
4170 // The loop iteration variable in the associated for-loop of a simd
4171 // construct with just one associated for-loop is linear with a
4172 // constant-linear-step that is the increment of the associated for-loop.
4173 // Exclude loop var from the list of variables with implicitly defined data
4174 // sharing attributes.
4175 VarsWithImplicitDSA.erase(LCDecl);
4176
4177 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4178 // in a Construct, C/C++].
4179 // The loop iteration variable in the associated for-loop of a simd
4180 // construct with just one associated for-loop may be listed in a linear
4181 // clause with a constant-linear-step that is the increment of the
4182 // associated for-loop.
4183 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4184 // parallel for construct may be listed in a private or lastprivate clause.
4185 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4186 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4187 // declared in the loop and it is predetermined as a private.
4188 auto PredeterminedCKind =
4189 isOpenMPSimdDirective(DKind)
4190 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4191 : OMPC_private;
4192 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4193 DVar.CKind != PredeterminedCKind) ||
4194 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4195 isOpenMPDistributeDirective(DKind)) &&
4196 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4197 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4198 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4199 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4200 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4201 << getOpenMPClauseName(PredeterminedCKind);
4202 if (DVar.RefExpr == nullptr)
4203 DVar.CKind = PredeterminedCKind;
4204 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4205 HasErrors = true;
4206 } else if (LoopDeclRefExpr != nullptr) {
4207 // Make the loop iteration variable private (for worksharing constructs),
4208 // linear (for simd directives with the only one associated loop) or
4209 // lastprivate (for simd directives with several collapsed or ordered
4210 // loops).
4211 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004212 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4213 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004214 /*FromParent=*/false);
4215 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4216 }
4217
4218 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4219
4220 // Check test-expr.
4221 HasErrors |= ISC.CheckCond(For->getCond());
4222
4223 // Check incr-expr.
4224 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004225 }
4226
Alexander Musmana5f070a2014-10-01 06:03:56 +00004227 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004228 return HasErrors;
4229
Alexander Musmana5f070a2014-10-01 06:03:56 +00004230 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004231 ResultIterSpace.PreCond =
4232 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004233 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004234 DSA.getCurScope(),
4235 (isOpenMPWorksharingDirective(DKind) ||
4236 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4237 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004238 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004239 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004240 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4241 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4242 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4243 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4244 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4245 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4246
Alexey Bataev62dbb972015-04-22 11:59:37 +00004247 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4248 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004249 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004250 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004251 ResultIterSpace.CounterInit == nullptr ||
4252 ResultIterSpace.CounterStep == nullptr);
4253
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004254 return HasErrors;
4255}
4256
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004257/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004258static ExprResult
4259BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4260 ExprResult Start,
4261 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004262 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004263 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4264 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004265 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004266 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004267 VarRef.get()->getType())) {
4268 NewStart = SemaRef.PerformImplicitConversion(
4269 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4270 /*AllowExplicit=*/true);
4271 if (!NewStart.isUsable())
4272 return ExprError();
4273 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004274
4275 auto Init =
4276 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4277 return Init;
4278}
4279
Alexander Musmana5f070a2014-10-01 06:03:56 +00004280/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004281static ExprResult
4282BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4283 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4284 ExprResult Step, bool Subtract,
4285 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004286 // Add parentheses (for debugging purposes only).
4287 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4288 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4289 !Step.isUsable())
4290 return ExprError();
4291
Alexey Bataev5a3af132016-03-29 08:58:54 +00004292 ExprResult NewStep = Step;
4293 if (Captures)
4294 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004295 if (NewStep.isInvalid())
4296 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004297 ExprResult Update =
4298 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004299 if (!Update.isUsable())
4300 return ExprError();
4301
Alexey Bataevc0214e02016-02-16 12:13:49 +00004302 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4303 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004304 ExprResult NewStart = Start;
4305 if (Captures)
4306 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004307 if (NewStart.isInvalid())
4308 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004309
Alexey Bataevc0214e02016-02-16 12:13:49 +00004310 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4311 ExprResult SavedUpdate = Update;
4312 ExprResult UpdateVal;
4313 if (VarRef.get()->getType()->isOverloadableType() ||
4314 NewStart.get()->getType()->isOverloadableType() ||
4315 Update.get()->getType()->isOverloadableType()) {
4316 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4317 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4318 Update =
4319 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4320 if (Update.isUsable()) {
4321 UpdateVal =
4322 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4323 VarRef.get(), SavedUpdate.get());
4324 if (UpdateVal.isUsable()) {
4325 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4326 UpdateVal.get());
4327 }
4328 }
4329 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4330 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004331
Alexey Bataevc0214e02016-02-16 12:13:49 +00004332 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4333 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4334 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4335 NewStart.get(), SavedUpdate.get());
4336 if (!Update.isUsable())
4337 return ExprError();
4338
Alexey Bataev11481f52016-02-17 10:29:05 +00004339 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4340 VarRef.get()->getType())) {
4341 Update = SemaRef.PerformImplicitConversion(
4342 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4343 if (!Update.isUsable())
4344 return ExprError();
4345 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004346
4347 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4348 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004349 return Update;
4350}
4351
4352/// \brief Convert integer expression \a E to make it have at least \a Bits
4353/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004354static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004355 if (E == nullptr)
4356 return ExprError();
4357 auto &C = SemaRef.Context;
4358 QualType OldType = E->getType();
4359 unsigned HasBits = C.getTypeSize(OldType);
4360 if (HasBits >= Bits)
4361 return ExprResult(E);
4362 // OK to convert to signed, because new type has more bits than old.
4363 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4364 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4365 true);
4366}
4367
4368/// \brief Check if the given expression \a E is a constant integer that fits
4369/// into \a Bits bits.
4370static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4371 if (E == nullptr)
4372 return false;
4373 llvm::APSInt Result;
4374 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4375 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4376 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004377}
4378
Alexey Bataev5a3af132016-03-29 08:58:54 +00004379/// Build preinits statement for the given declarations.
4380static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004381 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004382 if (!PreInits.empty()) {
4383 return new (Context) DeclStmt(
4384 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4385 SourceLocation(), SourceLocation());
4386 }
4387 return nullptr;
4388}
4389
4390/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004391static Stmt *
4392buildPreInits(ASTContext &Context,
4393 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004394 if (!Captures.empty()) {
4395 SmallVector<Decl *, 16> PreInits;
4396 for (auto &Pair : Captures)
4397 PreInits.push_back(Pair.second->getDecl());
4398 return buildPreInits(Context, PreInits);
4399 }
4400 return nullptr;
4401}
4402
4403/// Build postupdate expression for the given list of postupdates expressions.
4404static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4405 Expr *PostUpdate = nullptr;
4406 if (!PostUpdates.empty()) {
4407 for (auto *E : PostUpdates) {
4408 Expr *ConvE = S.BuildCStyleCastExpr(
4409 E->getExprLoc(),
4410 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4411 E->getExprLoc(), E)
4412 .get();
4413 PostUpdate = PostUpdate
4414 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4415 PostUpdate, ConvE)
4416 .get()
4417 : ConvE;
4418 }
4419 }
4420 return PostUpdate;
4421}
4422
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004423/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004424/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4425/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004426static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004427CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4428 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4429 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004430 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004431 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004432 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004433 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004434 // Found 'collapse' clause - calculate collapse number.
4435 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004436 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004437 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004438 }
4439 if (OrderedLoopCountExpr) {
4440 // Found 'ordered' clause - calculate collapse number.
4441 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004442 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4443 if (Result.getLimitedValue() < NestedLoopCount) {
4444 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4445 diag::err_omp_wrong_ordered_loop_count)
4446 << OrderedLoopCountExpr->getSourceRange();
4447 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4448 diag::note_collapse_loop_count)
4449 << CollapseLoopCountExpr->getSourceRange();
4450 }
4451 NestedLoopCount = Result.getLimitedValue();
4452 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004453 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004454 // This is helper routine for loop directives (e.g., 'for', 'simd',
4455 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004456 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004457 SmallVector<LoopIterationSpace, 4> IterSpaces;
4458 IterSpaces.resize(NestedLoopCount);
4459 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004460 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004461 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004462 NestedLoopCount, CollapseLoopCountExpr,
4463 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004464 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004465 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004466 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004467 // OpenMP [2.8.1, simd construct, Restrictions]
4468 // All loops associated with the construct must be perfectly nested; that
4469 // is, there must be no intervening code nor any OpenMP directive between
4470 // any two loops.
4471 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004472 }
4473
Alexander Musmana5f070a2014-10-01 06:03:56 +00004474 Built.clear(/* size */ NestedLoopCount);
4475
4476 if (SemaRef.CurContext->isDependentContext())
4477 return NestedLoopCount;
4478
4479 // An example of what is generated for the following code:
4480 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004481 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004482 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004483 // for (k = 0; k < NK; ++k)
4484 // for (j = J0; j < NJ; j+=2) {
4485 // <loop body>
4486 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004487 //
4488 // We generate the code below.
4489 // Note: the loop body may be outlined in CodeGen.
4490 // Note: some counters may be C++ classes, operator- is used to find number of
4491 // iterations and operator+= to calculate counter value.
4492 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4493 // or i64 is currently supported).
4494 //
4495 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4496 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4497 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4498 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4499 // // similar updates for vars in clauses (e.g. 'linear')
4500 // <loop body (using local i and j)>
4501 // }
4502 // i = NI; // assign final values of counters
4503 // j = NJ;
4504 //
4505
4506 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4507 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004508 // Precondition tests if there is at least one iteration (all conditions are
4509 // true).
4510 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004511 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004512 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004513 32 /* Bits */, SemaRef
4514 .PerformImplicitConversion(
4515 N0->IgnoreImpCasts(), N0->getType(),
4516 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004517 .get(),
4518 SemaRef);
4519 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004520 64 /* Bits */, SemaRef
4521 .PerformImplicitConversion(
4522 N0->IgnoreImpCasts(), N0->getType(),
4523 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004524 .get(),
4525 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004526
4527 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4528 return NestedLoopCount;
4529
4530 auto &C = SemaRef.Context;
4531 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4532
4533 Scope *CurScope = DSA.getCurScope();
4534 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004535 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004536 PreCond =
4537 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4538 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004539 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004540 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004541 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004542 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4543 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004544 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004545 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004546 SemaRef
4547 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4548 Sema::AA_Converting,
4549 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004550 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004551 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004552 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004553 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004554 SemaRef
4555 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4556 Sema::AA_Converting,
4557 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004558 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004559 }
4560
4561 // Choose either the 32-bit or 64-bit version.
4562 ExprResult LastIteration = LastIteration64;
4563 if (LastIteration32.isUsable() &&
4564 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4565 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4566 FitsInto(
4567 32 /* Bits */,
4568 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4569 LastIteration64.get(), SemaRef)))
4570 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004571 QualType VType = LastIteration.get()->getType();
4572 QualType RealVType = VType;
4573 QualType StrideVType = VType;
4574 if (isOpenMPTaskLoopDirective(DKind)) {
4575 VType =
4576 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4577 StrideVType =
4578 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4579 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004580
4581 if (!LastIteration.isUsable())
4582 return 0;
4583
4584 // Save the number of iterations.
4585 ExprResult NumIterations = LastIteration;
4586 {
4587 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004588 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4589 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004590 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4591 if (!LastIteration.isUsable())
4592 return 0;
4593 }
4594
4595 // Calculate the last iteration number beforehand instead of doing this on
4596 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4597 llvm::APSInt Result;
4598 bool IsConstant =
4599 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4600 ExprResult CalcLastIteration;
4601 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004602 ExprResult SaveRef =
4603 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004604 LastIteration = SaveRef;
4605
4606 // Prepare SaveRef + 1.
4607 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004608 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004609 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4610 if (!NumIterations.isUsable())
4611 return 0;
4612 }
4613
4614 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4615
David Majnemer9d168222016-08-05 17:44:54 +00004616 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004617 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004618 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4619 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004620 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004621 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4622 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004623 SemaRef.AddInitializerToDecl(LBDecl,
4624 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4625 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004626
4627 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004628 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4629 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004630 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004631 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004632
4633 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4634 // This will be used to implement clause 'lastprivate'.
4635 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004636 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4637 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004638 SemaRef.AddInitializerToDecl(ILDecl,
4639 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4640 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004641
4642 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004643 VarDecl *STDecl =
4644 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4645 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004646 SemaRef.AddInitializerToDecl(STDecl,
4647 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4648 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004649
4650 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004651 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004652 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4653 UB.get(), LastIteration.get());
4654 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4655 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4656 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4657 CondOp.get());
4658 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004659
4660 // If we have a combined directive that combines 'distribute', 'for' or
4661 // 'simd' we need to be able to access the bounds of the schedule of the
4662 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4663 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4664 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004665
Carlo Bertolliffafe102017-04-20 00:39:39 +00004666 // Lower bound variable, initialized with zero.
4667 VarDecl *CombLBDecl =
4668 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4669 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4670 SemaRef.AddInitializerToDecl(
4671 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4672 /*DirectInit*/ false);
4673
4674 // Upper bound variable, initialized with last iteration number.
4675 VarDecl *CombUBDecl =
4676 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4677 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4678 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4679 /*DirectInit*/ false);
4680
4681 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4682 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4683 ExprResult CombCondOp =
4684 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4685 LastIteration.get(), CombUB.get());
4686 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4687 CombCondOp.get());
4688 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4689
4690 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004691 // We expect to have at least 2 more parameters than the 'parallel'
4692 // directive does - the lower and upper bounds of the previous schedule.
4693 assert(CD->getNumParams() >= 4 &&
4694 "Unexpected number of parameters in loop combined directive");
4695
4696 // Set the proper type for the bounds given what we learned from the
4697 // enclosed loops.
4698 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4699 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4700
4701 // Previous lower and upper bounds are obtained from the region
4702 // parameters.
4703 PrevLB =
4704 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4705 PrevUB =
4706 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4707 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004708 }
4709
4710 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004711 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004712 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004713 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004714 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4715 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004716 Expr *RHS =
4717 (isOpenMPWorksharingDirective(DKind) ||
4718 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4719 ? LB.get()
4720 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004721 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4722 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004723
4724 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4725 Expr *CombRHS =
4726 (isOpenMPWorksharingDirective(DKind) ||
4727 isOpenMPTaskLoopDirective(DKind) ||
4728 isOpenMPDistributeDirective(DKind))
4729 ? CombLB.get()
4730 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4731 CombInit =
4732 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4733 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4734 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004735 }
4736
Alexander Musmanc6388682014-12-15 07:07:06 +00004737 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004738 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004739 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004740 (isOpenMPWorksharingDirective(DKind) ||
4741 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004742 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4743 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4744 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004745 ExprResult CombCond;
4746 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4747 CombCond =
4748 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4749 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004750 // Loop increment (IV = IV + 1)
4751 SourceLocation IncLoc;
4752 ExprResult Inc =
4753 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4754 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4755 if (!Inc.isUsable())
4756 return 0;
4757 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004758 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4759 if (!Inc.isUsable())
4760 return 0;
4761
4762 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4763 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004764 // In combined construct, add combined version that use CombLB and CombUB
4765 // base variables for the update
4766 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004767 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4768 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004769 // LB + ST
4770 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4771 if (!NextLB.isUsable())
4772 return 0;
4773 // LB = LB + ST
4774 NextLB =
4775 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4776 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4777 if (!NextLB.isUsable())
4778 return 0;
4779 // UB + ST
4780 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4781 if (!NextUB.isUsable())
4782 return 0;
4783 // UB = UB + ST
4784 NextUB =
4785 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4786 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4787 if (!NextUB.isUsable())
4788 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004789 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4790 CombNextLB =
4791 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4792 if (!NextLB.isUsable())
4793 return 0;
4794 // LB = LB + ST
4795 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4796 CombNextLB.get());
4797 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4798 if (!CombNextLB.isUsable())
4799 return 0;
4800 // UB + ST
4801 CombNextUB =
4802 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4803 if (!CombNextUB.isUsable())
4804 return 0;
4805 // UB = UB + ST
4806 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4807 CombNextUB.get());
4808 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4809 if (!CombNextUB.isUsable())
4810 return 0;
4811 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004812 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004813
Carlo Bertolliffafe102017-04-20 00:39:39 +00004814 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004815 // directive with for as IV = IV + ST; ensure upper bound expression based
4816 // on PrevUB instead of NumIterations - used to implement 'for' when found
4817 // in combination with 'distribute', like in 'distribute parallel for'
4818 SourceLocation DistIncLoc;
4819 ExprResult DistCond, DistInc, PrevEUB;
4820 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4821 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4822 assert(DistCond.isUsable() && "distribute cond expr was not built");
4823
4824 DistInc =
4825 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4826 assert(DistInc.isUsable() && "distribute inc expr was not built");
4827 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4828 DistInc.get());
4829 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4830 assert(DistInc.isUsable() && "distribute inc expr was not built");
4831
4832 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4833 // construct
4834 SourceLocation DistEUBLoc;
4835 ExprResult IsUBGreater =
4836 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4837 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4838 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4839 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4840 CondOp.get());
4841 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4842 }
4843
Alexander Musmana5f070a2014-10-01 06:03:56 +00004844 // Build updates and final values of the loop counters.
4845 bool HasErrors = false;
4846 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004847 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004848 Built.Updates.resize(NestedLoopCount);
4849 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004850 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004851 {
4852 ExprResult Div;
4853 // Go from inner nested loop to outer.
4854 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4855 LoopIterationSpace &IS = IterSpaces[Cnt];
4856 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4857 // Build: Iter = (IV / Div) % IS.NumIters
4858 // where Div is product of previous iterations' IS.NumIters.
4859 ExprResult Iter;
4860 if (Div.isUsable()) {
4861 Iter =
4862 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4863 } else {
4864 Iter = IV;
4865 assert((Cnt == (int)NestedLoopCount - 1) &&
4866 "unusable div expected on first iteration only");
4867 }
4868
4869 if (Cnt != 0 && Iter.isUsable())
4870 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4871 IS.NumIterations);
4872 if (!Iter.isUsable()) {
4873 HasErrors = true;
4874 break;
4875 }
4876
Alexey Bataev39f915b82015-05-08 10:41:21 +00004877 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004878 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4879 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4880 IS.CounterVar->getExprLoc(),
4881 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004882 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004883 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004884 if (!Init.isUsable()) {
4885 HasErrors = true;
4886 break;
4887 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004888 ExprResult Update = BuildCounterUpdate(
4889 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4890 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004891 if (!Update.isUsable()) {
4892 HasErrors = true;
4893 break;
4894 }
4895
4896 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4897 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004898 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004899 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004900 if (!Final.isUsable()) {
4901 HasErrors = true;
4902 break;
4903 }
4904
4905 // Build Div for the next iteration: Div <- Div * IS.NumIters
4906 if (Cnt != 0) {
4907 if (Div.isUnset())
4908 Div = IS.NumIterations;
4909 else
4910 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4911 IS.NumIterations);
4912
4913 // Add parentheses (for debugging purposes only).
4914 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004915 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004916 if (!Div.isUsable()) {
4917 HasErrors = true;
4918 break;
4919 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004920 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004921 }
4922 if (!Update.isUsable() || !Final.isUsable()) {
4923 HasErrors = true;
4924 break;
4925 }
4926 // Save results
4927 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004928 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004929 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004930 Built.Updates[Cnt] = Update.get();
4931 Built.Finals[Cnt] = Final.get();
4932 }
4933 }
4934
4935 if (HasErrors)
4936 return 0;
4937
4938 // Save results
4939 Built.IterationVarRef = IV.get();
4940 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004941 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004942 Built.CalcLastIteration =
4943 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004944 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004945 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004946 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004947 Built.Init = Init.get();
4948 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004949 Built.LB = LB.get();
4950 Built.UB = UB.get();
4951 Built.IL = IL.get();
4952 Built.ST = ST.get();
4953 Built.EUB = EUB.get();
4954 Built.NLB = NextLB.get();
4955 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004956 Built.PrevLB = PrevLB.get();
4957 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004958 Built.DistInc = DistInc.get();
4959 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004960 Built.DistCombinedFields.LB = CombLB.get();
4961 Built.DistCombinedFields.UB = CombUB.get();
4962 Built.DistCombinedFields.EUB = CombEUB.get();
4963 Built.DistCombinedFields.Init = CombInit.get();
4964 Built.DistCombinedFields.Cond = CombCond.get();
4965 Built.DistCombinedFields.NLB = CombNextLB.get();
4966 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004967
Alexey Bataev8b427062016-05-25 12:36:08 +00004968 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4969 // Fill data for doacross depend clauses.
4970 for (auto Pair : DSA.getDoacrossDependClauses()) {
4971 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4972 Pair.first->setCounterValue(CounterVal);
4973 else {
4974 if (NestedLoopCount != Pair.second.size() ||
4975 NestedLoopCount != LoopMultipliers.size() + 1) {
4976 // Erroneous case - clause has some problems.
4977 Pair.first->setCounterValue(CounterVal);
4978 continue;
4979 }
4980 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4981 auto I = Pair.second.rbegin();
4982 auto IS = IterSpaces.rbegin();
4983 auto ILM = LoopMultipliers.rbegin();
4984 Expr *UpCounterVal = CounterVal;
4985 Expr *Multiplier = nullptr;
4986 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4987 if (I->first) {
4988 assert(IS->CounterStep);
4989 Expr *NormalizedOffset =
4990 SemaRef
4991 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4992 I->first, IS->CounterStep)
4993 .get();
4994 if (Multiplier) {
4995 NormalizedOffset =
4996 SemaRef
4997 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4998 NormalizedOffset, Multiplier)
4999 .get();
5000 }
5001 assert(I->second == OO_Plus || I->second == OO_Minus);
5002 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005003 UpCounterVal = SemaRef
5004 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5005 UpCounterVal, NormalizedOffset)
5006 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005007 }
5008 Multiplier = *ILM;
5009 ++I;
5010 ++IS;
5011 ++ILM;
5012 }
5013 Pair.first->setCounterValue(UpCounterVal);
5014 }
5015 }
5016
Alexey Bataevabfc0692014-06-25 06:52:00 +00005017 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005018}
5019
Alexey Bataev10e775f2015-07-30 11:36:16 +00005020static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005021 auto CollapseClauses =
5022 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5023 if (CollapseClauses.begin() != CollapseClauses.end())
5024 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005025 return nullptr;
5026}
5027
Alexey Bataev10e775f2015-07-30 11:36:16 +00005028static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005029 auto OrderedClauses =
5030 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5031 if (OrderedClauses.begin() != OrderedClauses.end())
5032 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005033 return nullptr;
5034}
5035
Kelvin Lic5609492016-07-15 04:39:07 +00005036static bool checkSimdlenSafelenSpecified(Sema &S,
5037 const ArrayRef<OMPClause *> Clauses) {
5038 OMPSafelenClause *Safelen = nullptr;
5039 OMPSimdlenClause *Simdlen = nullptr;
5040
5041 for (auto *Clause : Clauses) {
5042 if (Clause->getClauseKind() == OMPC_safelen)
5043 Safelen = cast<OMPSafelenClause>(Clause);
5044 else if (Clause->getClauseKind() == OMPC_simdlen)
5045 Simdlen = cast<OMPSimdlenClause>(Clause);
5046 if (Safelen && Simdlen)
5047 break;
5048 }
5049
5050 if (Simdlen && Safelen) {
5051 llvm::APSInt SimdlenRes, SafelenRes;
5052 auto SimdlenLength = Simdlen->getSimdlen();
5053 auto SafelenLength = Safelen->getSafelen();
5054 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5055 SimdlenLength->isInstantiationDependent() ||
5056 SimdlenLength->containsUnexpandedParameterPack())
5057 return false;
5058 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5059 SafelenLength->isInstantiationDependent() ||
5060 SafelenLength->containsUnexpandedParameterPack())
5061 return false;
5062 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5063 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5064 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5065 // If both simdlen and safelen clauses are specified, the value of the
5066 // simdlen parameter must be less than or equal to the value of the safelen
5067 // parameter.
5068 if (SimdlenRes > SafelenRes) {
5069 S.Diag(SimdlenLength->getExprLoc(),
5070 diag::err_omp_wrong_simdlen_safelen_values)
5071 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5072 return true;
5073 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005074 }
5075 return false;
5076}
5077
Alexey Bataev4acb8592014-07-07 13:01:15 +00005078StmtResult Sema::ActOnOpenMPSimdDirective(
5079 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5080 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005081 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005082 if (!AStmt)
5083 return StmtError();
5084
5085 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005086 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005087 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5088 // define the nested loops number.
5089 unsigned NestedLoopCount = CheckOpenMPLoop(
5090 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5091 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005092 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005093 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005094
Alexander Musmana5f070a2014-10-01 06:03:56 +00005095 assert((CurContext->isDependentContext() || B.builtAll()) &&
5096 "omp simd loop exprs were not built");
5097
Alexander Musman3276a272015-03-21 10:12:56 +00005098 if (!CurContext->isDependentContext()) {
5099 // Finalize the clauses that need pre-built expressions for CodeGen.
5100 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005101 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005102 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005103 B.NumIterations, *this, CurScope,
5104 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005105 return StmtError();
5106 }
5107 }
5108
Kelvin Lic5609492016-07-15 04:39:07 +00005109 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005110 return StmtError();
5111
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005112 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005113 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5114 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005115}
5116
Alexey Bataev4acb8592014-07-07 13:01:15 +00005117StmtResult Sema::ActOnOpenMPForDirective(
5118 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5119 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005120 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005121 if (!AStmt)
5122 return StmtError();
5123
5124 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005125 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005126 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5127 // define the nested loops number.
5128 unsigned NestedLoopCount = CheckOpenMPLoop(
5129 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5130 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005131 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005132 return StmtError();
5133
Alexander Musmana5f070a2014-10-01 06:03:56 +00005134 assert((CurContext->isDependentContext() || B.builtAll()) &&
5135 "omp for loop exprs were not built");
5136
Alexey Bataev54acd402015-08-04 11:18:19 +00005137 if (!CurContext->isDependentContext()) {
5138 // Finalize the clauses that need pre-built expressions for CodeGen.
5139 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005140 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005141 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005142 B.NumIterations, *this, CurScope,
5143 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005144 return StmtError();
5145 }
5146 }
5147
Alexey Bataevf29276e2014-06-18 04:14:57 +00005148 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005149 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005150 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005151}
5152
Alexander Musmanf82886e2014-09-18 05:12:34 +00005153StmtResult Sema::ActOnOpenMPForSimdDirective(
5154 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5155 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005156 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005157 if (!AStmt)
5158 return StmtError();
5159
5160 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005161 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005162 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5163 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005164 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005165 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5166 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5167 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005168 if (NestedLoopCount == 0)
5169 return StmtError();
5170
Alexander Musmanc6388682014-12-15 07:07:06 +00005171 assert((CurContext->isDependentContext() || B.builtAll()) &&
5172 "omp for simd loop exprs were not built");
5173
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005174 if (!CurContext->isDependentContext()) {
5175 // Finalize the clauses that need pre-built expressions for CodeGen.
5176 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005177 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005178 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005179 B.NumIterations, *this, CurScope,
5180 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005181 return StmtError();
5182 }
5183 }
5184
Kelvin Lic5609492016-07-15 04:39:07 +00005185 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005186 return StmtError();
5187
Alexander Musmanf82886e2014-09-18 05:12:34 +00005188 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005189 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5190 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005191}
5192
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005193StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5194 Stmt *AStmt,
5195 SourceLocation StartLoc,
5196 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005197 if (!AStmt)
5198 return StmtError();
5199
5200 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005201 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005202 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005203 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005204 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005205 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005206 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005207 return StmtError();
5208 // All associated statements must be '#pragma omp section' except for
5209 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005210 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005211 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5212 if (SectionStmt)
5213 Diag(SectionStmt->getLocStart(),
5214 diag::err_omp_sections_substmt_not_section);
5215 return StmtError();
5216 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005217 cast<OMPSectionDirective>(SectionStmt)
5218 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005219 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005220 } else {
5221 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5222 return StmtError();
5223 }
5224
5225 getCurFunction()->setHasBranchProtectedScope();
5226
Alexey Bataev25e5b442015-09-15 12:52:43 +00005227 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5228 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005229}
5230
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005231StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5232 SourceLocation StartLoc,
5233 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005234 if (!AStmt)
5235 return StmtError();
5236
5237 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005238
5239 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005240 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005241
Alexey Bataev25e5b442015-09-15 12:52:43 +00005242 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5243 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005244}
5245
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005246StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5247 Stmt *AStmt,
5248 SourceLocation StartLoc,
5249 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005250 if (!AStmt)
5251 return StmtError();
5252
5253 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005254
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005255 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005256
Alexey Bataev3255bf32015-01-19 05:20:46 +00005257 // OpenMP [2.7.3, single Construct, Restrictions]
5258 // The copyprivate clause must not be used with the nowait clause.
5259 OMPClause *Nowait = nullptr;
5260 OMPClause *Copyprivate = nullptr;
5261 for (auto *Clause : Clauses) {
5262 if (Clause->getClauseKind() == OMPC_nowait)
5263 Nowait = Clause;
5264 else if (Clause->getClauseKind() == OMPC_copyprivate)
5265 Copyprivate = Clause;
5266 if (Copyprivate && Nowait) {
5267 Diag(Copyprivate->getLocStart(),
5268 diag::err_omp_single_copyprivate_with_nowait);
5269 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5270 return StmtError();
5271 }
5272 }
5273
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005274 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5275}
5276
Alexander Musman80c22892014-07-17 08:54:58 +00005277StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5278 SourceLocation StartLoc,
5279 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005280 if (!AStmt)
5281 return StmtError();
5282
5283 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005284
5285 getCurFunction()->setHasBranchProtectedScope();
5286
5287 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5288}
5289
Alexey Bataev28c75412015-12-15 08:19:24 +00005290StmtResult Sema::ActOnOpenMPCriticalDirective(
5291 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5292 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005293 if (!AStmt)
5294 return StmtError();
5295
5296 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005297
Alexey Bataev28c75412015-12-15 08:19:24 +00005298 bool ErrorFound = false;
5299 llvm::APSInt Hint;
5300 SourceLocation HintLoc;
5301 bool DependentHint = false;
5302 for (auto *C : Clauses) {
5303 if (C->getClauseKind() == OMPC_hint) {
5304 if (!DirName.getName()) {
5305 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5306 ErrorFound = true;
5307 }
5308 Expr *E = cast<OMPHintClause>(C)->getHint();
5309 if (E->isTypeDependent() || E->isValueDependent() ||
5310 E->isInstantiationDependent())
5311 DependentHint = true;
5312 else {
5313 Hint = E->EvaluateKnownConstInt(Context);
5314 HintLoc = C->getLocStart();
5315 }
5316 }
5317 }
5318 if (ErrorFound)
5319 return StmtError();
5320 auto Pair = DSAStack->getCriticalWithHint(DirName);
5321 if (Pair.first && DirName.getName() && !DependentHint) {
5322 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5323 Diag(StartLoc, diag::err_omp_critical_with_hint);
5324 if (HintLoc.isValid()) {
5325 Diag(HintLoc, diag::note_omp_critical_hint_here)
5326 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5327 } else
5328 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5329 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5330 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5331 << 1
5332 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5333 /*Radix=*/10, /*Signed=*/false);
5334 } else
5335 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5336 }
5337 }
5338
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005339 getCurFunction()->setHasBranchProtectedScope();
5340
Alexey Bataev28c75412015-12-15 08:19:24 +00005341 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5342 Clauses, AStmt);
5343 if (!Pair.first && DirName.getName() && !DependentHint)
5344 DSAStack->addCriticalWithHint(Dir, Hint);
5345 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005346}
5347
Alexey Bataev4acb8592014-07-07 13:01:15 +00005348StmtResult Sema::ActOnOpenMPParallelForDirective(
5349 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5350 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005351 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005352 if (!AStmt)
5353 return StmtError();
5354
Alexey Bataev4acb8592014-07-07 13:01:15 +00005355 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5356 // 1.2.2 OpenMP Language Terminology
5357 // Structured block - An executable statement with a single entry at the
5358 // top and a single exit at the bottom.
5359 // The point of exit cannot be a branch out of the structured block.
5360 // longjmp() and throw() must not violate the entry/exit criteria.
5361 CS->getCapturedDecl()->setNothrow();
5362
Alexander Musmanc6388682014-12-15 07:07:06 +00005363 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005364 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5365 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005366 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005367 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5368 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5369 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005370 if (NestedLoopCount == 0)
5371 return StmtError();
5372
Alexander Musmana5f070a2014-10-01 06:03:56 +00005373 assert((CurContext->isDependentContext() || B.builtAll()) &&
5374 "omp parallel for loop exprs were not built");
5375
Alexey Bataev54acd402015-08-04 11:18:19 +00005376 if (!CurContext->isDependentContext()) {
5377 // Finalize the clauses that need pre-built expressions for CodeGen.
5378 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005379 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005380 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005381 B.NumIterations, *this, CurScope,
5382 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005383 return StmtError();
5384 }
5385 }
5386
Alexey Bataev4acb8592014-07-07 13:01:15 +00005387 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005388 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005389 NestedLoopCount, Clauses, AStmt, B,
5390 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005391}
5392
Alexander Musmane4e893b2014-09-23 09:33:00 +00005393StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5395 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005396 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005397 if (!AStmt)
5398 return StmtError();
5399
Alexander Musmane4e893b2014-09-23 09:33:00 +00005400 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5401 // 1.2.2 OpenMP Language Terminology
5402 // Structured block - An executable statement with a single entry at the
5403 // top and a single exit at the bottom.
5404 // The point of exit cannot be a branch out of the structured block.
5405 // longjmp() and throw() must not violate the entry/exit criteria.
5406 CS->getCapturedDecl()->setNothrow();
5407
Alexander Musmanc6388682014-12-15 07:07:06 +00005408 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005409 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5410 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005411 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005412 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5413 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5414 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005415 if (NestedLoopCount == 0)
5416 return StmtError();
5417
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005418 if (!CurContext->isDependentContext()) {
5419 // Finalize the clauses that need pre-built expressions for CodeGen.
5420 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005421 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005422 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005423 B.NumIterations, *this, CurScope,
5424 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005425 return StmtError();
5426 }
5427 }
5428
Kelvin Lic5609492016-07-15 04:39:07 +00005429 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005430 return StmtError();
5431
Alexander Musmane4e893b2014-09-23 09:33:00 +00005432 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005433 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005434 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005435}
5436
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005437StmtResult
5438Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5439 Stmt *AStmt, SourceLocation StartLoc,
5440 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005441 if (!AStmt)
5442 return StmtError();
5443
5444 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005445 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005446 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005447 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005448 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005449 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005450 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005451 return StmtError();
5452 // All associated statements must be '#pragma omp section' except for
5453 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005454 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005455 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5456 if (SectionStmt)
5457 Diag(SectionStmt->getLocStart(),
5458 diag::err_omp_parallel_sections_substmt_not_section);
5459 return StmtError();
5460 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005461 cast<OMPSectionDirective>(SectionStmt)
5462 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005463 }
5464 } else {
5465 Diag(AStmt->getLocStart(),
5466 diag::err_omp_parallel_sections_not_compound_stmt);
5467 return StmtError();
5468 }
5469
5470 getCurFunction()->setHasBranchProtectedScope();
5471
Alexey Bataev25e5b442015-09-15 12:52:43 +00005472 return OMPParallelSectionsDirective::Create(
5473 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005474}
5475
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005476StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5477 Stmt *AStmt, SourceLocation StartLoc,
5478 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005479 if (!AStmt)
5480 return StmtError();
5481
David Majnemer9d168222016-08-05 17:44:54 +00005482 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005483 // 1.2.2 OpenMP Language Terminology
5484 // Structured block - An executable statement with a single entry at the
5485 // top and a single exit at the bottom.
5486 // The point of exit cannot be a branch out of the structured block.
5487 // longjmp() and throw() must not violate the entry/exit criteria.
5488 CS->getCapturedDecl()->setNothrow();
5489
5490 getCurFunction()->setHasBranchProtectedScope();
5491
Alexey Bataev25e5b442015-09-15 12:52:43 +00005492 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5493 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005494}
5495
Alexey Bataev68446b72014-07-18 07:47:19 +00005496StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5497 SourceLocation EndLoc) {
5498 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5499}
5500
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005501StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5502 SourceLocation EndLoc) {
5503 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5504}
5505
Alexey Bataev2df347a2014-07-18 10:17:07 +00005506StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5507 SourceLocation EndLoc) {
5508 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5509}
5510
Alexey Bataev169d96a2017-07-18 20:17:46 +00005511StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5512 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005513 SourceLocation StartLoc,
5514 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005515 if (!AStmt)
5516 return StmtError();
5517
5518 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005519
5520 getCurFunction()->setHasBranchProtectedScope();
5521
Alexey Bataev169d96a2017-07-18 20:17:46 +00005522 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005523 AStmt,
5524 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005525}
5526
Alexey Bataev6125da92014-07-21 11:26:11 +00005527StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5528 SourceLocation StartLoc,
5529 SourceLocation EndLoc) {
5530 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5531 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5532}
5533
Alexey Bataev346265e2015-09-25 10:37:12 +00005534StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5535 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005536 SourceLocation StartLoc,
5537 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005538 OMPClause *DependFound = nullptr;
5539 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005540 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005541 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005542 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005543 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005544 for (auto *C : Clauses) {
5545 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5546 DependFound = C;
5547 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5548 if (DependSourceClause) {
5549 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5550 << getOpenMPDirectiveName(OMPD_ordered)
5551 << getOpenMPClauseName(OMPC_depend) << 2;
5552 ErrorFound = true;
5553 } else
5554 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005555 if (DependSinkClause) {
5556 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5557 << 0;
5558 ErrorFound = true;
5559 }
5560 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5561 if (DependSourceClause) {
5562 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5563 << 1;
5564 ErrorFound = true;
5565 }
5566 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005567 }
5568 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005569 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005570 else if (C->getClauseKind() == OMPC_simd)
5571 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005572 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005573 if (!ErrorFound && !SC &&
5574 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005575 // OpenMP [2.8.1,simd Construct, Restrictions]
5576 // An ordered construct with the simd clause is the only OpenMP construct
5577 // that can appear in the simd region.
5578 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005579 ErrorFound = true;
5580 } else if (DependFound && (TC || SC)) {
5581 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5582 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5583 ErrorFound = true;
5584 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5585 Diag(DependFound->getLocStart(),
5586 diag::err_omp_ordered_directive_without_param);
5587 ErrorFound = true;
5588 } else if (TC || Clauses.empty()) {
5589 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5590 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5591 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5592 << (TC != nullptr);
5593 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5594 ErrorFound = true;
5595 }
5596 }
5597 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005598 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005599
5600 if (AStmt) {
5601 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5602
5603 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005604 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005605
5606 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005607}
5608
Alexey Bataev1d160b12015-03-13 12:27:31 +00005609namespace {
5610/// \brief Helper class for checking expression in 'omp atomic [update]'
5611/// construct.
5612class OpenMPAtomicUpdateChecker {
5613 /// \brief Error results for atomic update expressions.
5614 enum ExprAnalysisErrorCode {
5615 /// \brief A statement is not an expression statement.
5616 NotAnExpression,
5617 /// \brief Expression is not builtin binary or unary operation.
5618 NotABinaryOrUnaryExpression,
5619 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5620 NotAnUnaryIncDecExpression,
5621 /// \brief An expression is not of scalar type.
5622 NotAScalarType,
5623 /// \brief A binary operation is not an assignment operation.
5624 NotAnAssignmentOp,
5625 /// \brief RHS part of the binary operation is not a binary expression.
5626 NotABinaryExpression,
5627 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5628 /// expression.
5629 NotABinaryOperator,
5630 /// \brief RHS binary operation does not have reference to the updated LHS
5631 /// part.
5632 NotAnUpdateExpression,
5633 /// \brief No errors is found.
5634 NoError
5635 };
5636 /// \brief Reference to Sema.
5637 Sema &SemaRef;
5638 /// \brief A location for note diagnostics (when error is found).
5639 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005640 /// \brief 'x' lvalue part of the source atomic expression.
5641 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005642 /// \brief 'expr' rvalue part of the source atomic expression.
5643 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005644 /// \brief Helper expression of the form
5645 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5646 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5647 Expr *UpdateExpr;
5648 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5649 /// important for non-associative operations.
5650 bool IsXLHSInRHSPart;
5651 BinaryOperatorKind Op;
5652 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005653 /// \brief true if the source expression is a postfix unary operation, false
5654 /// if it is a prefix unary operation.
5655 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005656
5657public:
5658 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005659 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005660 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005661 /// \brief Check specified statement that it is suitable for 'atomic update'
5662 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005663 /// expression. If DiagId and NoteId == 0, then only check is performed
5664 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005665 /// \param DiagId Diagnostic which should be emitted if error is found.
5666 /// \param NoteId Diagnostic note for the main error message.
5667 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005668 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005669 /// \brief Return the 'x' lvalue part of the source atomic expression.
5670 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005671 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5672 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005673 /// \brief Return the update expression used in calculation of the updated
5674 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5675 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5676 Expr *getUpdateExpr() const { return UpdateExpr; }
5677 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5678 /// false otherwise.
5679 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5680
Alexey Bataevb78ca832015-04-01 03:33:17 +00005681 /// \brief true if the source expression is a postfix unary operation, false
5682 /// if it is a prefix unary operation.
5683 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5684
Alexey Bataev1d160b12015-03-13 12:27:31 +00005685private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005686 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5687 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005688};
5689} // namespace
5690
5691bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5692 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5693 ExprAnalysisErrorCode ErrorFound = NoError;
5694 SourceLocation ErrorLoc, NoteLoc;
5695 SourceRange ErrorRange, NoteRange;
5696 // Allowed constructs are:
5697 // x = x binop expr;
5698 // x = expr binop x;
5699 if (AtomicBinOp->getOpcode() == BO_Assign) {
5700 X = AtomicBinOp->getLHS();
5701 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5702 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5703 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5704 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5705 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005706 Op = AtomicInnerBinOp->getOpcode();
5707 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005708 auto *LHS = AtomicInnerBinOp->getLHS();
5709 auto *RHS = AtomicInnerBinOp->getRHS();
5710 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5711 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5712 /*Canonical=*/true);
5713 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5714 /*Canonical=*/true);
5715 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5716 /*Canonical=*/true);
5717 if (XId == LHSId) {
5718 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005719 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005720 } else if (XId == RHSId) {
5721 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005722 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005723 } else {
5724 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5725 ErrorRange = AtomicInnerBinOp->getSourceRange();
5726 NoteLoc = X->getExprLoc();
5727 NoteRange = X->getSourceRange();
5728 ErrorFound = NotAnUpdateExpression;
5729 }
5730 } else {
5731 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5732 ErrorRange = AtomicInnerBinOp->getSourceRange();
5733 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5734 NoteRange = SourceRange(NoteLoc, NoteLoc);
5735 ErrorFound = NotABinaryOperator;
5736 }
5737 } else {
5738 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5739 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5740 ErrorFound = NotABinaryExpression;
5741 }
5742 } else {
5743 ErrorLoc = AtomicBinOp->getExprLoc();
5744 ErrorRange = AtomicBinOp->getSourceRange();
5745 NoteLoc = AtomicBinOp->getOperatorLoc();
5746 NoteRange = SourceRange(NoteLoc, NoteLoc);
5747 ErrorFound = NotAnAssignmentOp;
5748 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005749 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005750 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5751 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5752 return true;
5753 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005754 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005755 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005756}
5757
5758bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5759 unsigned NoteId) {
5760 ExprAnalysisErrorCode ErrorFound = NoError;
5761 SourceLocation ErrorLoc, NoteLoc;
5762 SourceRange ErrorRange, NoteRange;
5763 // Allowed constructs are:
5764 // x++;
5765 // x--;
5766 // ++x;
5767 // --x;
5768 // x binop= expr;
5769 // x = x binop expr;
5770 // x = expr binop x;
5771 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5772 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5773 if (AtomicBody->getType()->isScalarType() ||
5774 AtomicBody->isInstantiationDependent()) {
5775 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5776 AtomicBody->IgnoreParenImpCasts())) {
5777 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005778 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005779 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005780 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005781 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005782 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005783 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005784 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5785 AtomicBody->IgnoreParenImpCasts())) {
5786 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005787 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005788 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005789 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5790 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005791 // Check for Unary Operation
5792 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005793 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005794 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5795 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005796 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005797 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5798 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005799 } else {
5800 ErrorFound = NotAnUnaryIncDecExpression;
5801 ErrorLoc = AtomicUnaryOp->getExprLoc();
5802 ErrorRange = AtomicUnaryOp->getSourceRange();
5803 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5804 NoteRange = SourceRange(NoteLoc, NoteLoc);
5805 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005806 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005807 ErrorFound = NotABinaryOrUnaryExpression;
5808 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5809 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5810 }
5811 } else {
5812 ErrorFound = NotAScalarType;
5813 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5814 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5815 }
5816 } else {
5817 ErrorFound = NotAnExpression;
5818 NoteLoc = ErrorLoc = S->getLocStart();
5819 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5820 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005821 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005822 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5823 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5824 return true;
5825 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005826 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005827 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005828 // Build an update expression of form 'OpaqueValueExpr(x) binop
5829 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5830 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5831 auto *OVEX = new (SemaRef.getASTContext())
5832 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5833 auto *OVEExpr = new (SemaRef.getASTContext())
5834 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5835 auto Update =
5836 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5837 IsXLHSInRHSPart ? OVEExpr : OVEX);
5838 if (Update.isInvalid())
5839 return true;
5840 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5841 Sema::AA_Casting);
5842 if (Update.isInvalid())
5843 return true;
5844 UpdateExpr = Update.get();
5845 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005846 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005847}
5848
Alexey Bataev0162e452014-07-22 10:10:35 +00005849StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5850 Stmt *AStmt,
5851 SourceLocation StartLoc,
5852 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005853 if (!AStmt)
5854 return StmtError();
5855
David Majnemer9d168222016-08-05 17:44:54 +00005856 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005857 // 1.2.2 OpenMP Language Terminology
5858 // Structured block - An executable statement with a single entry at the
5859 // top and a single exit at the bottom.
5860 // The point of exit cannot be a branch out of the structured block.
5861 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005862 OpenMPClauseKind AtomicKind = OMPC_unknown;
5863 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005864 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005865 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005866 C->getClauseKind() == OMPC_update ||
5867 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005868 if (AtomicKind != OMPC_unknown) {
5869 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5870 << SourceRange(C->getLocStart(), C->getLocEnd());
5871 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5872 << getOpenMPClauseName(AtomicKind);
5873 } else {
5874 AtomicKind = C->getClauseKind();
5875 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005876 }
5877 }
5878 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005879
Alexey Bataev459dec02014-07-24 06:46:57 +00005880 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005881 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5882 Body = EWC->getSubExpr();
5883
Alexey Bataev62cec442014-11-18 10:14:22 +00005884 Expr *X = nullptr;
5885 Expr *V = nullptr;
5886 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005887 Expr *UE = nullptr;
5888 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005889 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005890 // OpenMP [2.12.6, atomic Construct]
5891 // In the next expressions:
5892 // * x and v (as applicable) are both l-value expressions with scalar type.
5893 // * During the execution of an atomic region, multiple syntactic
5894 // occurrences of x must designate the same storage location.
5895 // * Neither of v and expr (as applicable) may access the storage location
5896 // designated by x.
5897 // * Neither of x and expr (as applicable) may access the storage location
5898 // designated by v.
5899 // * expr is an expression with scalar type.
5900 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5901 // * binop, binop=, ++, and -- are not overloaded operators.
5902 // * The expression x binop expr must be numerically equivalent to x binop
5903 // (expr). This requirement is satisfied if the operators in expr have
5904 // precedence greater than binop, or by using parentheses around expr or
5905 // subexpressions of expr.
5906 // * The expression expr binop x must be numerically equivalent to (expr)
5907 // binop x. This requirement is satisfied if the operators in expr have
5908 // precedence equal to or greater than binop, or by using parentheses around
5909 // expr or subexpressions of expr.
5910 // * For forms that allow multiple occurrences of x, the number of times
5911 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005912 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005913 enum {
5914 NotAnExpression,
5915 NotAnAssignmentOp,
5916 NotAScalarType,
5917 NotAnLValue,
5918 NoError
5919 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005920 SourceLocation ErrorLoc, NoteLoc;
5921 SourceRange ErrorRange, NoteRange;
5922 // If clause is read:
5923 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005924 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5925 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005926 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5927 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5928 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5929 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5930 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5931 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5932 if (!X->isLValue() || !V->isLValue()) {
5933 auto NotLValueExpr = X->isLValue() ? V : X;
5934 ErrorFound = NotAnLValue;
5935 ErrorLoc = AtomicBinOp->getExprLoc();
5936 ErrorRange = AtomicBinOp->getSourceRange();
5937 NoteLoc = NotLValueExpr->getExprLoc();
5938 NoteRange = NotLValueExpr->getSourceRange();
5939 }
5940 } else if (!X->isInstantiationDependent() ||
5941 !V->isInstantiationDependent()) {
5942 auto NotScalarExpr =
5943 (X->isInstantiationDependent() || X->getType()->isScalarType())
5944 ? V
5945 : X;
5946 ErrorFound = NotAScalarType;
5947 ErrorLoc = AtomicBinOp->getExprLoc();
5948 ErrorRange = AtomicBinOp->getSourceRange();
5949 NoteLoc = NotScalarExpr->getExprLoc();
5950 NoteRange = NotScalarExpr->getSourceRange();
5951 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005952 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005953 ErrorFound = NotAnAssignmentOp;
5954 ErrorLoc = AtomicBody->getExprLoc();
5955 ErrorRange = AtomicBody->getSourceRange();
5956 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5957 : AtomicBody->getExprLoc();
5958 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5959 : AtomicBody->getSourceRange();
5960 }
5961 } else {
5962 ErrorFound = NotAnExpression;
5963 NoteLoc = ErrorLoc = Body->getLocStart();
5964 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005965 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005966 if (ErrorFound != NoError) {
5967 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5968 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005969 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5970 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005971 return StmtError();
5972 } else if (CurContext->isDependentContext())
5973 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005974 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005975 enum {
5976 NotAnExpression,
5977 NotAnAssignmentOp,
5978 NotAScalarType,
5979 NotAnLValue,
5980 NoError
5981 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005982 SourceLocation ErrorLoc, NoteLoc;
5983 SourceRange ErrorRange, NoteRange;
5984 // If clause is write:
5985 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005986 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5987 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005988 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5989 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005990 X = AtomicBinOp->getLHS();
5991 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005992 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5993 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5994 if (!X->isLValue()) {
5995 ErrorFound = NotAnLValue;
5996 ErrorLoc = AtomicBinOp->getExprLoc();
5997 ErrorRange = AtomicBinOp->getSourceRange();
5998 NoteLoc = X->getExprLoc();
5999 NoteRange = X->getSourceRange();
6000 }
6001 } else if (!X->isInstantiationDependent() ||
6002 !E->isInstantiationDependent()) {
6003 auto NotScalarExpr =
6004 (X->isInstantiationDependent() || X->getType()->isScalarType())
6005 ? E
6006 : X;
6007 ErrorFound = NotAScalarType;
6008 ErrorLoc = AtomicBinOp->getExprLoc();
6009 ErrorRange = AtomicBinOp->getSourceRange();
6010 NoteLoc = NotScalarExpr->getExprLoc();
6011 NoteRange = NotScalarExpr->getSourceRange();
6012 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006013 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006014 ErrorFound = NotAnAssignmentOp;
6015 ErrorLoc = AtomicBody->getExprLoc();
6016 ErrorRange = AtomicBody->getSourceRange();
6017 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6018 : AtomicBody->getExprLoc();
6019 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6020 : AtomicBody->getSourceRange();
6021 }
6022 } else {
6023 ErrorFound = NotAnExpression;
6024 NoteLoc = ErrorLoc = Body->getLocStart();
6025 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006026 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006027 if (ErrorFound != NoError) {
6028 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6029 << ErrorRange;
6030 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6031 << NoteRange;
6032 return StmtError();
6033 } else if (CurContext->isDependentContext())
6034 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006035 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006036 // If clause is update:
6037 // x++;
6038 // x--;
6039 // ++x;
6040 // --x;
6041 // x binop= expr;
6042 // x = x binop expr;
6043 // x = expr binop x;
6044 OpenMPAtomicUpdateChecker Checker(*this);
6045 if (Checker.checkStatement(
6046 Body, (AtomicKind == OMPC_update)
6047 ? diag::err_omp_atomic_update_not_expression_statement
6048 : diag::err_omp_atomic_not_expression_statement,
6049 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006050 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006051 if (!CurContext->isDependentContext()) {
6052 E = Checker.getExpr();
6053 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006054 UE = Checker.getUpdateExpr();
6055 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006056 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006057 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006058 enum {
6059 NotAnAssignmentOp,
6060 NotACompoundStatement,
6061 NotTwoSubstatements,
6062 NotASpecificExpression,
6063 NoError
6064 } ErrorFound = NoError;
6065 SourceLocation ErrorLoc, NoteLoc;
6066 SourceRange ErrorRange, NoteRange;
6067 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6068 // If clause is a capture:
6069 // v = x++;
6070 // v = x--;
6071 // v = ++x;
6072 // v = --x;
6073 // v = x binop= expr;
6074 // v = x = x binop expr;
6075 // v = x = expr binop x;
6076 auto *AtomicBinOp =
6077 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6078 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6079 V = AtomicBinOp->getLHS();
6080 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6081 OpenMPAtomicUpdateChecker Checker(*this);
6082 if (Checker.checkStatement(
6083 Body, diag::err_omp_atomic_capture_not_expression_statement,
6084 diag::note_omp_atomic_update))
6085 return StmtError();
6086 E = Checker.getExpr();
6087 X = Checker.getX();
6088 UE = Checker.getUpdateExpr();
6089 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6090 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006091 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006092 ErrorLoc = AtomicBody->getExprLoc();
6093 ErrorRange = AtomicBody->getSourceRange();
6094 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6095 : AtomicBody->getExprLoc();
6096 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6097 : AtomicBody->getSourceRange();
6098 ErrorFound = NotAnAssignmentOp;
6099 }
6100 if (ErrorFound != NoError) {
6101 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6102 << ErrorRange;
6103 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6104 return StmtError();
6105 } else if (CurContext->isDependentContext()) {
6106 UE = V = E = X = nullptr;
6107 }
6108 } else {
6109 // If clause is a capture:
6110 // { v = x; x = expr; }
6111 // { v = x; x++; }
6112 // { v = x; x--; }
6113 // { v = x; ++x; }
6114 // { v = x; --x; }
6115 // { v = x; x binop= expr; }
6116 // { v = x; x = x binop expr; }
6117 // { v = x; x = expr binop x; }
6118 // { x++; v = x; }
6119 // { x--; v = x; }
6120 // { ++x; v = x; }
6121 // { --x; v = x; }
6122 // { x binop= expr; v = x; }
6123 // { x = x binop expr; v = x; }
6124 // { x = expr binop x; v = x; }
6125 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6126 // Check that this is { expr1; expr2; }
6127 if (CS->size() == 2) {
6128 auto *First = CS->body_front();
6129 auto *Second = CS->body_back();
6130 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6131 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6132 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6133 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6134 // Need to find what subexpression is 'v' and what is 'x'.
6135 OpenMPAtomicUpdateChecker Checker(*this);
6136 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6137 BinaryOperator *BinOp = nullptr;
6138 if (IsUpdateExprFound) {
6139 BinOp = dyn_cast<BinaryOperator>(First);
6140 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6141 }
6142 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6143 // { v = x; x++; }
6144 // { v = x; x--; }
6145 // { v = x; ++x; }
6146 // { v = x; --x; }
6147 // { v = x; x binop= expr; }
6148 // { v = x; x = x binop expr; }
6149 // { v = x; x = expr binop x; }
6150 // Check that the first expression has form v = x.
6151 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6152 llvm::FoldingSetNodeID XId, PossibleXId;
6153 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6154 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6155 IsUpdateExprFound = XId == PossibleXId;
6156 if (IsUpdateExprFound) {
6157 V = BinOp->getLHS();
6158 X = Checker.getX();
6159 E = Checker.getExpr();
6160 UE = Checker.getUpdateExpr();
6161 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006162 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006163 }
6164 }
6165 if (!IsUpdateExprFound) {
6166 IsUpdateExprFound = !Checker.checkStatement(First);
6167 BinOp = nullptr;
6168 if (IsUpdateExprFound) {
6169 BinOp = dyn_cast<BinaryOperator>(Second);
6170 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6171 }
6172 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6173 // { x++; v = x; }
6174 // { x--; v = x; }
6175 // { ++x; v = x; }
6176 // { --x; v = x; }
6177 // { x binop= expr; v = x; }
6178 // { x = x binop expr; v = x; }
6179 // { x = expr binop x; v = x; }
6180 // Check that the second expression has form v = x.
6181 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6182 llvm::FoldingSetNodeID XId, PossibleXId;
6183 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6184 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6185 IsUpdateExprFound = XId == PossibleXId;
6186 if (IsUpdateExprFound) {
6187 V = BinOp->getLHS();
6188 X = Checker.getX();
6189 E = Checker.getExpr();
6190 UE = Checker.getUpdateExpr();
6191 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006192 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006193 }
6194 }
6195 }
6196 if (!IsUpdateExprFound) {
6197 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006198 auto *FirstExpr = dyn_cast<Expr>(First);
6199 auto *SecondExpr = dyn_cast<Expr>(Second);
6200 if (!FirstExpr || !SecondExpr ||
6201 !(FirstExpr->isInstantiationDependent() ||
6202 SecondExpr->isInstantiationDependent())) {
6203 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6204 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006205 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006206 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6207 : First->getLocStart();
6208 NoteRange = ErrorRange = FirstBinOp
6209 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006210 : SourceRange(ErrorLoc, ErrorLoc);
6211 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006212 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6213 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6214 ErrorFound = NotAnAssignmentOp;
6215 NoteLoc = ErrorLoc = SecondBinOp
6216 ? SecondBinOp->getOperatorLoc()
6217 : Second->getLocStart();
6218 NoteRange = ErrorRange =
6219 SecondBinOp ? SecondBinOp->getSourceRange()
6220 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006221 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006222 auto *PossibleXRHSInFirst =
6223 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6224 auto *PossibleXLHSInSecond =
6225 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6226 llvm::FoldingSetNodeID X1Id, X2Id;
6227 PossibleXRHSInFirst->Profile(X1Id, Context,
6228 /*Canonical=*/true);
6229 PossibleXLHSInSecond->Profile(X2Id, Context,
6230 /*Canonical=*/true);
6231 IsUpdateExprFound = X1Id == X2Id;
6232 if (IsUpdateExprFound) {
6233 V = FirstBinOp->getLHS();
6234 X = SecondBinOp->getLHS();
6235 E = SecondBinOp->getRHS();
6236 UE = nullptr;
6237 IsXLHSInRHSPart = false;
6238 IsPostfixUpdate = true;
6239 } else {
6240 ErrorFound = NotASpecificExpression;
6241 ErrorLoc = FirstBinOp->getExprLoc();
6242 ErrorRange = FirstBinOp->getSourceRange();
6243 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6244 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6245 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006246 }
6247 }
6248 }
6249 }
6250 } else {
6251 NoteLoc = ErrorLoc = Body->getLocStart();
6252 NoteRange = ErrorRange =
6253 SourceRange(Body->getLocStart(), Body->getLocStart());
6254 ErrorFound = NotTwoSubstatements;
6255 }
6256 } else {
6257 NoteLoc = ErrorLoc = Body->getLocStart();
6258 NoteRange = ErrorRange =
6259 SourceRange(Body->getLocStart(), Body->getLocStart());
6260 ErrorFound = NotACompoundStatement;
6261 }
6262 if (ErrorFound != NoError) {
6263 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6264 << ErrorRange;
6265 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6266 return StmtError();
6267 } else if (CurContext->isDependentContext()) {
6268 UE = V = E = X = nullptr;
6269 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006270 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006271 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006272
6273 getCurFunction()->setHasBranchProtectedScope();
6274
Alexey Bataev62cec442014-11-18 10:14:22 +00006275 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006276 X, V, E, UE, IsXLHSInRHSPart,
6277 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006278}
6279
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006280StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6281 Stmt *AStmt,
6282 SourceLocation StartLoc,
6283 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006284 if (!AStmt)
6285 return StmtError();
6286
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006287 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6288 // 1.2.2 OpenMP Language Terminology
6289 // Structured block - An executable statement with a single entry at the
6290 // top and a single exit at the bottom.
6291 // The point of exit cannot be a branch out of the structured block.
6292 // longjmp() and throw() must not violate the entry/exit criteria.
6293 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006294
Alexey Bataev13314bf2014-10-09 04:18:56 +00006295 // OpenMP [2.16, Nesting of Regions]
6296 // If specified, a teams construct must be contained within a target
6297 // construct. That target construct must contain no statements or directives
6298 // outside of the teams construct.
6299 if (DSAStack->hasInnerTeamsRegion()) {
6300 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6301 bool OMPTeamsFound = true;
6302 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6303 auto I = CS->body_begin();
6304 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006305 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006306 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6307 OMPTeamsFound = false;
6308 break;
6309 }
6310 ++I;
6311 }
6312 assert(I != CS->body_end() && "Not found statement");
6313 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006314 } else {
6315 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6316 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006317 }
6318 if (!OMPTeamsFound) {
6319 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6320 Diag(DSAStack->getInnerTeamsRegionLoc(),
6321 diag::note_omp_nested_teams_construct_here);
6322 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6323 << isa<OMPExecutableDirective>(S);
6324 return StmtError();
6325 }
6326 }
6327
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006328 getCurFunction()->setHasBranchProtectedScope();
6329
6330 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6331}
6332
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006333StmtResult
6334Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6335 Stmt *AStmt, SourceLocation StartLoc,
6336 SourceLocation EndLoc) {
6337 if (!AStmt)
6338 return StmtError();
6339
6340 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6341 // 1.2.2 OpenMP Language Terminology
6342 // Structured block - An executable statement with a single entry at the
6343 // top and a single exit at the bottom.
6344 // The point of exit cannot be a branch out of the structured block.
6345 // longjmp() and throw() must not violate the entry/exit criteria.
6346 CS->getCapturedDecl()->setNothrow();
6347
6348 getCurFunction()->setHasBranchProtectedScope();
6349
6350 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6351 AStmt);
6352}
6353
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006354StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6355 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6356 SourceLocation EndLoc,
6357 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6358 if (!AStmt)
6359 return StmtError();
6360
6361 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6362 // 1.2.2 OpenMP Language Terminology
6363 // Structured block - An executable statement with a single entry at the
6364 // top and a single exit at the bottom.
6365 // The point of exit cannot be a branch out of the structured block.
6366 // longjmp() and throw() must not violate the entry/exit criteria.
6367 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006368 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6369 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6370 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6371 // 1.2.2 OpenMP Language Terminology
6372 // Structured block - An executable statement with a single entry at the
6373 // top and a single exit at the bottom.
6374 // The point of exit cannot be a branch out of the structured block.
6375 // longjmp() and throw() must not violate the entry/exit criteria.
6376 CS->getCapturedDecl()->setNothrow();
6377 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006378
6379 OMPLoopDirective::HelperExprs B;
6380 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6381 // define the nested loops number.
6382 unsigned NestedLoopCount =
6383 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006384 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006385 VarsWithImplicitDSA, B);
6386 if (NestedLoopCount == 0)
6387 return StmtError();
6388
6389 assert((CurContext->isDependentContext() || B.builtAll()) &&
6390 "omp target parallel for loop exprs were not built");
6391
6392 if (!CurContext->isDependentContext()) {
6393 // Finalize the clauses that need pre-built expressions for CodeGen.
6394 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006395 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006396 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006397 B.NumIterations, *this, CurScope,
6398 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006399 return StmtError();
6400 }
6401 }
6402
6403 getCurFunction()->setHasBranchProtectedScope();
6404 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6405 NestedLoopCount, Clauses, AStmt,
6406 B, DSAStack->isCancelRegion());
6407}
6408
Alexey Bataev95b64a92017-05-30 16:00:04 +00006409/// Check for existence of a map clause in the list of clauses.
6410static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6411 const OpenMPClauseKind K) {
6412 return llvm::any_of(
6413 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6414}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006415
Alexey Bataev95b64a92017-05-30 16:00:04 +00006416template <typename... Params>
6417static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6418 const Params... ClauseTypes) {
6419 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006420}
6421
Michael Wong65f367f2015-07-21 13:44:28 +00006422StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6423 Stmt *AStmt,
6424 SourceLocation StartLoc,
6425 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006426 if (!AStmt)
6427 return StmtError();
6428
6429 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6430
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006431 // OpenMP [2.10.1, Restrictions, p. 97]
6432 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006433 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6434 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6435 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006436 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006437 return StmtError();
6438 }
6439
Michael Wong65f367f2015-07-21 13:44:28 +00006440 getCurFunction()->setHasBranchProtectedScope();
6441
6442 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6443 AStmt);
6444}
6445
Samuel Antaodf67fc42016-01-19 19:15:56 +00006446StmtResult
6447Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6448 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006449 SourceLocation EndLoc, Stmt *AStmt) {
6450 if (!AStmt)
6451 return StmtError();
6452
6453 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6454 // 1.2.2 OpenMP Language Terminology
6455 // Structured block - An executable statement with a single entry at the
6456 // top and a single exit at the bottom.
6457 // The point of exit cannot be a branch out of the structured block.
6458 // longjmp() and throw() must not violate the entry/exit criteria.
6459 CS->getCapturedDecl()->setNothrow();
6460 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6461 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6462 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6463 // 1.2.2 OpenMP Language Terminology
6464 // Structured block - An executable statement with a single entry at the
6465 // top and a single exit at the bottom.
6466 // The point of exit cannot be a branch out of the structured block.
6467 // longjmp() and throw() must not violate the entry/exit criteria.
6468 CS->getCapturedDecl()->setNothrow();
6469 }
6470
Samuel Antaodf67fc42016-01-19 19:15:56 +00006471 // OpenMP [2.10.2, Restrictions, p. 99]
6472 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006473 if (!hasClauses(Clauses, OMPC_map)) {
6474 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6475 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006476 return StmtError();
6477 }
6478
Alexey Bataev7828b252017-11-21 17:08:48 +00006479 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6480 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006481}
6482
Samuel Antao72590762016-01-19 20:04:50 +00006483StmtResult
6484Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6485 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006486 SourceLocation EndLoc, Stmt *AStmt) {
6487 if (!AStmt)
6488 return StmtError();
6489
6490 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6491 // 1.2.2 OpenMP Language Terminology
6492 // Structured block - An executable statement with a single entry at the
6493 // top and a single exit at the bottom.
6494 // The point of exit cannot be a branch out of the structured block.
6495 // longjmp() and throw() must not violate the entry/exit criteria.
6496 CS->getCapturedDecl()->setNothrow();
6497 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6498 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6499 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6500 // 1.2.2 OpenMP Language Terminology
6501 // Structured block - An executable statement with a single entry at the
6502 // top and a single exit at the bottom.
6503 // The point of exit cannot be a branch out of the structured block.
6504 // longjmp() and throw() must not violate the entry/exit criteria.
6505 CS->getCapturedDecl()->setNothrow();
6506 }
6507
Samuel Antao72590762016-01-19 20:04:50 +00006508 // OpenMP [2.10.3, Restrictions, p. 102]
6509 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006510 if (!hasClauses(Clauses, OMPC_map)) {
6511 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6512 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006513 return StmtError();
6514 }
6515
Alexey Bataev7828b252017-11-21 17:08:48 +00006516 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6517 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006518}
6519
Samuel Antao686c70c2016-05-26 17:30:50 +00006520StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6521 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006522 SourceLocation EndLoc,
6523 Stmt *AStmt) {
6524 if (!AStmt)
6525 return StmtError();
6526
6527 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6528 // 1.2.2 OpenMP Language Terminology
6529 // Structured block - An executable statement with a single entry at the
6530 // top and a single exit at the bottom.
6531 // The point of exit cannot be a branch out of the structured block.
6532 // longjmp() and throw() must not violate the entry/exit criteria.
6533 CS->getCapturedDecl()->setNothrow();
6534 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6535 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6536 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6537 // 1.2.2 OpenMP Language Terminology
6538 // Structured block - An executable statement with a single entry at the
6539 // top and a single exit at the bottom.
6540 // The point of exit cannot be a branch out of the structured block.
6541 // longjmp() and throw() must not violate the entry/exit criteria.
6542 CS->getCapturedDecl()->setNothrow();
6543 }
6544
Alexey Bataev95b64a92017-05-30 16:00:04 +00006545 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006546 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6547 return StmtError();
6548 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006549 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6550 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006551}
6552
Alexey Bataev13314bf2014-10-09 04:18:56 +00006553StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6554 Stmt *AStmt, SourceLocation StartLoc,
6555 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006556 if (!AStmt)
6557 return StmtError();
6558
Alexey Bataev13314bf2014-10-09 04:18:56 +00006559 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6560 // 1.2.2 OpenMP Language Terminology
6561 // Structured block - An executable statement with a single entry at the
6562 // top and a single exit at the bottom.
6563 // The point of exit cannot be a branch out of the structured block.
6564 // longjmp() and throw() must not violate the entry/exit criteria.
6565 CS->getCapturedDecl()->setNothrow();
6566
6567 getCurFunction()->setHasBranchProtectedScope();
6568
Alexey Bataevceabd412017-11-30 18:01:54 +00006569 DSAStack->setParentTeamsRegionLoc(StartLoc);
6570
Alexey Bataev13314bf2014-10-09 04:18:56 +00006571 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6572}
6573
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006574StmtResult
6575Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6576 SourceLocation EndLoc,
6577 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006578 if (DSAStack->isParentNowaitRegion()) {
6579 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6580 return StmtError();
6581 }
6582 if (DSAStack->isParentOrderedRegion()) {
6583 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6584 return StmtError();
6585 }
6586 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6587 CancelRegion);
6588}
6589
Alexey Bataev87933c72015-09-18 08:07:34 +00006590StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6591 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006592 SourceLocation EndLoc,
6593 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006594 if (DSAStack->isParentNowaitRegion()) {
6595 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6596 return StmtError();
6597 }
6598 if (DSAStack->isParentOrderedRegion()) {
6599 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6600 return StmtError();
6601 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006602 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006603 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6604 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006605}
6606
Alexey Bataev382967a2015-12-08 12:06:20 +00006607static bool checkGrainsizeNumTasksClauses(Sema &S,
6608 ArrayRef<OMPClause *> Clauses) {
6609 OMPClause *PrevClause = nullptr;
6610 bool ErrorFound = false;
6611 for (auto *C : Clauses) {
6612 if (C->getClauseKind() == OMPC_grainsize ||
6613 C->getClauseKind() == OMPC_num_tasks) {
6614 if (!PrevClause)
6615 PrevClause = C;
6616 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6617 S.Diag(C->getLocStart(),
6618 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6619 << getOpenMPClauseName(C->getClauseKind())
6620 << getOpenMPClauseName(PrevClause->getClauseKind());
6621 S.Diag(PrevClause->getLocStart(),
6622 diag::note_omp_previous_grainsize_num_tasks)
6623 << getOpenMPClauseName(PrevClause->getClauseKind());
6624 ErrorFound = true;
6625 }
6626 }
6627 }
6628 return ErrorFound;
6629}
6630
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006631static bool checkReductionClauseWithNogroup(Sema &S,
6632 ArrayRef<OMPClause *> Clauses) {
6633 OMPClause *ReductionClause = nullptr;
6634 OMPClause *NogroupClause = nullptr;
6635 for (auto *C : Clauses) {
6636 if (C->getClauseKind() == OMPC_reduction) {
6637 ReductionClause = C;
6638 if (NogroupClause)
6639 break;
6640 continue;
6641 }
6642 if (C->getClauseKind() == OMPC_nogroup) {
6643 NogroupClause = C;
6644 if (ReductionClause)
6645 break;
6646 continue;
6647 }
6648 }
6649 if (ReductionClause && NogroupClause) {
6650 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6651 << SourceRange(NogroupClause->getLocStart(),
6652 NogroupClause->getLocEnd());
6653 return true;
6654 }
6655 return false;
6656}
6657
Alexey Bataev49f6e782015-12-01 04:18:41 +00006658StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6659 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6660 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006661 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006662 if (!AStmt)
6663 return StmtError();
6664
6665 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6666 OMPLoopDirective::HelperExprs B;
6667 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6668 // define the nested loops number.
6669 unsigned NestedLoopCount =
6670 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006671 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006672 VarsWithImplicitDSA, B);
6673 if (NestedLoopCount == 0)
6674 return StmtError();
6675
6676 assert((CurContext->isDependentContext() || B.builtAll()) &&
6677 "omp for loop exprs were not built");
6678
Alexey Bataev382967a2015-12-08 12:06:20 +00006679 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6680 // The grainsize clause and num_tasks clause are mutually exclusive and may
6681 // not appear on the same taskloop directive.
6682 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6683 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006684 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6685 // If a reduction clause is present on the taskloop directive, the nogroup
6686 // clause must not be specified.
6687 if (checkReductionClauseWithNogroup(*this, Clauses))
6688 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006689
Alexey Bataev49f6e782015-12-01 04:18:41 +00006690 getCurFunction()->setHasBranchProtectedScope();
6691 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6692 NestedLoopCount, Clauses, AStmt, B);
6693}
6694
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006695StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6697 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006698 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006699 if (!AStmt)
6700 return StmtError();
6701
6702 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6703 OMPLoopDirective::HelperExprs B;
6704 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6705 // define the nested loops number.
6706 unsigned NestedLoopCount =
6707 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6708 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6709 VarsWithImplicitDSA, B);
6710 if (NestedLoopCount == 0)
6711 return StmtError();
6712
6713 assert((CurContext->isDependentContext() || B.builtAll()) &&
6714 "omp for loop exprs were not built");
6715
Alexey Bataev5a3af132016-03-29 08:58:54 +00006716 if (!CurContext->isDependentContext()) {
6717 // Finalize the clauses that need pre-built expressions for CodeGen.
6718 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006719 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006720 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006721 B.NumIterations, *this, CurScope,
6722 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006723 return StmtError();
6724 }
6725 }
6726
Alexey Bataev382967a2015-12-08 12:06:20 +00006727 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6728 // The grainsize clause and num_tasks clause are mutually exclusive and may
6729 // not appear on the same taskloop directive.
6730 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6731 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006732 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6733 // If a reduction clause is present on the taskloop directive, the nogroup
6734 // clause must not be specified.
6735 if (checkReductionClauseWithNogroup(*this, Clauses))
6736 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006737 if (checkSimdlenSafelenSpecified(*this, Clauses))
6738 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006739
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006740 getCurFunction()->setHasBranchProtectedScope();
6741 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6742 NestedLoopCount, Clauses, AStmt, B);
6743}
6744
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006745StmtResult Sema::ActOnOpenMPDistributeDirective(
6746 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6747 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006748 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006749 if (!AStmt)
6750 return StmtError();
6751
6752 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6753 OMPLoopDirective::HelperExprs B;
6754 // In presence of clause 'collapse' with number of loops, it will
6755 // define the nested loops number.
6756 unsigned NestedLoopCount =
6757 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6758 nullptr /*ordered not a clause on distribute*/, AStmt,
6759 *this, *DSAStack, VarsWithImplicitDSA, B);
6760 if (NestedLoopCount == 0)
6761 return StmtError();
6762
6763 assert((CurContext->isDependentContext() || B.builtAll()) &&
6764 "omp for loop exprs were not built");
6765
6766 getCurFunction()->setHasBranchProtectedScope();
6767 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6768 NestedLoopCount, Clauses, AStmt, B);
6769}
6770
Carlo Bertolli9925f152016-06-27 14:55:37 +00006771StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6772 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6773 SourceLocation EndLoc,
6774 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6775 if (!AStmt)
6776 return StmtError();
6777
6778 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6779 // 1.2.2 OpenMP Language Terminology
6780 // Structured block - An executable statement with a single entry at the
6781 // top and a single exit at the bottom.
6782 // The point of exit cannot be a branch out of the structured block.
6783 // longjmp() and throw() must not violate the entry/exit criteria.
6784 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006785 for (int ThisCaptureLevel =
6786 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6787 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6788 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6789 // 1.2.2 OpenMP Language Terminology
6790 // Structured block - An executable statement with a single entry at the
6791 // top and a single exit at the bottom.
6792 // The point of exit cannot be a branch out of the structured block.
6793 // longjmp() and throw() must not violate the entry/exit criteria.
6794 CS->getCapturedDecl()->setNothrow();
6795 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006796
6797 OMPLoopDirective::HelperExprs B;
6798 // In presence of clause 'collapse' with number of loops, it will
6799 // define the nested loops number.
6800 unsigned NestedLoopCount = CheckOpenMPLoop(
6801 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006802 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006803 VarsWithImplicitDSA, B);
6804 if (NestedLoopCount == 0)
6805 return StmtError();
6806
6807 assert((CurContext->isDependentContext() || B.builtAll()) &&
6808 "omp for loop exprs were not built");
6809
6810 getCurFunction()->setHasBranchProtectedScope();
6811 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00006812 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
6813 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00006814}
6815
Kelvin Li4a39add2016-07-05 05:00:15 +00006816StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6817 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6818 SourceLocation EndLoc,
6819 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6820 if (!AStmt)
6821 return StmtError();
6822
6823 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6824 // 1.2.2 OpenMP Language Terminology
6825 // Structured block - An executable statement with a single entry at the
6826 // top and a single exit at the bottom.
6827 // The point of exit cannot be a branch out of the structured block.
6828 // longjmp() and throw() must not violate the entry/exit criteria.
6829 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00006830 for (int ThisCaptureLevel =
6831 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
6832 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6833 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6834 // 1.2.2 OpenMP Language Terminology
6835 // Structured block - An executable statement with a single entry at the
6836 // top and a single exit at the bottom.
6837 // The point of exit cannot be a branch out of the structured block.
6838 // longjmp() and throw() must not violate the entry/exit criteria.
6839 CS->getCapturedDecl()->setNothrow();
6840 }
Kelvin Li4a39add2016-07-05 05:00:15 +00006841
6842 OMPLoopDirective::HelperExprs B;
6843 // In presence of clause 'collapse' with number of loops, it will
6844 // define the nested loops number.
6845 unsigned NestedLoopCount = CheckOpenMPLoop(
6846 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00006847 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00006848 VarsWithImplicitDSA, B);
6849 if (NestedLoopCount == 0)
6850 return StmtError();
6851
6852 assert((CurContext->isDependentContext() || B.builtAll()) &&
6853 "omp for loop exprs were not built");
6854
Alexey Bataev438388c2017-11-22 18:34:02 +00006855 if (!CurContext->isDependentContext()) {
6856 // Finalize the clauses that need pre-built expressions for CodeGen.
6857 for (auto C : Clauses) {
6858 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6859 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6860 B.NumIterations, *this, CurScope,
6861 DSAStack))
6862 return StmtError();
6863 }
6864 }
6865
Kelvin Lic5609492016-07-15 04:39:07 +00006866 if (checkSimdlenSafelenSpecified(*this, Clauses))
6867 return StmtError();
6868
Kelvin Li4a39add2016-07-05 05:00:15 +00006869 getCurFunction()->setHasBranchProtectedScope();
6870 return OMPDistributeParallelForSimdDirective::Create(
6871 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6872}
6873
Kelvin Li787f3fc2016-07-06 04:45:38 +00006874StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6875 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6876 SourceLocation EndLoc,
6877 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6878 if (!AStmt)
6879 return StmtError();
6880
6881 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6882 // 1.2.2 OpenMP Language Terminology
6883 // Structured block - An executable statement with a single entry at the
6884 // top and a single exit at the bottom.
6885 // The point of exit cannot be a branch out of the structured block.
6886 // longjmp() and throw() must not violate the entry/exit criteria.
6887 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00006888 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
6889 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6890 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6891 // 1.2.2 OpenMP Language Terminology
6892 // Structured block - An executable statement with a single entry at the
6893 // top and a single exit at the bottom.
6894 // The point of exit cannot be a branch out of the structured block.
6895 // longjmp() and throw() must not violate the entry/exit criteria.
6896 CS->getCapturedDecl()->setNothrow();
6897 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00006898
6899 OMPLoopDirective::HelperExprs B;
6900 // In presence of clause 'collapse' with number of loops, it will
6901 // define the nested loops number.
6902 unsigned NestedLoopCount =
6903 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00006904 nullptr /*ordered not a clause on distribute*/, CS, *this,
6905 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00006906 if (NestedLoopCount == 0)
6907 return StmtError();
6908
6909 assert((CurContext->isDependentContext() || B.builtAll()) &&
6910 "omp for loop exprs were not built");
6911
Alexey Bataev438388c2017-11-22 18:34:02 +00006912 if (!CurContext->isDependentContext()) {
6913 // Finalize the clauses that need pre-built expressions for CodeGen.
6914 for (auto C : Clauses) {
6915 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6916 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6917 B.NumIterations, *this, CurScope,
6918 DSAStack))
6919 return StmtError();
6920 }
6921 }
6922
Kelvin Lic5609492016-07-15 04:39:07 +00006923 if (checkSimdlenSafelenSpecified(*this, Clauses))
6924 return StmtError();
6925
Kelvin Li787f3fc2016-07-06 04:45:38 +00006926 getCurFunction()->setHasBranchProtectedScope();
6927 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6928 NestedLoopCount, Clauses, AStmt, B);
6929}
6930
Kelvin Lia579b912016-07-14 02:54:56 +00006931StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6932 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6933 SourceLocation EndLoc,
6934 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6935 if (!AStmt)
6936 return StmtError();
6937
6938 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6939 // 1.2.2 OpenMP Language Terminology
6940 // Structured block - An executable statement with a single entry at the
6941 // top and a single exit at the bottom.
6942 // The point of exit cannot be a branch out of the structured block.
6943 // longjmp() and throw() must not violate the entry/exit criteria.
6944 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006945 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6946 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6947 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6948 // 1.2.2 OpenMP Language Terminology
6949 // Structured block - An executable statement with a single entry at the
6950 // top and a single exit at the bottom.
6951 // The point of exit cannot be a branch out of the structured block.
6952 // longjmp() and throw() must not violate the entry/exit criteria.
6953 CS->getCapturedDecl()->setNothrow();
6954 }
Kelvin Lia579b912016-07-14 02:54:56 +00006955
6956 OMPLoopDirective::HelperExprs B;
6957 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6958 // define the nested loops number.
6959 unsigned NestedLoopCount = CheckOpenMPLoop(
6960 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006961 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00006962 VarsWithImplicitDSA, B);
6963 if (NestedLoopCount == 0)
6964 return StmtError();
6965
6966 assert((CurContext->isDependentContext() || B.builtAll()) &&
6967 "omp target parallel for simd loop exprs were not built");
6968
6969 if (!CurContext->isDependentContext()) {
6970 // Finalize the clauses that need pre-built expressions for CodeGen.
6971 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006972 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006973 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6974 B.NumIterations, *this, CurScope,
6975 DSAStack))
6976 return StmtError();
6977 }
6978 }
Kelvin Lic5609492016-07-15 04:39:07 +00006979 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006980 return StmtError();
6981
6982 getCurFunction()->setHasBranchProtectedScope();
6983 return OMPTargetParallelForSimdDirective::Create(
6984 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6985}
6986
Kelvin Li986330c2016-07-20 22:57:10 +00006987StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6988 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6989 SourceLocation EndLoc,
6990 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6991 if (!AStmt)
6992 return StmtError();
6993
6994 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6995 // 1.2.2 OpenMP Language Terminology
6996 // Structured block - An executable statement with a single entry at the
6997 // top and a single exit at the bottom.
6998 // The point of exit cannot be a branch out of the structured block.
6999 // longjmp() and throw() must not violate the entry/exit criteria.
7000 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007001 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7002 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7003 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7004 // 1.2.2 OpenMP Language Terminology
7005 // Structured block - An executable statement with a single entry at the
7006 // top and a single exit at the bottom.
7007 // The point of exit cannot be a branch out of the structured block.
7008 // longjmp() and throw() must not violate the entry/exit criteria.
7009 CS->getCapturedDecl()->setNothrow();
7010 }
7011
Kelvin Li986330c2016-07-20 22:57:10 +00007012 OMPLoopDirective::HelperExprs B;
7013 // In presence of clause 'collapse' with number of loops, it will define the
7014 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007015 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007016 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007017 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007018 VarsWithImplicitDSA, B);
7019 if (NestedLoopCount == 0)
7020 return StmtError();
7021
7022 assert((CurContext->isDependentContext() || B.builtAll()) &&
7023 "omp target simd loop exprs were not built");
7024
7025 if (!CurContext->isDependentContext()) {
7026 // Finalize the clauses that need pre-built expressions for CodeGen.
7027 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007028 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007029 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7030 B.NumIterations, *this, CurScope,
7031 DSAStack))
7032 return StmtError();
7033 }
7034 }
7035
7036 if (checkSimdlenSafelenSpecified(*this, Clauses))
7037 return StmtError();
7038
7039 getCurFunction()->setHasBranchProtectedScope();
7040 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7041 NestedLoopCount, Clauses, AStmt, B);
7042}
7043
Kelvin Li02532872016-08-05 14:37:37 +00007044StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7045 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7046 SourceLocation EndLoc,
7047 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7048 if (!AStmt)
7049 return StmtError();
7050
7051 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7052 // 1.2.2 OpenMP Language Terminology
7053 // Structured block - An executable statement with a single entry at the
7054 // top and a single exit at the bottom.
7055 // The point of exit cannot be a branch out of the structured block.
7056 // longjmp() and throw() must not violate the entry/exit criteria.
7057 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007058 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7059 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7060 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7061 // 1.2.2 OpenMP Language Terminology
7062 // Structured block - An executable statement with a single entry at the
7063 // top and a single exit at the bottom.
7064 // The point of exit cannot be a branch out of the structured block.
7065 // longjmp() and throw() must not violate the entry/exit criteria.
7066 CS->getCapturedDecl()->setNothrow();
7067 }
Kelvin Li02532872016-08-05 14:37:37 +00007068
7069 OMPLoopDirective::HelperExprs B;
7070 // In presence of clause 'collapse' with number of loops, it will
7071 // define the nested loops number.
7072 unsigned NestedLoopCount =
7073 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007074 nullptr /*ordered not a clause on distribute*/, CS, *this,
7075 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007076 if (NestedLoopCount == 0)
7077 return StmtError();
7078
7079 assert((CurContext->isDependentContext() || B.builtAll()) &&
7080 "omp teams distribute loop exprs were not built");
7081
7082 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007083
7084 DSAStack->setParentTeamsRegionLoc(StartLoc);
7085
David Majnemer9d168222016-08-05 17:44:54 +00007086 return OMPTeamsDistributeDirective::Create(
7087 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007088}
7089
Kelvin Li4e325f72016-10-25 12:50:55 +00007090StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7091 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7092 SourceLocation EndLoc,
7093 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7094 if (!AStmt)
7095 return StmtError();
7096
7097 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7098 // 1.2.2 OpenMP Language Terminology
7099 // Structured block - An executable statement with a single entry at the
7100 // top and a single exit at the bottom.
7101 // The point of exit cannot be a branch out of the structured block.
7102 // longjmp() and throw() must not violate the entry/exit criteria.
7103 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007104 for (int ThisCaptureLevel =
7105 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7106 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7107 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7108 // 1.2.2 OpenMP Language Terminology
7109 // Structured block - An executable statement with a single entry at the
7110 // top and a single exit at the bottom.
7111 // The point of exit cannot be a branch out of the structured block.
7112 // longjmp() and throw() must not violate the entry/exit criteria.
7113 CS->getCapturedDecl()->setNothrow();
7114 }
7115
Kelvin Li4e325f72016-10-25 12:50:55 +00007116
7117 OMPLoopDirective::HelperExprs B;
7118 // In presence of clause 'collapse' with number of loops, it will
7119 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007120 unsigned NestedLoopCount = CheckOpenMPLoop(
7121 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007122 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007123 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007124
7125 if (NestedLoopCount == 0)
7126 return StmtError();
7127
7128 assert((CurContext->isDependentContext() || B.builtAll()) &&
7129 "omp teams distribute simd loop exprs were not built");
7130
7131 if (!CurContext->isDependentContext()) {
7132 // Finalize the clauses that need pre-built expressions for CodeGen.
7133 for (auto C : Clauses) {
7134 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7135 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7136 B.NumIterations, *this, CurScope,
7137 DSAStack))
7138 return StmtError();
7139 }
7140 }
7141
7142 if (checkSimdlenSafelenSpecified(*this, Clauses))
7143 return StmtError();
7144
7145 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007146
7147 DSAStack->setParentTeamsRegionLoc(StartLoc);
7148
Kelvin Li4e325f72016-10-25 12:50:55 +00007149 return OMPTeamsDistributeSimdDirective::Create(
7150 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7151}
7152
Kelvin Li579e41c2016-11-30 23:51:03 +00007153StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7154 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7155 SourceLocation EndLoc,
7156 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7157 if (!AStmt)
7158 return StmtError();
7159
7160 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7161 // 1.2.2 OpenMP Language Terminology
7162 // Structured block - An executable statement with a single entry at the
7163 // top and a single exit at the bottom.
7164 // The point of exit cannot be a branch out of the structured block.
7165 // longjmp() and throw() must not violate the entry/exit criteria.
7166 CS->getCapturedDecl()->setNothrow();
7167
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007168 for (int ThisCaptureLevel =
7169 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7170 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7171 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7172 // 1.2.2 OpenMP Language Terminology
7173 // Structured block - An executable statement with a single entry at the
7174 // top and a single exit at the bottom.
7175 // The point of exit cannot be a branch out of the structured block.
7176 // longjmp() and throw() must not violate the entry/exit criteria.
7177 CS->getCapturedDecl()->setNothrow();
7178 }
7179
Kelvin Li579e41c2016-11-30 23:51:03 +00007180 OMPLoopDirective::HelperExprs B;
7181 // In presence of clause 'collapse' with number of loops, it will
7182 // define the nested loops number.
7183 auto NestedLoopCount = CheckOpenMPLoop(
7184 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007185 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007186 VarsWithImplicitDSA, B);
7187
7188 if (NestedLoopCount == 0)
7189 return StmtError();
7190
7191 assert((CurContext->isDependentContext() || B.builtAll()) &&
7192 "omp for loop exprs were not built");
7193
7194 if (!CurContext->isDependentContext()) {
7195 // Finalize the clauses that need pre-built expressions for CodeGen.
7196 for (auto C : Clauses) {
7197 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7198 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7199 B.NumIterations, *this, CurScope,
7200 DSAStack))
7201 return StmtError();
7202 }
7203 }
7204
7205 if (checkSimdlenSafelenSpecified(*this, Clauses))
7206 return StmtError();
7207
7208 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007209
7210 DSAStack->setParentTeamsRegionLoc(StartLoc);
7211
Kelvin Li579e41c2016-11-30 23:51:03 +00007212 return OMPTeamsDistributeParallelForSimdDirective::Create(
7213 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7214}
7215
Kelvin Li7ade93f2016-12-09 03:24:30 +00007216StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7217 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7218 SourceLocation EndLoc,
7219 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7220 if (!AStmt)
7221 return StmtError();
7222
7223 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7224 // 1.2.2 OpenMP Language Terminology
7225 // Structured block - An executable statement with a single entry at the
7226 // top and a single exit at the bottom.
7227 // The point of exit cannot be a branch out of the structured block.
7228 // longjmp() and throw() must not violate the entry/exit criteria.
7229 CS->getCapturedDecl()->setNothrow();
7230
Carlo Bertolli62fae152017-11-20 20:46:39 +00007231 for (int ThisCaptureLevel =
7232 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7233 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7234 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7235 // 1.2.2 OpenMP Language Terminology
7236 // Structured block - An executable statement with a single entry at the
7237 // top and a single exit at the bottom.
7238 // The point of exit cannot be a branch out of the structured block.
7239 // longjmp() and throw() must not violate the entry/exit criteria.
7240 CS->getCapturedDecl()->setNothrow();
7241 }
7242
Kelvin Li7ade93f2016-12-09 03:24:30 +00007243 OMPLoopDirective::HelperExprs B;
7244 // In presence of clause 'collapse' with number of loops, it will
7245 // define the nested loops number.
7246 unsigned NestedLoopCount = CheckOpenMPLoop(
7247 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007248 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007249 VarsWithImplicitDSA, B);
7250
7251 if (NestedLoopCount == 0)
7252 return StmtError();
7253
7254 assert((CurContext->isDependentContext() || B.builtAll()) &&
7255 "omp for loop exprs were not built");
7256
Kelvin Li7ade93f2016-12-09 03:24:30 +00007257 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007258
7259 DSAStack->setParentTeamsRegionLoc(StartLoc);
7260
Kelvin Li7ade93f2016-12-09 03:24:30 +00007261 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007262 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7263 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007264}
7265
Kelvin Libf594a52016-12-17 05:48:59 +00007266StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7267 Stmt *AStmt,
7268 SourceLocation StartLoc,
7269 SourceLocation EndLoc) {
7270 if (!AStmt)
7271 return StmtError();
7272
7273 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7274 // 1.2.2 OpenMP Language Terminology
7275 // Structured block - An executable statement with a single entry at the
7276 // top and a single exit at the bottom.
7277 // The point of exit cannot be a branch out of the structured block.
7278 // longjmp() and throw() must not violate the entry/exit criteria.
7279 CS->getCapturedDecl()->setNothrow();
7280
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007281 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7282 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7283 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7284 // 1.2.2 OpenMP Language Terminology
7285 // Structured block - An executable statement with a single entry at the
7286 // top and a single exit at the bottom.
7287 // The point of exit cannot be a branch out of the structured block.
7288 // longjmp() and throw() must not violate the entry/exit criteria.
7289 CS->getCapturedDecl()->setNothrow();
7290 }
Kelvin Libf594a52016-12-17 05:48:59 +00007291 getCurFunction()->setHasBranchProtectedScope();
7292
7293 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7294 AStmt);
7295}
7296
Kelvin Li83c451e2016-12-25 04:52:54 +00007297StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7298 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7299 SourceLocation EndLoc,
7300 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7301 if (!AStmt)
7302 return StmtError();
7303
7304 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7305 // 1.2.2 OpenMP Language Terminology
7306 // Structured block - An executable statement with a single entry at the
7307 // top and a single exit at the bottom.
7308 // The point of exit cannot be a branch out of the structured block.
7309 // longjmp() and throw() must not violate the entry/exit criteria.
7310 CS->getCapturedDecl()->setNothrow();
7311
7312 OMPLoopDirective::HelperExprs B;
7313 // In presence of clause 'collapse' with number of loops, it will
7314 // define the nested loops number.
7315 auto NestedLoopCount = CheckOpenMPLoop(
7316 OMPD_target_teams_distribute,
7317 getCollapseNumberExpr(Clauses),
7318 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7319 VarsWithImplicitDSA, B);
7320 if (NestedLoopCount == 0)
7321 return StmtError();
7322
7323 assert((CurContext->isDependentContext() || B.builtAll()) &&
7324 "omp target teams distribute loop exprs were not built");
7325
7326 getCurFunction()->setHasBranchProtectedScope();
7327 return OMPTargetTeamsDistributeDirective::Create(
7328 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7329}
7330
Kelvin Li80e8f562016-12-29 22:16:30 +00007331StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7332 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7333 SourceLocation EndLoc,
7334 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7335 if (!AStmt)
7336 return StmtError();
7337
7338 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7339 // 1.2.2 OpenMP Language Terminology
7340 // Structured block - An executable statement with a single entry at the
7341 // top and a single exit at the bottom.
7342 // The point of exit cannot be a branch out of the structured block.
7343 // longjmp() and throw() must not violate the entry/exit criteria.
7344 CS->getCapturedDecl()->setNothrow();
7345
7346 OMPLoopDirective::HelperExprs B;
7347 // In presence of clause 'collapse' with number of loops, it will
7348 // define the nested loops number.
7349 auto NestedLoopCount = CheckOpenMPLoop(
7350 OMPD_target_teams_distribute_parallel_for,
7351 getCollapseNumberExpr(Clauses),
7352 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7353 VarsWithImplicitDSA, B);
7354 if (NestedLoopCount == 0)
7355 return StmtError();
7356
7357 assert((CurContext->isDependentContext() || B.builtAll()) &&
7358 "omp target teams distribute parallel for loop exprs were not built");
7359
Kelvin Li80e8f562016-12-29 22:16:30 +00007360 getCurFunction()->setHasBranchProtectedScope();
7361 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007362 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7363 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007364}
7365
Kelvin Li1851df52017-01-03 05:23:48 +00007366StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7367 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7368 SourceLocation EndLoc,
7369 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7370 if (!AStmt)
7371 return StmtError();
7372
7373 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7374 // 1.2.2 OpenMP Language Terminology
7375 // Structured block - An executable statement with a single entry at the
7376 // top and a single exit at the bottom.
7377 // The point of exit cannot be a branch out of the structured block.
7378 // longjmp() and throw() must not violate the entry/exit criteria.
7379 CS->getCapturedDecl()->setNothrow();
7380
7381 OMPLoopDirective::HelperExprs B;
7382 // In presence of clause 'collapse' with number of loops, it will
7383 // define the nested loops number.
7384 auto NestedLoopCount = CheckOpenMPLoop(
7385 OMPD_target_teams_distribute_parallel_for_simd,
7386 getCollapseNumberExpr(Clauses),
7387 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7388 VarsWithImplicitDSA, B);
7389 if (NestedLoopCount == 0)
7390 return StmtError();
7391
7392 assert((CurContext->isDependentContext() || B.builtAll()) &&
7393 "omp target teams distribute parallel for simd loop exprs were not "
7394 "built");
7395
7396 if (!CurContext->isDependentContext()) {
7397 // Finalize the clauses that need pre-built expressions for CodeGen.
7398 for (auto C : Clauses) {
7399 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7400 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7401 B.NumIterations, *this, CurScope,
7402 DSAStack))
7403 return StmtError();
7404 }
7405 }
7406
Alexey Bataev438388c2017-11-22 18:34:02 +00007407 if (checkSimdlenSafelenSpecified(*this, Clauses))
7408 return StmtError();
7409
Kelvin Li1851df52017-01-03 05:23:48 +00007410 getCurFunction()->setHasBranchProtectedScope();
7411 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7412 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7413}
7414
Kelvin Lida681182017-01-10 18:08:18 +00007415StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7416 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7417 SourceLocation EndLoc,
7418 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7419 if (!AStmt)
7420 return StmtError();
7421
7422 auto *CS = cast<CapturedStmt>(AStmt);
7423 // 1.2.2 OpenMP Language Terminology
7424 // Structured block - An executable statement with a single entry at the
7425 // top and a single exit at the bottom.
7426 // The point of exit cannot be a branch out of the structured block.
7427 // longjmp() and throw() must not violate the entry/exit criteria.
7428 CS->getCapturedDecl()->setNothrow();
7429
7430 OMPLoopDirective::HelperExprs B;
7431 // In presence of clause 'collapse' with number of loops, it will
7432 // define the nested loops number.
7433 auto NestedLoopCount = CheckOpenMPLoop(
7434 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7435 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7436 VarsWithImplicitDSA, B);
7437 if (NestedLoopCount == 0)
7438 return StmtError();
7439
7440 assert((CurContext->isDependentContext() || B.builtAll()) &&
7441 "omp target teams distribute simd loop exprs were not built");
7442
Alexey Bataev438388c2017-11-22 18:34:02 +00007443 if (!CurContext->isDependentContext()) {
7444 // Finalize the clauses that need pre-built expressions for CodeGen.
7445 for (auto C : Clauses) {
7446 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7447 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7448 B.NumIterations, *this, CurScope,
7449 DSAStack))
7450 return StmtError();
7451 }
7452 }
7453
7454 if (checkSimdlenSafelenSpecified(*this, Clauses))
7455 return StmtError();
7456
Kelvin Lida681182017-01-10 18:08:18 +00007457 getCurFunction()->setHasBranchProtectedScope();
7458 return OMPTargetTeamsDistributeSimdDirective::Create(
7459 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7460}
7461
Alexey Bataeved09d242014-05-28 05:53:51 +00007462OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007463 SourceLocation StartLoc,
7464 SourceLocation LParenLoc,
7465 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007466 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007467 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007468 case OMPC_final:
7469 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7470 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007471 case OMPC_num_threads:
7472 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7473 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007474 case OMPC_safelen:
7475 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7476 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007477 case OMPC_simdlen:
7478 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7479 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007480 case OMPC_collapse:
7481 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7482 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007483 case OMPC_ordered:
7484 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7485 break;
Michael Wonge710d542015-08-07 16:16:36 +00007486 case OMPC_device:
7487 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7488 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007489 case OMPC_num_teams:
7490 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7491 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007492 case OMPC_thread_limit:
7493 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7494 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007495 case OMPC_priority:
7496 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7497 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007498 case OMPC_grainsize:
7499 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7500 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007501 case OMPC_num_tasks:
7502 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7503 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007504 case OMPC_hint:
7505 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7506 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007507 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007508 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007509 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007510 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007511 case OMPC_private:
7512 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007513 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007514 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007515 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007516 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007517 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007518 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007519 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007520 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007521 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007522 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007523 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007524 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007525 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007526 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007527 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007528 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007529 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007530 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007531 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007532 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007533 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007534 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007535 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007536 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007537 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007538 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007539 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007540 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007541 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007542 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007543 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007544 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007545 llvm_unreachable("Clause is not allowed.");
7546 }
7547 return Res;
7548}
7549
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007550// An OpenMP directive such as 'target parallel' has two captured regions:
7551// for the 'target' and 'parallel' respectively. This function returns
7552// the region in which to capture expressions associated with a clause.
7553// A return value of OMPD_unknown signifies that the expression should not
7554// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007555static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7556 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7557 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007558 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007559 switch (CKind) {
7560 case OMPC_if:
7561 switch (DKind) {
7562 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007563 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007564 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007565 case OMPD_target_teams_distribute_parallel_for:
7566 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007567 // If this clause applies to the nested 'parallel' region, capture within
7568 // the 'target' region, otherwise do not capture.
7569 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7570 CaptureRegion = OMPD_target;
7571 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007572 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007573 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007574 CaptureRegion = OMPD_teams;
7575 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007576 case OMPD_cancel:
7577 case OMPD_parallel:
7578 case OMPD_parallel_sections:
7579 case OMPD_parallel_for:
7580 case OMPD_parallel_for_simd:
7581 case OMPD_target:
7582 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007583 case OMPD_target_teams:
7584 case OMPD_target_teams_distribute:
7585 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007586 case OMPD_distribute_parallel_for:
7587 case OMPD_distribute_parallel_for_simd:
7588 case OMPD_task:
7589 case OMPD_taskloop:
7590 case OMPD_taskloop_simd:
7591 case OMPD_target_data:
7592 case OMPD_target_enter_data:
7593 case OMPD_target_exit_data:
7594 case OMPD_target_update:
7595 // Do not capture if-clause expressions.
7596 break;
7597 case OMPD_threadprivate:
7598 case OMPD_taskyield:
7599 case OMPD_barrier:
7600 case OMPD_taskwait:
7601 case OMPD_cancellation_point:
7602 case OMPD_flush:
7603 case OMPD_declare_reduction:
7604 case OMPD_declare_simd:
7605 case OMPD_declare_target:
7606 case OMPD_end_declare_target:
7607 case OMPD_teams:
7608 case OMPD_simd:
7609 case OMPD_for:
7610 case OMPD_for_simd:
7611 case OMPD_sections:
7612 case OMPD_section:
7613 case OMPD_single:
7614 case OMPD_master:
7615 case OMPD_critical:
7616 case OMPD_taskgroup:
7617 case OMPD_distribute:
7618 case OMPD_ordered:
7619 case OMPD_atomic:
7620 case OMPD_distribute_simd:
7621 case OMPD_teams_distribute:
7622 case OMPD_teams_distribute_simd:
7623 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7624 case OMPD_unknown:
7625 llvm_unreachable("Unknown OpenMP directive");
7626 }
7627 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007628 case OMPC_num_threads:
7629 switch (DKind) {
7630 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007631 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007632 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007633 case OMPD_target_teams_distribute_parallel_for:
7634 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007635 CaptureRegion = OMPD_target;
7636 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007637 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007638 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007639 CaptureRegion = OMPD_teams;
7640 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007641 case OMPD_parallel:
7642 case OMPD_parallel_sections:
7643 case OMPD_parallel_for:
7644 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007645 case OMPD_distribute_parallel_for:
7646 case OMPD_distribute_parallel_for_simd:
7647 // Do not capture num_threads-clause expressions.
7648 break;
7649 case OMPD_target_data:
7650 case OMPD_target_enter_data:
7651 case OMPD_target_exit_data:
7652 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007653 case OMPD_target:
7654 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007655 case OMPD_target_teams:
7656 case OMPD_target_teams_distribute:
7657 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007658 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007659 case OMPD_task:
7660 case OMPD_taskloop:
7661 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007662 case OMPD_threadprivate:
7663 case OMPD_taskyield:
7664 case OMPD_barrier:
7665 case OMPD_taskwait:
7666 case OMPD_cancellation_point:
7667 case OMPD_flush:
7668 case OMPD_declare_reduction:
7669 case OMPD_declare_simd:
7670 case OMPD_declare_target:
7671 case OMPD_end_declare_target:
7672 case OMPD_teams:
7673 case OMPD_simd:
7674 case OMPD_for:
7675 case OMPD_for_simd:
7676 case OMPD_sections:
7677 case OMPD_section:
7678 case OMPD_single:
7679 case OMPD_master:
7680 case OMPD_critical:
7681 case OMPD_taskgroup:
7682 case OMPD_distribute:
7683 case OMPD_ordered:
7684 case OMPD_atomic:
7685 case OMPD_distribute_simd:
7686 case OMPD_teams_distribute:
7687 case OMPD_teams_distribute_simd:
7688 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7689 case OMPD_unknown:
7690 llvm_unreachable("Unknown OpenMP directive");
7691 }
7692 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007693 case OMPC_num_teams:
7694 switch (DKind) {
7695 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007696 case OMPD_target_teams_distribute:
7697 case OMPD_target_teams_distribute_simd:
7698 case OMPD_target_teams_distribute_parallel_for:
7699 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007700 CaptureRegion = OMPD_target;
7701 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007702 case OMPD_teams_distribute_parallel_for:
7703 case OMPD_teams_distribute_parallel_for_simd:
7704 case OMPD_teams:
7705 case OMPD_teams_distribute:
7706 case OMPD_teams_distribute_simd:
7707 // Do not capture num_teams-clause expressions.
7708 break;
7709 case OMPD_distribute_parallel_for:
7710 case OMPD_distribute_parallel_for_simd:
7711 case OMPD_task:
7712 case OMPD_taskloop:
7713 case OMPD_taskloop_simd:
7714 case OMPD_target_data:
7715 case OMPD_target_enter_data:
7716 case OMPD_target_exit_data:
7717 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007718 case OMPD_cancel:
7719 case OMPD_parallel:
7720 case OMPD_parallel_sections:
7721 case OMPD_parallel_for:
7722 case OMPD_parallel_for_simd:
7723 case OMPD_target:
7724 case OMPD_target_simd:
7725 case OMPD_target_parallel:
7726 case OMPD_target_parallel_for:
7727 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007728 case OMPD_threadprivate:
7729 case OMPD_taskyield:
7730 case OMPD_barrier:
7731 case OMPD_taskwait:
7732 case OMPD_cancellation_point:
7733 case OMPD_flush:
7734 case OMPD_declare_reduction:
7735 case OMPD_declare_simd:
7736 case OMPD_declare_target:
7737 case OMPD_end_declare_target:
7738 case OMPD_simd:
7739 case OMPD_for:
7740 case OMPD_for_simd:
7741 case OMPD_sections:
7742 case OMPD_section:
7743 case OMPD_single:
7744 case OMPD_master:
7745 case OMPD_critical:
7746 case OMPD_taskgroup:
7747 case OMPD_distribute:
7748 case OMPD_ordered:
7749 case OMPD_atomic:
7750 case OMPD_distribute_simd:
7751 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7752 case OMPD_unknown:
7753 llvm_unreachable("Unknown OpenMP directive");
7754 }
7755 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007756 case OMPC_thread_limit:
7757 switch (DKind) {
7758 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007759 case OMPD_target_teams_distribute:
7760 case OMPD_target_teams_distribute_simd:
7761 case OMPD_target_teams_distribute_parallel_for:
7762 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007763 CaptureRegion = OMPD_target;
7764 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007765 case OMPD_teams_distribute_parallel_for:
7766 case OMPD_teams_distribute_parallel_for_simd:
7767 case OMPD_teams:
7768 case OMPD_teams_distribute:
7769 case OMPD_teams_distribute_simd:
7770 // Do not capture thread_limit-clause expressions.
7771 break;
7772 case OMPD_distribute_parallel_for:
7773 case OMPD_distribute_parallel_for_simd:
7774 case OMPD_task:
7775 case OMPD_taskloop:
7776 case OMPD_taskloop_simd:
7777 case OMPD_target_data:
7778 case OMPD_target_enter_data:
7779 case OMPD_target_exit_data:
7780 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007781 case OMPD_cancel:
7782 case OMPD_parallel:
7783 case OMPD_parallel_sections:
7784 case OMPD_parallel_for:
7785 case OMPD_parallel_for_simd:
7786 case OMPD_target:
7787 case OMPD_target_simd:
7788 case OMPD_target_parallel:
7789 case OMPD_target_parallel_for:
7790 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007791 case OMPD_threadprivate:
7792 case OMPD_taskyield:
7793 case OMPD_barrier:
7794 case OMPD_taskwait:
7795 case OMPD_cancellation_point:
7796 case OMPD_flush:
7797 case OMPD_declare_reduction:
7798 case OMPD_declare_simd:
7799 case OMPD_declare_target:
7800 case OMPD_end_declare_target:
7801 case OMPD_simd:
7802 case OMPD_for:
7803 case OMPD_for_simd:
7804 case OMPD_sections:
7805 case OMPD_section:
7806 case OMPD_single:
7807 case OMPD_master:
7808 case OMPD_critical:
7809 case OMPD_taskgroup:
7810 case OMPD_distribute:
7811 case OMPD_ordered:
7812 case OMPD_atomic:
7813 case OMPD_distribute_simd:
7814 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7815 case OMPD_unknown:
7816 llvm_unreachable("Unknown OpenMP directive");
7817 }
7818 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007819 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007820 switch (DKind) {
7821 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007822 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007823 case OMPD_target_teams_distribute_parallel_for:
7824 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007825 CaptureRegion = OMPD_target;
7826 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007827 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007828 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007829 CaptureRegion = OMPD_teams;
7830 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007831 case OMPD_parallel_for:
7832 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00007833 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00007834 case OMPD_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00007835 CaptureRegion = OMPD_parallel;
7836 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007837 case OMPD_for:
7838 case OMPD_for_simd:
7839 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007840 break;
7841 case OMPD_task:
7842 case OMPD_taskloop:
7843 case OMPD_taskloop_simd:
7844 case OMPD_target_data:
7845 case OMPD_target_enter_data:
7846 case OMPD_target_exit_data:
7847 case OMPD_target_update:
7848 case OMPD_teams:
7849 case OMPD_teams_distribute:
7850 case OMPD_teams_distribute_simd:
7851 case OMPD_target_teams_distribute:
7852 case OMPD_target_teams_distribute_simd:
7853 case OMPD_target:
7854 case OMPD_target_simd:
7855 case OMPD_target_parallel:
7856 case OMPD_cancel:
7857 case OMPD_parallel:
7858 case OMPD_parallel_sections:
7859 case OMPD_threadprivate:
7860 case OMPD_taskyield:
7861 case OMPD_barrier:
7862 case OMPD_taskwait:
7863 case OMPD_cancellation_point:
7864 case OMPD_flush:
7865 case OMPD_declare_reduction:
7866 case OMPD_declare_simd:
7867 case OMPD_declare_target:
7868 case OMPD_end_declare_target:
7869 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007870 case OMPD_sections:
7871 case OMPD_section:
7872 case OMPD_single:
7873 case OMPD_master:
7874 case OMPD_critical:
7875 case OMPD_taskgroup:
7876 case OMPD_distribute:
7877 case OMPD_ordered:
7878 case OMPD_atomic:
7879 case OMPD_distribute_simd:
7880 case OMPD_target_teams:
7881 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7882 case OMPD_unknown:
7883 llvm_unreachable("Unknown OpenMP directive");
7884 }
7885 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007886 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007887 switch (DKind) {
7888 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007889 case OMPD_teams_distribute_parallel_for_simd:
7890 case OMPD_teams_distribute:
7891 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007892 CaptureRegion = OMPD_teams;
7893 break;
7894 case OMPD_target_teams_distribute_parallel_for:
7895 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007896 case OMPD_target_teams_distribute:
7897 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007898 CaptureRegion = OMPD_target;
7899 break;
7900 case OMPD_distribute_parallel_for:
7901 case OMPD_distribute_parallel_for_simd:
7902 CaptureRegion = OMPD_parallel;
7903 break;
7904 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007905 case OMPD_distribute_simd:
7906 // Do not capture thread_limit-clause expressions.
7907 break;
7908 case OMPD_parallel_for:
7909 case OMPD_parallel_for_simd:
7910 case OMPD_target_parallel_for_simd:
7911 case OMPD_target_parallel_for:
7912 case OMPD_task:
7913 case OMPD_taskloop:
7914 case OMPD_taskloop_simd:
7915 case OMPD_target_data:
7916 case OMPD_target_enter_data:
7917 case OMPD_target_exit_data:
7918 case OMPD_target_update:
7919 case OMPD_teams:
7920 case OMPD_target:
7921 case OMPD_target_simd:
7922 case OMPD_target_parallel:
7923 case OMPD_cancel:
7924 case OMPD_parallel:
7925 case OMPD_parallel_sections:
7926 case OMPD_threadprivate:
7927 case OMPD_taskyield:
7928 case OMPD_barrier:
7929 case OMPD_taskwait:
7930 case OMPD_cancellation_point:
7931 case OMPD_flush:
7932 case OMPD_declare_reduction:
7933 case OMPD_declare_simd:
7934 case OMPD_declare_target:
7935 case OMPD_end_declare_target:
7936 case OMPD_simd:
7937 case OMPD_for:
7938 case OMPD_for_simd:
7939 case OMPD_sections:
7940 case OMPD_section:
7941 case OMPD_single:
7942 case OMPD_master:
7943 case OMPD_critical:
7944 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007945 case OMPD_ordered:
7946 case OMPD_atomic:
7947 case OMPD_target_teams:
7948 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7949 case OMPD_unknown:
7950 llvm_unreachable("Unknown OpenMP directive");
7951 }
7952 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007953 case OMPC_device:
7954 switch (DKind) {
7955 case OMPD_target_teams:
7956 case OMPD_target_teams_distribute:
7957 case OMPD_target_teams_distribute_simd:
7958 case OMPD_target_teams_distribute_parallel_for:
7959 case OMPD_target_teams_distribute_parallel_for_simd:
7960 case OMPD_target_data:
7961 case OMPD_target_enter_data:
7962 case OMPD_target_exit_data:
7963 case OMPD_target_update:
7964 case OMPD_target:
7965 case OMPD_target_simd:
7966 case OMPD_target_parallel:
7967 case OMPD_target_parallel_for:
7968 case OMPD_target_parallel_for_simd:
7969 // Do not capture device-clause expressions.
7970 break;
7971 case OMPD_teams_distribute_parallel_for:
7972 case OMPD_teams_distribute_parallel_for_simd:
7973 case OMPD_teams:
7974 case OMPD_teams_distribute:
7975 case OMPD_teams_distribute_simd:
7976 case OMPD_distribute_parallel_for:
7977 case OMPD_distribute_parallel_for_simd:
7978 case OMPD_task:
7979 case OMPD_taskloop:
7980 case OMPD_taskloop_simd:
7981 case OMPD_cancel:
7982 case OMPD_parallel:
7983 case OMPD_parallel_sections:
7984 case OMPD_parallel_for:
7985 case OMPD_parallel_for_simd:
7986 case OMPD_threadprivate:
7987 case OMPD_taskyield:
7988 case OMPD_barrier:
7989 case OMPD_taskwait:
7990 case OMPD_cancellation_point:
7991 case OMPD_flush:
7992 case OMPD_declare_reduction:
7993 case OMPD_declare_simd:
7994 case OMPD_declare_target:
7995 case OMPD_end_declare_target:
7996 case OMPD_simd:
7997 case OMPD_for:
7998 case OMPD_for_simd:
7999 case OMPD_sections:
8000 case OMPD_section:
8001 case OMPD_single:
8002 case OMPD_master:
8003 case OMPD_critical:
8004 case OMPD_taskgroup:
8005 case OMPD_distribute:
8006 case OMPD_ordered:
8007 case OMPD_atomic:
8008 case OMPD_distribute_simd:
8009 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8010 case OMPD_unknown:
8011 llvm_unreachable("Unknown OpenMP directive");
8012 }
8013 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008014 case OMPC_firstprivate:
8015 case OMPC_lastprivate:
8016 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008017 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008018 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008019 case OMPC_linear:
8020 case OMPC_default:
8021 case OMPC_proc_bind:
8022 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008023 case OMPC_safelen:
8024 case OMPC_simdlen:
8025 case OMPC_collapse:
8026 case OMPC_private:
8027 case OMPC_shared:
8028 case OMPC_aligned:
8029 case OMPC_copyin:
8030 case OMPC_copyprivate:
8031 case OMPC_ordered:
8032 case OMPC_nowait:
8033 case OMPC_untied:
8034 case OMPC_mergeable:
8035 case OMPC_threadprivate:
8036 case OMPC_flush:
8037 case OMPC_read:
8038 case OMPC_write:
8039 case OMPC_update:
8040 case OMPC_capture:
8041 case OMPC_seq_cst:
8042 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008043 case OMPC_threads:
8044 case OMPC_simd:
8045 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008046 case OMPC_priority:
8047 case OMPC_grainsize:
8048 case OMPC_nogroup:
8049 case OMPC_num_tasks:
8050 case OMPC_hint:
8051 case OMPC_defaultmap:
8052 case OMPC_unknown:
8053 case OMPC_uniform:
8054 case OMPC_to:
8055 case OMPC_from:
8056 case OMPC_use_device_ptr:
8057 case OMPC_is_device_ptr:
8058 llvm_unreachable("Unexpected OpenMP clause.");
8059 }
8060 return CaptureRegion;
8061}
8062
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008063OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8064 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008065 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008066 SourceLocation NameModifierLoc,
8067 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008068 SourceLocation EndLoc) {
8069 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008070 Stmt *HelperValStmt = nullptr;
8071 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008072 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8073 !Condition->isInstantiationDependent() &&
8074 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008075 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008076 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008077 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008078
Richard Smith03a4aa32016-06-23 19:02:52 +00008079 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008080
8081 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8082 CaptureRegion =
8083 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008084 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008085 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8086 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8087 HelperValStmt = buildPreInits(Context, Captures);
8088 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008089 }
8090
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008091 return new (Context)
8092 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8093 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008094}
8095
Alexey Bataev3778b602014-07-17 07:32:53 +00008096OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8097 SourceLocation StartLoc,
8098 SourceLocation LParenLoc,
8099 SourceLocation EndLoc) {
8100 Expr *ValExpr = Condition;
8101 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8102 !Condition->isInstantiationDependent() &&
8103 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008104 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008105 if (Val.isInvalid())
8106 return nullptr;
8107
Richard Smith03a4aa32016-06-23 19:02:52 +00008108 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008109 }
8110
8111 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8112}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008113ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8114 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008115 if (!Op)
8116 return ExprError();
8117
8118 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8119 public:
8120 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008121 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008122 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8123 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008124 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8125 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008126 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8127 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008128 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8129 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008130 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8131 QualType T,
8132 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008133 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8134 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008135 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8136 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008137 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008138 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008139 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008140 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8141 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008142 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8143 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008144 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8145 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008146 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008147 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008148 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008149 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8150 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008151 llvm_unreachable("conversion functions are permitted");
8152 }
8153 } ConvertDiagnoser;
8154 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8155}
8156
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008157static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008158 OpenMPClauseKind CKind,
8159 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008160 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8161 !ValExpr->isInstantiationDependent()) {
8162 SourceLocation Loc = ValExpr->getExprLoc();
8163 ExprResult Value =
8164 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8165 if (Value.isInvalid())
8166 return false;
8167
8168 ValExpr = Value.get();
8169 // The expression must evaluate to a non-negative integer value.
8170 llvm::APSInt Result;
8171 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008172 Result.isSigned() &&
8173 !((!StrictlyPositive && Result.isNonNegative()) ||
8174 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008175 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008176 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8177 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008178 return false;
8179 }
8180 }
8181 return true;
8182}
8183
Alexey Bataev568a8332014-03-06 06:15:19 +00008184OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8185 SourceLocation StartLoc,
8186 SourceLocation LParenLoc,
8187 SourceLocation EndLoc) {
8188 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008189 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008190
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008191 // OpenMP [2.5, Restrictions]
8192 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008193 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8194 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008195 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008196
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008197 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008198 OpenMPDirectiveKind CaptureRegion =
8199 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8200 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008201 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8202 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8203 HelperValStmt = buildPreInits(Context, Captures);
8204 }
8205
8206 return new (Context) OMPNumThreadsClause(
8207 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008208}
8209
Alexey Bataev62c87d22014-03-21 04:51:18 +00008210ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008211 OpenMPClauseKind CKind,
8212 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008213 if (!E)
8214 return ExprError();
8215 if (E->isValueDependent() || E->isTypeDependent() ||
8216 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008217 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008218 llvm::APSInt Result;
8219 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8220 if (ICE.isInvalid())
8221 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008222 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8223 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008224 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008225 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8226 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008227 return ExprError();
8228 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008229 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8230 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8231 << E->getSourceRange();
8232 return ExprError();
8233 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008234 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8235 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008236 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008237 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008238 return ICE;
8239}
8240
8241OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8242 SourceLocation LParenLoc,
8243 SourceLocation EndLoc) {
8244 // OpenMP [2.8.1, simd construct, Description]
8245 // The parameter of the safelen clause must be a constant
8246 // positive integer expression.
8247 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8248 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008249 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008250 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008251 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008252}
8253
Alexey Bataev66b15b52015-08-21 11:14:16 +00008254OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8255 SourceLocation LParenLoc,
8256 SourceLocation EndLoc) {
8257 // OpenMP [2.8.1, simd construct, Description]
8258 // The parameter of the simdlen clause must be a constant
8259 // positive integer expression.
8260 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8261 if (Simdlen.isInvalid())
8262 return nullptr;
8263 return new (Context)
8264 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8265}
8266
Alexander Musman64d33f12014-06-04 07:53:32 +00008267OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8268 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008269 SourceLocation LParenLoc,
8270 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008271 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008272 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008273 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008274 // The parameter of the collapse clause must be a constant
8275 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008276 ExprResult NumForLoopsResult =
8277 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8278 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008279 return nullptr;
8280 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008281 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008282}
8283
Alexey Bataev10e775f2015-07-30 11:36:16 +00008284OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8285 SourceLocation EndLoc,
8286 SourceLocation LParenLoc,
8287 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008288 // OpenMP [2.7.1, loop construct, Description]
8289 // OpenMP [2.8.1, simd construct, Description]
8290 // OpenMP [2.9.6, distribute construct, Description]
8291 // The parameter of the ordered clause must be a constant
8292 // positive integer expression if any.
8293 if (NumForLoops && LParenLoc.isValid()) {
8294 ExprResult NumForLoopsResult =
8295 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8296 if (NumForLoopsResult.isInvalid())
8297 return nullptr;
8298 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008299 } else
8300 NumForLoops = nullptr;
8301 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008302 return new (Context)
8303 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8304}
8305
Alexey Bataeved09d242014-05-28 05:53:51 +00008306OMPClause *Sema::ActOnOpenMPSimpleClause(
8307 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8308 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008309 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008310 switch (Kind) {
8311 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008312 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008313 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8314 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008315 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008316 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008317 Res = ActOnOpenMPProcBindClause(
8318 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8319 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008320 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008321 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008322 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008323 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008324 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008325 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008326 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008327 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008328 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008329 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008330 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008331 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008332 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008333 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008334 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008335 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008336 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008337 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008338 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008339 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008340 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008341 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008342 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008343 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008344 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008345 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008346 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008347 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008348 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008349 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008350 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008351 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008352 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008353 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008354 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008355 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008356 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008357 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008358 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008359 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008360 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008361 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008362 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008363 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008364 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008365 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008366 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008367 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008368 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008369 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008370 llvm_unreachable("Clause is not allowed.");
8371 }
8372 return Res;
8373}
8374
Alexey Bataev6402bca2015-12-28 07:25:51 +00008375static std::string
8376getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8377 ArrayRef<unsigned> Exclude = llvm::None) {
8378 std::string Values;
8379 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8380 unsigned Skipped = Exclude.size();
8381 auto S = Exclude.begin(), E = Exclude.end();
8382 for (unsigned i = First; i < Last; ++i) {
8383 if (std::find(S, E, i) != E) {
8384 --Skipped;
8385 continue;
8386 }
8387 Values += "'";
8388 Values += getOpenMPSimpleClauseTypeName(K, i);
8389 Values += "'";
8390 if (i == Bound - Skipped)
8391 Values += " or ";
8392 else if (i != Bound + 1 - Skipped)
8393 Values += ", ";
8394 }
8395 return Values;
8396}
8397
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008398OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8399 SourceLocation KindKwLoc,
8400 SourceLocation StartLoc,
8401 SourceLocation LParenLoc,
8402 SourceLocation EndLoc) {
8403 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008404 static_assert(OMPC_DEFAULT_unknown > 0,
8405 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008406 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008407 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8408 /*Last=*/OMPC_DEFAULT_unknown)
8409 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008410 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008411 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008412 switch (Kind) {
8413 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008414 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008415 break;
8416 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008417 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008418 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008419 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008420 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008421 break;
8422 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008423 return new (Context)
8424 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008425}
8426
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008427OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8428 SourceLocation KindKwLoc,
8429 SourceLocation StartLoc,
8430 SourceLocation LParenLoc,
8431 SourceLocation EndLoc) {
8432 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008433 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008434 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8435 /*Last=*/OMPC_PROC_BIND_unknown)
8436 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008437 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008438 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008439 return new (Context)
8440 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008441}
8442
Alexey Bataev56dafe82014-06-20 07:16:17 +00008443OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008444 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008445 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008446 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008447 SourceLocation EndLoc) {
8448 OMPClause *Res = nullptr;
8449 switch (Kind) {
8450 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008451 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8452 assert(Argument.size() == NumberOfElements &&
8453 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008454 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008455 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8456 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8457 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8458 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8459 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008460 break;
8461 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008462 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8463 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8464 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8465 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008466 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008467 case OMPC_dist_schedule:
8468 Res = ActOnOpenMPDistScheduleClause(
8469 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8470 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8471 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008472 case OMPC_defaultmap:
8473 enum { Modifier, DefaultmapKind };
8474 Res = ActOnOpenMPDefaultmapClause(
8475 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8476 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008477 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8478 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008479 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008480 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008481 case OMPC_num_threads:
8482 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008483 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008484 case OMPC_collapse:
8485 case OMPC_default:
8486 case OMPC_proc_bind:
8487 case OMPC_private:
8488 case OMPC_firstprivate:
8489 case OMPC_lastprivate:
8490 case OMPC_shared:
8491 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008492 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008493 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008494 case OMPC_linear:
8495 case OMPC_aligned:
8496 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008497 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008498 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008499 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008500 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008501 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008502 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008503 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008504 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008505 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008506 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008507 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008508 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008509 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008510 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008511 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008512 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008513 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008514 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008515 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008516 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008517 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008518 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008519 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008520 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008521 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008522 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008523 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008524 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008525 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008526 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008527 llvm_unreachable("Clause is not allowed.");
8528 }
8529 return Res;
8530}
8531
Alexey Bataev6402bca2015-12-28 07:25:51 +00008532static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8533 OpenMPScheduleClauseModifier M2,
8534 SourceLocation M1Loc, SourceLocation M2Loc) {
8535 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8536 SmallVector<unsigned, 2> Excluded;
8537 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8538 Excluded.push_back(M2);
8539 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8540 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8541 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8542 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8543 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8544 << getListOfPossibleValues(OMPC_schedule,
8545 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8546 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8547 Excluded)
8548 << getOpenMPClauseName(OMPC_schedule);
8549 return true;
8550 }
8551 return false;
8552}
8553
Alexey Bataev56dafe82014-06-20 07:16:17 +00008554OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008555 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008556 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008557 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8558 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8559 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8560 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8561 return nullptr;
8562 // OpenMP, 2.7.1, Loop Construct, Restrictions
8563 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8564 // but not both.
8565 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8566 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8567 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8568 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8569 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8570 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8571 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8572 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8573 return nullptr;
8574 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008575 if (Kind == OMPC_SCHEDULE_unknown) {
8576 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008577 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8578 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8579 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8580 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8581 Exclude);
8582 } else {
8583 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8584 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008585 }
8586 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8587 << Values << getOpenMPClauseName(OMPC_schedule);
8588 return nullptr;
8589 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008590 // OpenMP, 2.7.1, Loop Construct, Restrictions
8591 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8592 // schedule(guided).
8593 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8594 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8595 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8596 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8597 diag::err_omp_schedule_nonmonotonic_static);
8598 return nullptr;
8599 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008600 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008601 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008602 if (ChunkSize) {
8603 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8604 !ChunkSize->isInstantiationDependent() &&
8605 !ChunkSize->containsUnexpandedParameterPack()) {
8606 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8607 ExprResult Val =
8608 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8609 if (Val.isInvalid())
8610 return nullptr;
8611
8612 ValExpr = Val.get();
8613
8614 // OpenMP [2.7.1, Restrictions]
8615 // chunk_size must be a loop invariant integer expression with a positive
8616 // value.
8617 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008618 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8619 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8620 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008621 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008622 return nullptr;
8623 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008624 } else if (getOpenMPCaptureRegionForClause(
8625 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8626 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008627 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008628 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8629 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8630 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008631 }
8632 }
8633 }
8634
Alexey Bataev6402bca2015-12-28 07:25:51 +00008635 return new (Context)
8636 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008637 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008638}
8639
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008640OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8641 SourceLocation StartLoc,
8642 SourceLocation EndLoc) {
8643 OMPClause *Res = nullptr;
8644 switch (Kind) {
8645 case OMPC_ordered:
8646 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8647 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008648 case OMPC_nowait:
8649 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8650 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008651 case OMPC_untied:
8652 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8653 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008654 case OMPC_mergeable:
8655 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8656 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008657 case OMPC_read:
8658 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8659 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008660 case OMPC_write:
8661 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8662 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008663 case OMPC_update:
8664 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8665 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008666 case OMPC_capture:
8667 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8668 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008669 case OMPC_seq_cst:
8670 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8671 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008672 case OMPC_threads:
8673 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8674 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008675 case OMPC_simd:
8676 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8677 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008678 case OMPC_nogroup:
8679 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8680 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008681 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008682 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008683 case OMPC_num_threads:
8684 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008685 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008686 case OMPC_collapse:
8687 case OMPC_schedule:
8688 case OMPC_private:
8689 case OMPC_firstprivate:
8690 case OMPC_lastprivate:
8691 case OMPC_shared:
8692 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008693 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008694 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008695 case OMPC_linear:
8696 case OMPC_aligned:
8697 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008698 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008699 case OMPC_default:
8700 case OMPC_proc_bind:
8701 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008702 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008703 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008704 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008705 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008706 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008707 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008708 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008709 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008710 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008711 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008712 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008713 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008714 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008715 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008716 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008717 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008718 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008719 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008720 llvm_unreachable("Clause is not allowed.");
8721 }
8722 return Res;
8723}
8724
Alexey Bataev236070f2014-06-20 11:19:47 +00008725OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8726 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008727 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008728 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8729}
8730
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008731OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8732 SourceLocation EndLoc) {
8733 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8734}
8735
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008736OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8737 SourceLocation EndLoc) {
8738 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8739}
8740
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008741OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8742 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008743 return new (Context) OMPReadClause(StartLoc, EndLoc);
8744}
8745
Alexey Bataevdea47612014-07-23 07:46:59 +00008746OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8747 SourceLocation EndLoc) {
8748 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8749}
8750
Alexey Bataev67a4f222014-07-23 10:25:33 +00008751OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8752 SourceLocation EndLoc) {
8753 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8754}
8755
Alexey Bataev459dec02014-07-24 06:46:57 +00008756OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8757 SourceLocation EndLoc) {
8758 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8759}
8760
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008761OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8762 SourceLocation EndLoc) {
8763 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8764}
8765
Alexey Bataev346265e2015-09-25 10:37:12 +00008766OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8767 SourceLocation EndLoc) {
8768 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8769}
8770
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008771OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8772 SourceLocation EndLoc) {
8773 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8774}
8775
Alexey Bataevb825de12015-12-07 10:51:44 +00008776OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8777 SourceLocation EndLoc) {
8778 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8779}
8780
Alexey Bataevc5e02582014-06-16 07:08:35 +00008781OMPClause *Sema::ActOnOpenMPVarListClause(
8782 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8783 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8784 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008785 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008786 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8787 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8788 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008789 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008790 switch (Kind) {
8791 case OMPC_private:
8792 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8793 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008794 case OMPC_firstprivate:
8795 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8796 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008797 case OMPC_lastprivate:
8798 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8799 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008800 case OMPC_shared:
8801 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8802 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008803 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008804 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8805 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008806 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008807 case OMPC_task_reduction:
8808 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8809 EndLoc, ReductionIdScopeSpec,
8810 ReductionId);
8811 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008812 case OMPC_in_reduction:
8813 Res =
8814 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8815 EndLoc, ReductionIdScopeSpec, ReductionId);
8816 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008817 case OMPC_linear:
8818 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008819 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008820 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008821 case OMPC_aligned:
8822 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8823 ColonLoc, EndLoc);
8824 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008825 case OMPC_copyin:
8826 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8827 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008828 case OMPC_copyprivate:
8829 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8830 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008831 case OMPC_flush:
8832 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8833 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008834 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008835 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008836 StartLoc, LParenLoc, EndLoc);
8837 break;
8838 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008839 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8840 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8841 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008842 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008843 case OMPC_to:
8844 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8845 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008846 case OMPC_from:
8847 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8848 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008849 case OMPC_use_device_ptr:
8850 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8851 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008852 case OMPC_is_device_ptr:
8853 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8854 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008855 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008856 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008857 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008858 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008859 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008860 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008861 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008862 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008863 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008864 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008865 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008866 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008867 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008868 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008869 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008870 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008871 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008872 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008873 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008874 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008875 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008876 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008877 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008878 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008879 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008880 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008881 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008882 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008883 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008884 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008885 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008886 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008887 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008888 llvm_unreachable("Clause is not allowed.");
8889 }
8890 return Res;
8891}
8892
Alexey Bataev90c228f2016-02-08 09:29:13 +00008893ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008894 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008895 ExprResult Res = BuildDeclRefExpr(
8896 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8897 if (!Res.isUsable())
8898 return ExprError();
8899 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8900 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8901 if (!Res.isUsable())
8902 return ExprError();
8903 }
8904 if (VK != VK_LValue && Res.get()->isGLValue()) {
8905 Res = DefaultLvalueConversion(Res.get());
8906 if (!Res.isUsable())
8907 return ExprError();
8908 }
8909 return Res;
8910}
8911
Alexey Bataev60da77e2016-02-29 05:54:20 +00008912static std::pair<ValueDecl *, bool>
8913getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8914 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008915 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8916 RefExpr->containsUnexpandedParameterPack())
8917 return std::make_pair(nullptr, true);
8918
Alexey Bataevd985eda2016-02-10 11:29:16 +00008919 // OpenMP [3.1, C/C++]
8920 // A list item is a variable name.
8921 // OpenMP [2.9.3.3, Restrictions, p.1]
8922 // A variable that is part of another variable (as an array or
8923 // structure element) cannot appear in a private clause.
8924 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008925 enum {
8926 NoArrayExpr = -1,
8927 ArraySubscript = 0,
8928 OMPArraySection = 1
8929 } IsArrayExpr = NoArrayExpr;
8930 if (AllowArraySection) {
8931 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8932 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8933 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8934 Base = TempASE->getBase()->IgnoreParenImpCasts();
8935 RefExpr = Base;
8936 IsArrayExpr = ArraySubscript;
8937 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8938 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8939 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8940 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8941 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8942 Base = TempASE->getBase()->IgnoreParenImpCasts();
8943 RefExpr = Base;
8944 IsArrayExpr = OMPArraySection;
8945 }
8946 }
8947 ELoc = RefExpr->getExprLoc();
8948 ERange = RefExpr->getSourceRange();
8949 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008950 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8951 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8952 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8953 (S.getCurrentThisType().isNull() || !ME ||
8954 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8955 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008956 if (IsArrayExpr != NoArrayExpr)
8957 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8958 << ERange;
8959 else {
8960 S.Diag(ELoc,
8961 AllowArraySection
8962 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8963 : diag::err_omp_expected_var_name_member_expr)
8964 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8965 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008966 return std::make_pair(nullptr, false);
8967 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008968 return std::make_pair(
8969 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008970}
8971
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008972OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8973 SourceLocation StartLoc,
8974 SourceLocation LParenLoc,
8975 SourceLocation EndLoc) {
8976 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008977 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008978 for (auto &RefExpr : VarList) {
8979 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008980 SourceLocation ELoc;
8981 SourceRange ERange;
8982 Expr *SimpleRefExpr = RefExpr;
8983 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008984 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008985 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008986 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008987 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008988 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008989 ValueDecl *D = Res.first;
8990 if (!D)
8991 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008992
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008993 QualType Type = D->getType();
8994 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008995
8996 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8997 // A variable that appears in a private clause must not have an incomplete
8998 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008999 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009000 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009001 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009002
Alexey Bataev758e55e2013-09-06 18:03:48 +00009003 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9004 // in a Construct]
9005 // Variables with the predetermined data-sharing attributes may not be
9006 // listed in data-sharing attributes clauses, except for the cases
9007 // listed below. For these exceptions only, listing a predetermined
9008 // variable in a data-sharing attribute clause is allowed and overrides
9009 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009010 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009011 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009012 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9013 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009014 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009015 continue;
9016 }
9017
Kelvin Libf594a52016-12-17 05:48:59 +00009018 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009019 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009020 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009021 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009022 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9023 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009024 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009025 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009026 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009027 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009028 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009029 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009030 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009031 continue;
9032 }
9033
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009034 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9035 // A list item cannot appear in both a map clause and a data-sharing
9036 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009037 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009038 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009039 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009040 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009041 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009042 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009043 CurrDir == OMPD_target_parallel_for_simd ||
9044 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009045 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009046 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009047 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009048 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9049 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9050 ConflictKind = WhereFoundClauseKind;
9051 return true;
9052 })) {
9053 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009054 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009055 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009056 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009057 ReportOriginalDSA(*this, DSAStack, D, DVar);
9058 continue;
9059 }
9060 }
9061
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009062 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9063 // A variable of class type (or array thereof) that appears in a private
9064 // clause requires an accessible, unambiguous default constructor for the
9065 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009066 // Generate helper private variable and initialize it with the default
9067 // value. The address of the original variable is replaced by the address of
9068 // the new private variable in CodeGen. This new variable is not added to
9069 // IdResolver, so the code in the OpenMP region uses original variable for
9070 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009071 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009072 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9073 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009074 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009075 if (VDPrivate->isInvalidDecl())
9076 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009077 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009078 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009079
Alexey Bataev90c228f2016-02-08 09:29:13 +00009080 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009081 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009082 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009083 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009084 Vars.push_back((VD || CurContext->isDependentContext())
9085 ? RefExpr->IgnoreParens()
9086 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009087 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009088 }
9089
Alexey Bataeved09d242014-05-28 05:53:51 +00009090 if (Vars.empty())
9091 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009092
Alexey Bataev03b340a2014-10-21 03:16:40 +00009093 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9094 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009095}
9096
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009097namespace {
9098class DiagsUninitializedSeveretyRAII {
9099private:
9100 DiagnosticsEngine &Diags;
9101 SourceLocation SavedLoc;
9102 bool IsIgnored;
9103
9104public:
9105 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9106 bool IsIgnored)
9107 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9108 if (!IsIgnored) {
9109 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9110 /*Map*/ diag::Severity::Ignored, Loc);
9111 }
9112 }
9113 ~DiagsUninitializedSeveretyRAII() {
9114 if (!IsIgnored)
9115 Diags.popMappings(SavedLoc);
9116 }
9117};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009118}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009119
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009120OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9121 SourceLocation StartLoc,
9122 SourceLocation LParenLoc,
9123 SourceLocation EndLoc) {
9124 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009125 SmallVector<Expr *, 8> PrivateCopies;
9126 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009127 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009128 bool IsImplicitClause =
9129 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9130 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9131
Alexey Bataeved09d242014-05-28 05:53:51 +00009132 for (auto &RefExpr : VarList) {
9133 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009134 SourceLocation ELoc;
9135 SourceRange ERange;
9136 Expr *SimpleRefExpr = RefExpr;
9137 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009138 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009139 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009140 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009141 PrivateCopies.push_back(nullptr);
9142 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009143 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009144 ValueDecl *D = Res.first;
9145 if (!D)
9146 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009147
Alexey Bataev60da77e2016-02-29 05:54:20 +00009148 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009149 QualType Type = D->getType();
9150 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009151
9152 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9153 // A variable that appears in a private clause must not have an incomplete
9154 // type or a reference type.
9155 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009156 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009157 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009158 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009159
9160 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9161 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009162 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009163 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009164 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009165
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009166 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009167 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009168 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009169 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009170 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009171 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009172 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009173 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9174 // A list item that specifies a given variable may not appear in more
9175 // than one clause on the same directive, except that a variable may be
9176 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009177 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9178 // A list item may appear in a firstprivate or lastprivate clause but not
9179 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009180 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009181 (isOpenMPDistributeDirective(CurrDir) ||
9182 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009183 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009184 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009185 << getOpenMPClauseName(DVar.CKind)
9186 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009187 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009188 continue;
9189 }
9190
9191 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9192 // in a Construct]
9193 // Variables with the predetermined data-sharing attributes may not be
9194 // listed in data-sharing attributes clauses, except for the cases
9195 // listed below. For these exceptions only, listing a predetermined
9196 // variable in a data-sharing attribute clause is allowed and overrides
9197 // the variable's predetermined data-sharing attributes.
9198 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9199 // in a Construct, C/C++, p.2]
9200 // Variables with const-qualified type having no mutable member may be
9201 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009202 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009203 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9204 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009205 << getOpenMPClauseName(DVar.CKind)
9206 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009207 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009208 continue;
9209 }
9210
9211 // OpenMP [2.9.3.4, Restrictions, p.2]
9212 // A list item that is private within a parallel region must not appear
9213 // in a firstprivate clause on a worksharing construct if any of the
9214 // worksharing regions arising from the worksharing construct ever bind
9215 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009216 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9217 // A list item that is private within a teams region must not appear in a
9218 // firstprivate clause on a distribute construct if any of the distribute
9219 // regions arising from the distribute construct ever bind to any of the
9220 // teams regions arising from the teams construct.
9221 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9222 // A list item that appears in a reduction clause of a teams construct
9223 // must not appear in a firstprivate clause on a distribute construct if
9224 // any of the distribute regions arising from the distribute construct
9225 // ever bind to any of the teams regions arising from the teams construct.
9226 if ((isOpenMPWorksharingDirective(CurrDir) ||
9227 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009228 !isOpenMPParallelDirective(CurrDir) &&
9229 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009230 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009231 if (DVar.CKind != OMPC_shared &&
9232 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009233 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009234 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009235 Diag(ELoc, diag::err_omp_required_access)
9236 << getOpenMPClauseName(OMPC_firstprivate)
9237 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009238 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009239 continue;
9240 }
9241 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009242 // OpenMP [2.9.3.4, Restrictions, p.3]
9243 // A list item that appears in a reduction clause of a parallel construct
9244 // must not appear in a firstprivate clause on a worksharing or task
9245 // construct if any of the worksharing or task regions arising from the
9246 // worksharing or task construct ever bind to any of the parallel regions
9247 // arising from the parallel construct.
9248 // OpenMP [2.9.3.4, Restrictions, p.4]
9249 // A list item that appears in a reduction clause in worksharing
9250 // construct must not appear in a firstprivate clause in a task construct
9251 // encountered during execution of any of the worksharing regions arising
9252 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009253 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009254 DVar = DSAStack->hasInnermostDSA(
9255 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9256 [](OpenMPDirectiveKind K) -> bool {
9257 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009258 isOpenMPWorksharingDirective(K) ||
9259 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009260 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009261 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009262 if (DVar.CKind == OMPC_reduction &&
9263 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009264 isOpenMPWorksharingDirective(DVar.DKind) ||
9265 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009266 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9267 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009268 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009269 continue;
9270 }
9271 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009272
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009273 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9274 // A list item cannot appear in both a map clause and a data-sharing
9275 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009276 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009277 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009278 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009279 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009280 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9281 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9282 ConflictKind = WhereFoundClauseKind;
9283 return true;
9284 })) {
9285 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009286 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009287 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009288 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9289 ReportOriginalDSA(*this, DSAStack, D, DVar);
9290 continue;
9291 }
9292 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009293 }
9294
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009295 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009296 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009297 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009298 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9299 << getOpenMPClauseName(OMPC_firstprivate) << Type
9300 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9301 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009302 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009303 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009304 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009305 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009306 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009307 continue;
9308 }
9309
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009310 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009311 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9312 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009313 // Generate helper private variable and initialize it with the value of the
9314 // original variable. The address of the original variable is replaced by
9315 // the address of the new private variable in the CodeGen. This new variable
9316 // is not added to IdResolver, so the code in the OpenMP region uses
9317 // original variable for proper diagnostics and variable capturing.
9318 Expr *VDInitRefExpr = nullptr;
9319 // For arrays generate initializer for single element and replace it by the
9320 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009321 if (Type->isArrayType()) {
9322 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009323 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009324 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009325 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009326 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009327 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009328 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009329 InitializedEntity Entity =
9330 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009331 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9332
9333 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9334 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9335 if (Result.isInvalid())
9336 VDPrivate->setInvalidDecl();
9337 else
9338 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009339 // Remove temp variable declaration.
9340 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009341 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009342 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9343 ".firstprivate.temp");
9344 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9345 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009346 AddInitializerToDecl(VDPrivate,
9347 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009348 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009349 }
9350 if (VDPrivate->isInvalidDecl()) {
9351 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009352 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009353 diag::note_omp_task_predetermined_firstprivate_here);
9354 }
9355 continue;
9356 }
9357 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009358 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009359 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9360 RefExpr->getExprLoc());
9361 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009362 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009363 if (TopDVar.CKind == OMPC_lastprivate)
9364 Ref = TopDVar.PrivateCopy;
9365 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009366 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009367 if (!IsOpenMPCapturedDecl(D))
9368 ExprCaptures.push_back(Ref->getDecl());
9369 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009370 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009371 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009372 Vars.push_back((VD || CurContext->isDependentContext())
9373 ? RefExpr->IgnoreParens()
9374 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009375 PrivateCopies.push_back(VDPrivateRefExpr);
9376 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009377 }
9378
Alexey Bataeved09d242014-05-28 05:53:51 +00009379 if (Vars.empty())
9380 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009381
9382 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009383 Vars, PrivateCopies, Inits,
9384 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009385}
9386
Alexander Musman1bb328c2014-06-04 13:06:39 +00009387OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9388 SourceLocation StartLoc,
9389 SourceLocation LParenLoc,
9390 SourceLocation EndLoc) {
9391 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009392 SmallVector<Expr *, 8> SrcExprs;
9393 SmallVector<Expr *, 8> DstExprs;
9394 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009395 SmallVector<Decl *, 4> ExprCaptures;
9396 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009397 for (auto &RefExpr : VarList) {
9398 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009399 SourceLocation ELoc;
9400 SourceRange ERange;
9401 Expr *SimpleRefExpr = RefExpr;
9402 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009403 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009404 // It will be analyzed later.
9405 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009406 SrcExprs.push_back(nullptr);
9407 DstExprs.push_back(nullptr);
9408 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009409 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009410 ValueDecl *D = Res.first;
9411 if (!D)
9412 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009413
Alexey Bataev74caaf22016-02-20 04:09:36 +00009414 QualType Type = D->getType();
9415 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009416
9417 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9418 // A variable that appears in a lastprivate clause must not have an
9419 // incomplete type or a reference type.
9420 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009421 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009422 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009423 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009424
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009425 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009426 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9427 // in a Construct]
9428 // Variables with the predetermined data-sharing attributes may not be
9429 // listed in data-sharing attributes clauses, except for the cases
9430 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009431 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9432 // A list item may appear in a firstprivate or lastprivate clause but not
9433 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009434 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009435 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009436 (isOpenMPDistributeDirective(CurrDir) ||
9437 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009438 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9439 Diag(ELoc, diag::err_omp_wrong_dsa)
9440 << getOpenMPClauseName(DVar.CKind)
9441 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009442 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009443 continue;
9444 }
9445
Alexey Bataevf29276e2014-06-18 04:14:57 +00009446 // OpenMP [2.14.3.5, Restrictions, p.2]
9447 // A list item that is private within a parallel region, or that appears in
9448 // the reduction clause of a parallel construct, must not appear in a
9449 // lastprivate clause on a worksharing construct if any of the corresponding
9450 // worksharing regions ever binds to any of the corresponding parallel
9451 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009452 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009453 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009454 !isOpenMPParallelDirective(CurrDir) &&
9455 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009456 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009457 if (DVar.CKind != OMPC_shared) {
9458 Diag(ELoc, diag::err_omp_required_access)
9459 << getOpenMPClauseName(OMPC_lastprivate)
9460 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009461 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009462 continue;
9463 }
9464 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009465
Alexander Musman1bb328c2014-06-04 13:06:39 +00009466 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009467 // A variable of class type (or array thereof) that appears in a
9468 // lastprivate clause requires an accessible, unambiguous default
9469 // constructor for the class type, unless the list item is also specified
9470 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009471 // A variable of class type (or array thereof) that appears in a
9472 // lastprivate clause requires an accessible, unambiguous copy assignment
9473 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009474 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009475 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009476 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009477 D->hasAttrs() ? &D->getAttrs() : nullptr);
9478 auto *PseudoSrcExpr =
9479 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009480 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009481 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009482 D->hasAttrs() ? &D->getAttrs() : nullptr);
9483 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009484 // For arrays generate assignment operation for single element and replace
9485 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009486 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009487 PseudoDstExpr, PseudoSrcExpr);
9488 if (AssignmentOp.isInvalid())
9489 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009490 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009491 /*DiscardedValue=*/true);
9492 if (AssignmentOp.isInvalid())
9493 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009494
Alexey Bataev74caaf22016-02-20 04:09:36 +00009495 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009496 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009497 if (TopDVar.CKind == OMPC_firstprivate)
9498 Ref = TopDVar.PrivateCopy;
9499 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009500 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009501 if (!IsOpenMPCapturedDecl(D))
9502 ExprCaptures.push_back(Ref->getDecl());
9503 }
9504 if (TopDVar.CKind == OMPC_firstprivate ||
9505 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009506 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009507 ExprResult RefRes = DefaultLvalueConversion(Ref);
9508 if (!RefRes.isUsable())
9509 continue;
9510 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009511 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9512 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009513 if (!PostUpdateRes.isUsable())
9514 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009515 ExprPostUpdates.push_back(
9516 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009517 }
9518 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009519 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009520 Vars.push_back((VD || CurContext->isDependentContext())
9521 ? RefExpr->IgnoreParens()
9522 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009523 SrcExprs.push_back(PseudoSrcExpr);
9524 DstExprs.push_back(PseudoDstExpr);
9525 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009526 }
9527
9528 if (Vars.empty())
9529 return nullptr;
9530
9531 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009532 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009533 buildPreInits(Context, ExprCaptures),
9534 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009535}
9536
Alexey Bataev758e55e2013-09-06 18:03:48 +00009537OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9538 SourceLocation StartLoc,
9539 SourceLocation LParenLoc,
9540 SourceLocation EndLoc) {
9541 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009542 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009543 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009544 SourceLocation ELoc;
9545 SourceRange ERange;
9546 Expr *SimpleRefExpr = RefExpr;
9547 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009548 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009549 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009550 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009551 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009552 ValueDecl *D = Res.first;
9553 if (!D)
9554 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009555
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009556 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009557 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9558 // in a Construct]
9559 // Variables with the predetermined data-sharing attributes may not be
9560 // listed in data-sharing attributes clauses, except for the cases
9561 // listed below. For these exceptions only, listing a predetermined
9562 // variable in a data-sharing attribute clause is allowed and overrides
9563 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009564 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009565 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9566 DVar.RefExpr) {
9567 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9568 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009569 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009570 continue;
9571 }
9572
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009573 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009574 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009575 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009576 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009577 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9578 ? RefExpr->IgnoreParens()
9579 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009580 }
9581
Alexey Bataeved09d242014-05-28 05:53:51 +00009582 if (Vars.empty())
9583 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009584
9585 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9586}
9587
Alexey Bataevc5e02582014-06-16 07:08:35 +00009588namespace {
9589class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9590 DSAStackTy *Stack;
9591
9592public:
9593 bool VisitDeclRefExpr(DeclRefExpr *E) {
9594 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009595 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009596 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9597 return false;
9598 if (DVar.CKind != OMPC_unknown)
9599 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009600 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9601 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009602 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009603 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009604 return true;
9605 return false;
9606 }
9607 return false;
9608 }
9609 bool VisitStmt(Stmt *S) {
9610 for (auto Child : S->children()) {
9611 if (Child && Visit(Child))
9612 return true;
9613 }
9614 return false;
9615 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009616 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009617};
Alexey Bataev23b69422014-06-18 07:08:49 +00009618} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009619
Alexey Bataev60da77e2016-02-29 05:54:20 +00009620namespace {
9621// Transform MemberExpression for specified FieldDecl of current class to
9622// DeclRefExpr to specified OMPCapturedExprDecl.
9623class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9624 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9625 ValueDecl *Field;
9626 DeclRefExpr *CapturedExpr;
9627
9628public:
9629 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9630 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9631
9632 ExprResult TransformMemberExpr(MemberExpr *E) {
9633 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9634 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009635 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009636 return CapturedExpr;
9637 }
9638 return BaseTransform::TransformMemberExpr(E);
9639 }
9640 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9641};
9642} // namespace
9643
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009644template <typename T>
9645static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9646 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9647 for (auto &Set : Lookups) {
9648 for (auto *D : Set) {
9649 if (auto Res = Gen(cast<ValueDecl>(D)))
9650 return Res;
9651 }
9652 }
9653 return T();
9654}
9655
9656static ExprResult
9657buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9658 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9659 const DeclarationNameInfo &ReductionId, QualType Ty,
9660 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9661 if (ReductionIdScopeSpec.isInvalid())
9662 return ExprError();
9663 SmallVector<UnresolvedSet<8>, 4> Lookups;
9664 if (S) {
9665 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9666 Lookup.suppressDiagnostics();
9667 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9668 auto *D = Lookup.getRepresentativeDecl();
9669 do {
9670 S = S->getParent();
9671 } while (S && !S->isDeclScope(D));
9672 if (S)
9673 S = S->getParent();
9674 Lookups.push_back(UnresolvedSet<8>());
9675 Lookups.back().append(Lookup.begin(), Lookup.end());
9676 Lookup.clear();
9677 }
9678 } else if (auto *ULE =
9679 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9680 Lookups.push_back(UnresolvedSet<8>());
9681 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009682 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009683 if (D == PrevD)
9684 Lookups.push_back(UnresolvedSet<8>());
9685 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9686 Lookups.back().addDecl(DRD);
9687 PrevD = D;
9688 }
9689 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009690 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9691 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009692 Ty->containsUnexpandedParameterPack() ||
9693 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9694 return !D->isInvalidDecl() &&
9695 (D->getType()->isDependentType() ||
9696 D->getType()->isInstantiationDependentType() ||
9697 D->getType()->containsUnexpandedParameterPack());
9698 })) {
9699 UnresolvedSet<8> ResSet;
9700 for (auto &Set : Lookups) {
9701 ResSet.append(Set.begin(), Set.end());
9702 // The last item marks the end of all declarations at the specified scope.
9703 ResSet.addDecl(Set[Set.size() - 1]);
9704 }
9705 return UnresolvedLookupExpr::Create(
9706 SemaRef.Context, /*NamingClass=*/nullptr,
9707 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9708 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9709 }
9710 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9711 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9712 if (!D->isInvalidDecl() &&
9713 SemaRef.Context.hasSameType(D->getType(), Ty))
9714 return D;
9715 return nullptr;
9716 }))
9717 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9718 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9719 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9720 if (!D->isInvalidDecl() &&
9721 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9722 !Ty.isMoreQualifiedThan(D->getType()))
9723 return D;
9724 return nullptr;
9725 })) {
9726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9727 /*DetectVirtual=*/false);
9728 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9729 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9730 VD->getType().getUnqualifiedType()))) {
9731 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9732 /*DiagID=*/0) !=
9733 Sema::AR_inaccessible) {
9734 SemaRef.BuildBasePathArray(Paths, BasePath);
9735 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9736 }
9737 }
9738 }
9739 }
9740 if (ReductionIdScopeSpec.isSet()) {
9741 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9742 return ExprError();
9743 }
9744 return ExprEmpty();
9745}
9746
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009747namespace {
9748/// Data for the reduction-based clauses.
9749struct ReductionData {
9750 /// List of original reduction items.
9751 SmallVector<Expr *, 8> Vars;
9752 /// List of private copies of the reduction items.
9753 SmallVector<Expr *, 8> Privates;
9754 /// LHS expressions for the reduction_op expressions.
9755 SmallVector<Expr *, 8> LHSs;
9756 /// RHS expressions for the reduction_op expressions.
9757 SmallVector<Expr *, 8> RHSs;
9758 /// Reduction operation expression.
9759 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009760 /// Taskgroup descriptors for the corresponding reduction items in
9761 /// in_reduction clauses.
9762 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009763 /// List of captures for clause.
9764 SmallVector<Decl *, 4> ExprCaptures;
9765 /// List of postupdate expressions.
9766 SmallVector<Expr *, 4> ExprPostUpdates;
9767 ReductionData() = delete;
9768 /// Reserves required memory for the reduction data.
9769 ReductionData(unsigned Size) {
9770 Vars.reserve(Size);
9771 Privates.reserve(Size);
9772 LHSs.reserve(Size);
9773 RHSs.reserve(Size);
9774 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009775 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009776 ExprCaptures.reserve(Size);
9777 ExprPostUpdates.reserve(Size);
9778 }
9779 /// Stores reduction item and reduction operation only (required for dependent
9780 /// reduction item).
9781 void push(Expr *Item, Expr *ReductionOp) {
9782 Vars.emplace_back(Item);
9783 Privates.emplace_back(nullptr);
9784 LHSs.emplace_back(nullptr);
9785 RHSs.emplace_back(nullptr);
9786 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009787 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009788 }
9789 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009790 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9791 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009792 Vars.emplace_back(Item);
9793 Privates.emplace_back(Private);
9794 LHSs.emplace_back(LHS);
9795 RHSs.emplace_back(RHS);
9796 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009797 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009798 }
9799};
9800} // namespace
9801
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009802static bool CheckOMPArraySectionConstantForReduction(
9803 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9804 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9805 const Expr *Length = OASE->getLength();
9806 if (Length == nullptr) {
9807 // For array sections of the form [1:] or [:], we would need to analyze
9808 // the lower bound...
9809 if (OASE->getColonLoc().isValid())
9810 return false;
9811
9812 // This is an array subscript which has implicit length 1!
9813 SingleElement = true;
9814 ArraySizes.push_back(llvm::APSInt::get(1));
9815 } else {
9816 llvm::APSInt ConstantLengthValue;
9817 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9818 return false;
9819
9820 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9821 ArraySizes.push_back(ConstantLengthValue);
9822 }
9823
9824 // Get the base of this array section and walk up from there.
9825 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9826
9827 // We require length = 1 for all array sections except the right-most to
9828 // guarantee that the memory region is contiguous and has no holes in it.
9829 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9830 Length = TempOASE->getLength();
9831 if (Length == nullptr) {
9832 // For array sections of the form [1:] or [:], we would need to analyze
9833 // the lower bound...
9834 if (OASE->getColonLoc().isValid())
9835 return false;
9836
9837 // This is an array subscript which has implicit length 1!
9838 ArraySizes.push_back(llvm::APSInt::get(1));
9839 } else {
9840 llvm::APSInt ConstantLengthValue;
9841 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9842 ConstantLengthValue.getSExtValue() != 1)
9843 return false;
9844
9845 ArraySizes.push_back(ConstantLengthValue);
9846 }
9847 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9848 }
9849
9850 // If we have a single element, we don't need to add the implicit lengths.
9851 if (!SingleElement) {
9852 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9853 // Has implicit length 1!
9854 ArraySizes.push_back(llvm::APSInt::get(1));
9855 Base = TempASE->getBase()->IgnoreParenImpCasts();
9856 }
9857 }
9858
9859 // This array section can be privatized as a single value or as a constant
9860 // sized array.
9861 return true;
9862}
9863
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009864static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009865 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9866 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9867 SourceLocation ColonLoc, SourceLocation EndLoc,
9868 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009869 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009870 auto DN = ReductionId.getName();
9871 auto OOK = DN.getCXXOverloadedOperator();
9872 BinaryOperatorKind BOK = BO_Comma;
9873
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009874 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009875 // OpenMP [2.14.3.6, reduction clause]
9876 // C
9877 // reduction-identifier is either an identifier or one of the following
9878 // operators: +, -, *, &, |, ^, && and ||
9879 // C++
9880 // reduction-identifier is either an id-expression or one of the following
9881 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009882 switch (OOK) {
9883 case OO_Plus:
9884 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009885 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009886 break;
9887 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009888 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009889 break;
9890 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009891 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009892 break;
9893 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009894 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009895 break;
9896 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009897 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009898 break;
9899 case OO_AmpAmp:
9900 BOK = BO_LAnd;
9901 break;
9902 case OO_PipePipe:
9903 BOK = BO_LOr;
9904 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009905 case OO_New:
9906 case OO_Delete:
9907 case OO_Array_New:
9908 case OO_Array_Delete:
9909 case OO_Slash:
9910 case OO_Percent:
9911 case OO_Tilde:
9912 case OO_Exclaim:
9913 case OO_Equal:
9914 case OO_Less:
9915 case OO_Greater:
9916 case OO_LessEqual:
9917 case OO_GreaterEqual:
9918 case OO_PlusEqual:
9919 case OO_MinusEqual:
9920 case OO_StarEqual:
9921 case OO_SlashEqual:
9922 case OO_PercentEqual:
9923 case OO_CaretEqual:
9924 case OO_AmpEqual:
9925 case OO_PipeEqual:
9926 case OO_LessLess:
9927 case OO_GreaterGreater:
9928 case OO_LessLessEqual:
9929 case OO_GreaterGreaterEqual:
9930 case OO_EqualEqual:
9931 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +00009932 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009933 case OO_PlusPlus:
9934 case OO_MinusMinus:
9935 case OO_Comma:
9936 case OO_ArrowStar:
9937 case OO_Arrow:
9938 case OO_Call:
9939 case OO_Subscript:
9940 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009941 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009942 case NUM_OVERLOADED_OPERATORS:
9943 llvm_unreachable("Unexpected reduction identifier");
9944 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009945 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009946 if (II->isStr("max"))
9947 BOK = BO_GT;
9948 else if (II->isStr("min"))
9949 BOK = BO_LT;
9950 }
9951 break;
9952 }
9953 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009954 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009955 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009956 else
9957 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009958 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009959
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009960 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9961 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009962 for (auto RefExpr : VarList) {
9963 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009964 // OpenMP [2.1, C/C++]
9965 // A list item is a variable or array section, subject to the restrictions
9966 // specified in Section 2.4 on page 42 and in each of the sections
9967 // describing clauses and directives for which a list appears.
9968 // OpenMP [2.14.3.3, Restrictions, p.1]
9969 // A variable that is part of another variable (as an array or
9970 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009971 if (!FirstIter && IR != ER)
9972 ++IR;
9973 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009974 SourceLocation ELoc;
9975 SourceRange ERange;
9976 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009977 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009978 /*AllowArraySection=*/true);
9979 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009980 // Try to find 'declare reduction' corresponding construct before using
9981 // builtin/overloaded operators.
9982 QualType Type = Context.DependentTy;
9983 CXXCastPath BasePath;
9984 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009985 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009986 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009987 Expr *ReductionOp = nullptr;
9988 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009989 (DeclareReductionRef.isUnset() ||
9990 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009991 ReductionOp = DeclareReductionRef.get();
9992 // It will be analyzed later.
9993 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009994 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009995 ValueDecl *D = Res.first;
9996 if (!D)
9997 continue;
9998
Alexey Bataev88202be2017-07-27 13:20:36 +00009999 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010000 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010001 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10002 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10003 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +000010004 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010005 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010006 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10007 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10008 Type = ATy->getElementType();
10009 else
10010 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010011 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010012 } else
10013 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10014 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010015
Alexey Bataevc5e02582014-06-16 07:08:35 +000010016 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10017 // A variable that appears in a private clause must not have an incomplete
10018 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010019 if (S.RequireCompleteType(ELoc, Type,
10020 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010021 continue;
10022 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010023 // A list item that appears in a reduction clause must not be
10024 // const-qualified.
10025 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010026 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010027 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010028 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10029 VarDecl::DeclarationOnly;
10030 S.Diag(D->getLocation(),
10031 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010032 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010033 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010034 continue;
10035 }
10036 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10037 // If a list-item is a reference type then it must bind to the same object
10038 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010039 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010040 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010041 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010042 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010043 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010044 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10045 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010046 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010047 continue;
10048 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010049 }
10050 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010051
Alexey Bataevc5e02582014-06-16 07:08:35 +000010052 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10053 // in a Construct]
10054 // Variables with the predetermined data-sharing attributes may not be
10055 // listed in data-sharing attributes clauses, except for the cases
10056 // listed below. For these exceptions only, listing a predetermined
10057 // variable in a data-sharing attribute clause is allowed and overrides
10058 // the variable's predetermined data-sharing attributes.
10059 // OpenMP [2.14.3.6, Restrictions, p.3]
10060 // Any number of reduction clauses can be specified on the directive,
10061 // but a list item can appear only once in the reduction clauses for that
10062 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010063 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010064 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010065 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010066 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010067 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010068 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010069 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010070 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010071 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010072 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010073 << getOpenMPClauseName(DVar.CKind)
10074 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010075 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010076 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010077 }
10078
10079 // OpenMP [2.14.3.6, Restrictions, p.1]
10080 // A list item that appears in a reduction clause of a worksharing
10081 // construct must be shared in the parallel regions to which any of the
10082 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010083 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010084 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010085 !isOpenMPParallelDirective(CurrDir) &&
10086 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010087 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010088 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010089 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010090 << getOpenMPClauseName(OMPC_reduction)
10091 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010092 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010093 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010094 }
10095 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010096
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010097 // Try to find 'declare reduction' corresponding construct before using
10098 // builtin/overloaded operators.
10099 CXXCastPath BasePath;
10100 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010101 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010102 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10103 if (DeclareReductionRef.isInvalid())
10104 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010105 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010106 (DeclareReductionRef.isUnset() ||
10107 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010108 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010109 continue;
10110 }
10111 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10112 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010113 S.Diag(ReductionId.getLocStart(),
10114 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010115 << Type << ReductionIdRange;
10116 continue;
10117 }
10118
10119 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10120 // The type of a list item that appears in a reduction clause must be valid
10121 // for the reduction-identifier. For a max or min reduction in C, the type
10122 // of the list item must be an allowed arithmetic data type: char, int,
10123 // float, double, or _Bool, possibly modified with long, short, signed, or
10124 // unsigned. For a max or min reduction in C++, the type of the list item
10125 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10126 // double, or bool, possibly modified with long, short, signed, or unsigned.
10127 if (DeclareReductionRef.isUnset()) {
10128 if ((BOK == BO_GT || BOK == BO_LT) &&
10129 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010130 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10131 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010132 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010133 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010134 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10135 VarDecl::DeclarationOnly;
10136 S.Diag(D->getLocation(),
10137 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010138 << D;
10139 }
10140 continue;
10141 }
10142 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010143 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010144 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10145 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010146 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010147 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10148 VarDecl::DeclarationOnly;
10149 S.Diag(D->getLocation(),
10150 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010151 << D;
10152 }
10153 continue;
10154 }
10155 }
10156
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010157 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010158 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010159 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010160 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010161 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010162 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010163
10164 // Try if we can determine constant lengths for all array sections and avoid
10165 // the VLA.
10166 bool ConstantLengthOASE = false;
10167 if (OASE) {
10168 bool SingleElement;
10169 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10170 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10171 Context, OASE, SingleElement, ArraySizes);
10172
10173 // If we don't have a single element, we must emit a constant array type.
10174 if (ConstantLengthOASE && !SingleElement) {
10175 for (auto &Size : ArraySizes) {
10176 PrivateTy = Context.getConstantArrayType(
10177 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10178 }
10179 }
10180 }
10181
10182 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010183 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010184 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010185 if (!Context.getTargetInfo().isVLASupported() &&
10186 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10187 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10188 S.Diag(ELoc, diag::note_vla_unsupported);
10189 continue;
10190 }
David Majnemer9d168222016-08-05 17:44:54 +000010191 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010192 // Create pseudo array type for private copy. The size for this array will
10193 // be generated during codegen.
10194 // For array subscripts or single variables Private Ty is the same as Type
10195 // (type of the variable or single array element).
10196 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010197 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010198 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010199 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010200 } else if (!ASE && !OASE &&
10201 Context.getAsArrayType(D->getType().getNonReferenceType()))
10202 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010203 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010204 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010205 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010206 // Add initializer for private variable.
10207 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010208 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10209 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010210 if (DeclareReductionRef.isUsable()) {
10211 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10212 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10213 if (DRD->getInitializer()) {
10214 Init = DRDRef;
10215 RHSVD->setInit(DRDRef);
10216 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010217 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010218 } else {
10219 switch (BOK) {
10220 case BO_Add:
10221 case BO_Xor:
10222 case BO_Or:
10223 case BO_LOr:
10224 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10225 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010226 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010227 break;
10228 case BO_Mul:
10229 case BO_LAnd:
10230 if (Type->isScalarType() || Type->isAnyComplexType()) {
10231 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010232 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010233 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010234 break;
10235 case BO_And: {
10236 // '&' reduction op - initializer is '~0'.
10237 QualType OrigType = Type;
10238 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10239 Type = ComplexTy->getElementType();
10240 if (Type->isRealFloatingType()) {
10241 llvm::APFloat InitValue =
10242 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10243 /*isIEEE=*/true);
10244 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10245 Type, ELoc);
10246 } else if (Type->isScalarType()) {
10247 auto Size = Context.getTypeSize(Type);
10248 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10249 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10250 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10251 }
10252 if (Init && OrigType->isAnyComplexType()) {
10253 // Init = 0xFFFF + 0xFFFFi;
10254 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010255 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010256 }
10257 Type = OrigType;
10258 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010259 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010260 case BO_LT:
10261 case BO_GT: {
10262 // 'min' reduction op - initializer is 'Largest representable number in
10263 // the reduction list item type'.
10264 // 'max' reduction op - initializer is 'Least representable number in
10265 // the reduction list item type'.
10266 if (Type->isIntegerType() || Type->isPointerType()) {
10267 bool IsSigned = Type->hasSignedIntegerRepresentation();
10268 auto Size = Context.getTypeSize(Type);
10269 QualType IntTy =
10270 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10271 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010272 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10273 : llvm::APInt::getMinValue(Size)
10274 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10275 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010276 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10277 if (Type->isPointerType()) {
10278 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010279 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010280 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010281 if (CastExpr.isInvalid())
10282 continue;
10283 Init = CastExpr.get();
10284 }
10285 } else if (Type->isRealFloatingType()) {
10286 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10287 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10288 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10289 Type, ELoc);
10290 }
10291 break;
10292 }
10293 case BO_PtrMemD:
10294 case BO_PtrMemI:
10295 case BO_MulAssign:
10296 case BO_Div:
10297 case BO_Rem:
10298 case BO_Sub:
10299 case BO_Shl:
10300 case BO_Shr:
10301 case BO_LE:
10302 case BO_GE:
10303 case BO_EQ:
10304 case BO_NE:
10305 case BO_AndAssign:
10306 case BO_XorAssign:
10307 case BO_OrAssign:
10308 case BO_Assign:
10309 case BO_AddAssign:
10310 case BO_SubAssign:
10311 case BO_DivAssign:
10312 case BO_RemAssign:
10313 case BO_ShlAssign:
10314 case BO_ShrAssign:
10315 case BO_Comma:
10316 llvm_unreachable("Unexpected reduction operation");
10317 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010318 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010319 if (Init && DeclareReductionRef.isUnset())
10320 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10321 else if (!Init)
10322 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010323 if (RHSVD->isInvalidDecl())
10324 continue;
10325 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010326 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10327 << Type << ReductionIdRange;
10328 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10329 VarDecl::DeclarationOnly;
10330 S.Diag(D->getLocation(),
10331 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010332 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010333 continue;
10334 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010335 // Store initializer for single element in private copy. Will be used during
10336 // codegen.
10337 PrivateVD->setInit(RHSVD->getInit());
10338 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010339 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010340 ExprResult ReductionOp;
10341 if (DeclareReductionRef.isUsable()) {
10342 QualType RedTy = DeclareReductionRef.get()->getType();
10343 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010344 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10345 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010346 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010347 LHS = S.DefaultLvalueConversion(LHS.get());
10348 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010349 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10350 CK_UncheckedDerivedToBase, LHS.get(),
10351 &BasePath, LHS.get()->getValueKind());
10352 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10353 CK_UncheckedDerivedToBase, RHS.get(),
10354 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010355 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010356 FunctionProtoType::ExtProtoInfo EPI;
10357 QualType Params[] = {PtrRedTy, PtrRedTy};
10358 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10359 auto *OVE = new (Context) OpaqueValueExpr(
10360 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010361 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010362 Expr *Args[] = {LHS.get(), RHS.get()};
10363 ReductionOp = new (Context)
10364 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10365 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010366 ReductionOp = S.BuildBinOp(
10367 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010368 if (ReductionOp.isUsable()) {
10369 if (BOK != BO_LT && BOK != BO_GT) {
10370 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010371 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10372 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010373 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010374 auto *ConditionalOp = new (Context)
10375 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10376 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010377 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010378 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10379 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010380 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010381 if (ReductionOp.isUsable())
10382 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010383 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010384 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010385 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010386 }
10387
Alexey Bataevfa312f32017-07-21 18:48:21 +000010388 // OpenMP [2.15.4.6, Restrictions, p.2]
10389 // A list item that appears in an in_reduction clause of a task construct
10390 // must appear in a task_reduction clause of a construct associated with a
10391 // taskgroup region that includes the participating task in its taskgroup
10392 // set. The construct associated with the innermost region that meets this
10393 // condition must specify the same reduction-identifier as the in_reduction
10394 // clause.
10395 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010396 SourceRange ParentSR;
10397 BinaryOperatorKind ParentBOK;
10398 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010399 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010400 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010401 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10402 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010403 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010404 Stack->getTopMostTaskgroupReductionData(
10405 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010406 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10407 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10408 if (!IsParentBOK && !IsParentReductionOp) {
10409 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10410 continue;
10411 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010412 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10413 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10414 IsParentReductionOp) {
10415 bool EmitError = true;
10416 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10417 llvm::FoldingSetNodeID RedId, ParentRedId;
10418 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10419 DeclareReductionRef.get()->Profile(RedId, Context,
10420 /*Canonical=*/true);
10421 EmitError = RedId != ParentRedId;
10422 }
10423 if (EmitError) {
10424 S.Diag(ReductionId.getLocStart(),
10425 diag::err_omp_reduction_identifier_mismatch)
10426 << ReductionIdRange << RefExpr->getSourceRange();
10427 S.Diag(ParentSR.getBegin(),
10428 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010429 << ParentSR
10430 << (IsParentBOK ? ParentBOKDSA.RefExpr
10431 : ParentReductionOpDSA.RefExpr)
10432 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010433 continue;
10434 }
10435 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010436 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10437 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010438 }
10439
Alexey Bataev60da77e2016-02-29 05:54:20 +000010440 DeclRefExpr *Ref = nullptr;
10441 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010442 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010443 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010444 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010445 VarsExpr =
10446 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10447 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010448 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010449 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010450 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010451 if (!S.IsOpenMPCapturedDecl(D)) {
10452 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010453 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010454 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010455 if (!RefRes.isUsable())
10456 continue;
10457 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010458 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10459 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010460 if (!PostUpdateRes.isUsable())
10461 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010462 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10463 Stack->getCurrentDirective() == OMPD_taskgroup) {
10464 S.Diag(RefExpr->getExprLoc(),
10465 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010466 << RefExpr->getSourceRange();
10467 continue;
10468 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010469 RD.ExprPostUpdates.emplace_back(
10470 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010471 }
10472 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010473 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010474 // All reduction items are still marked as reduction (to do not increase
10475 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010476 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010477 if (CurrDir == OMPD_taskgroup) {
10478 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010479 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10480 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010481 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010482 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010483 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010484 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10485 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010486 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010487 return RD.Vars.empty();
10488}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010489
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010490OMPClause *Sema::ActOnOpenMPReductionClause(
10491 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10492 SourceLocation ColonLoc, SourceLocation EndLoc,
10493 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10494 ArrayRef<Expr *> UnresolvedReductions) {
10495 ReductionData RD(VarList.size());
10496
Alexey Bataev169d96a2017-07-18 20:17:46 +000010497 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10498 StartLoc, LParenLoc, ColonLoc, EndLoc,
10499 ReductionIdScopeSpec, ReductionId,
10500 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010501 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010502
Alexey Bataevc5e02582014-06-16 07:08:35 +000010503 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010504 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10505 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10506 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10507 buildPreInits(Context, RD.ExprCaptures),
10508 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010509}
10510
Alexey Bataev169d96a2017-07-18 20:17:46 +000010511OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10512 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10513 SourceLocation ColonLoc, SourceLocation EndLoc,
10514 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10515 ArrayRef<Expr *> UnresolvedReductions) {
10516 ReductionData RD(VarList.size());
10517
10518 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10519 VarList, StartLoc, LParenLoc, ColonLoc,
10520 EndLoc, ReductionIdScopeSpec, ReductionId,
10521 UnresolvedReductions, RD))
10522 return nullptr;
10523
10524 return OMPTaskReductionClause::Create(
10525 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10526 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10527 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10528 buildPreInits(Context, RD.ExprCaptures),
10529 buildPostUpdate(*this, RD.ExprPostUpdates));
10530}
10531
Alexey Bataevfa312f32017-07-21 18:48:21 +000010532OMPClause *Sema::ActOnOpenMPInReductionClause(
10533 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10534 SourceLocation ColonLoc, SourceLocation EndLoc,
10535 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10536 ArrayRef<Expr *> UnresolvedReductions) {
10537 ReductionData RD(VarList.size());
10538
10539 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10540 StartLoc, LParenLoc, ColonLoc, EndLoc,
10541 ReductionIdScopeSpec, ReductionId,
10542 UnresolvedReductions, RD))
10543 return nullptr;
10544
10545 return OMPInReductionClause::Create(
10546 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10547 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010548 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010549 buildPreInits(Context, RD.ExprCaptures),
10550 buildPostUpdate(*this, RD.ExprPostUpdates));
10551}
10552
Alexey Bataevecba70f2016-04-12 11:02:11 +000010553bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10554 SourceLocation LinLoc) {
10555 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10556 LinKind == OMPC_LINEAR_unknown) {
10557 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10558 return true;
10559 }
10560 return false;
10561}
10562
10563bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10564 OpenMPLinearClauseKind LinKind,
10565 QualType Type) {
10566 auto *VD = dyn_cast_or_null<VarDecl>(D);
10567 // A variable must not have an incomplete type or a reference type.
10568 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10569 return true;
10570 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10571 !Type->isReferenceType()) {
10572 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10573 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10574 return true;
10575 }
10576 Type = Type.getNonReferenceType();
10577
10578 // A list item must not be const-qualified.
10579 if (Type.isConstant(Context)) {
10580 Diag(ELoc, diag::err_omp_const_variable)
10581 << getOpenMPClauseName(OMPC_linear);
10582 if (D) {
10583 bool IsDecl =
10584 !VD ||
10585 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10586 Diag(D->getLocation(),
10587 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10588 << D;
10589 }
10590 return true;
10591 }
10592
10593 // A list item must be of integral or pointer type.
10594 Type = Type.getUnqualifiedType().getCanonicalType();
10595 const auto *Ty = Type.getTypePtrOrNull();
10596 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10597 !Ty->isPointerType())) {
10598 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10599 if (D) {
10600 bool IsDecl =
10601 !VD ||
10602 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10603 Diag(D->getLocation(),
10604 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10605 << D;
10606 }
10607 return true;
10608 }
10609 return false;
10610}
10611
Alexey Bataev182227b2015-08-20 10:54:39 +000010612OMPClause *Sema::ActOnOpenMPLinearClause(
10613 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10614 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10615 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010616 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010617 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010618 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010619 SmallVector<Decl *, 4> ExprCaptures;
10620 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010621 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010622 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010623 for (auto &RefExpr : VarList) {
10624 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010625 SourceLocation ELoc;
10626 SourceRange ERange;
10627 Expr *SimpleRefExpr = RefExpr;
10628 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10629 /*AllowArraySection=*/false);
10630 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010631 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010632 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010633 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010634 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010635 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010636 ValueDecl *D = Res.first;
10637 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010638 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010639
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010640 QualType Type = D->getType();
10641 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010642
10643 // OpenMP [2.14.3.7, linear clause]
10644 // A list-item cannot appear in more than one linear clause.
10645 // A list-item that appears in a linear clause cannot appear in any
10646 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010647 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010648 if (DVar.RefExpr) {
10649 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10650 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010651 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010652 continue;
10653 }
10654
Alexey Bataevecba70f2016-04-12 11:02:11 +000010655 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010656 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010657 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010658
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010659 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010660 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10661 D->hasAttrs() ? &D->getAttrs() : nullptr);
10662 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010663 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010664 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010665 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010666 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010667 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010668 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10669 if (!IsOpenMPCapturedDecl(D)) {
10670 ExprCaptures.push_back(Ref->getDecl());
10671 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10672 ExprResult RefRes = DefaultLvalueConversion(Ref);
10673 if (!RefRes.isUsable())
10674 continue;
10675 ExprResult PostUpdateRes =
10676 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10677 SimpleRefExpr, RefRes.get());
10678 if (!PostUpdateRes.isUsable())
10679 continue;
10680 ExprPostUpdates.push_back(
10681 IgnoredValueConversions(PostUpdateRes.get()).get());
10682 }
10683 }
10684 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010685 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010686 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010687 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010688 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010689 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010690 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010691 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10692
10693 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010694 Vars.push_back((VD || CurContext->isDependentContext())
10695 ? RefExpr->IgnoreParens()
10696 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010697 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010698 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010699 }
10700
10701 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010702 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010703
10704 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010705 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010706 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10707 !Step->isInstantiationDependent() &&
10708 !Step->containsUnexpandedParameterPack()) {
10709 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010710 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010711 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010712 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010713 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010714
Alexander Musman3276a272015-03-21 10:12:56 +000010715 // Build var to save the step value.
10716 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010717 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010718 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010719 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010720 ExprResult CalcStep =
10721 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010722 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010723
Alexander Musman8dba6642014-04-22 13:09:42 +000010724 // Warn about zero linear step (it would be probably better specified as
10725 // making corresponding variables 'const').
10726 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010727 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10728 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010729 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10730 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010731 if (!IsConstant && CalcStep.isUsable()) {
10732 // Calculate the step beforehand instead of doing this on each iteration.
10733 // (This is not used if the number of iterations may be kfold-ed).
10734 CalcStepExpr = CalcStep.get();
10735 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010736 }
10737
Alexey Bataev182227b2015-08-20 10:54:39 +000010738 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10739 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010740 StepExpr, CalcStepExpr,
10741 buildPreInits(Context, ExprCaptures),
10742 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010743}
10744
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010745static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10746 Expr *NumIterations, Sema &SemaRef,
10747 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010748 // Walk the vars and build update/final expressions for the CodeGen.
10749 SmallVector<Expr *, 8> Updates;
10750 SmallVector<Expr *, 8> Finals;
10751 Expr *Step = Clause.getStep();
10752 Expr *CalcStep = Clause.getCalcStep();
10753 // OpenMP [2.14.3.7, linear clause]
10754 // If linear-step is not specified it is assumed to be 1.
10755 if (Step == nullptr)
10756 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010757 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010758 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010759 }
Alexander Musman3276a272015-03-21 10:12:56 +000010760 bool HasErrors = false;
10761 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010762 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010763 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010764 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010765 SourceLocation ELoc;
10766 SourceRange ERange;
10767 Expr *SimpleRefExpr = RefExpr;
10768 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10769 /*AllowArraySection=*/false);
10770 ValueDecl *D = Res.first;
10771 if (Res.second || !D) {
10772 Updates.push_back(nullptr);
10773 Finals.push_back(nullptr);
10774 HasErrors = true;
10775 continue;
10776 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010777 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000010778 // OpenMP [2.15.11, distribute simd Construct]
10779 // A list item may not appear in a linear clause, unless it is the loop
10780 // iteration variable.
10781 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
10782 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
10783 SemaRef.Diag(ELoc,
10784 diag::err_omp_linear_distribute_var_non_loop_iteration);
10785 Updates.push_back(nullptr);
10786 Finals.push_back(nullptr);
10787 HasErrors = true;
10788 continue;
10789 }
Alexander Musman3276a272015-03-21 10:12:56 +000010790 Expr *InitExpr = *CurInit;
10791
10792 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010793 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010794 Expr *CapturedRef;
10795 if (LinKind == OMPC_LINEAR_uval)
10796 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10797 else
10798 CapturedRef =
10799 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10800 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10801 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010802
10803 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010804 ExprResult Update;
10805 if (!Info.first) {
10806 Update =
10807 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10808 InitExpr, IV, Step, /* Subtract */ false);
10809 } else
10810 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010811 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10812 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010813
10814 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010815 ExprResult Final;
10816 if (!Info.first) {
10817 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10818 InitExpr, NumIterations, Step,
10819 /* Subtract */ false);
10820 } else
10821 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010822 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10823 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010824
Alexander Musman3276a272015-03-21 10:12:56 +000010825 if (!Update.isUsable() || !Final.isUsable()) {
10826 Updates.push_back(nullptr);
10827 Finals.push_back(nullptr);
10828 HasErrors = true;
10829 } else {
10830 Updates.push_back(Update.get());
10831 Finals.push_back(Final.get());
10832 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010833 ++CurInit;
10834 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010835 }
10836 Clause.setUpdates(Updates);
10837 Clause.setFinals(Finals);
10838 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010839}
10840
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010841OMPClause *Sema::ActOnOpenMPAlignedClause(
10842 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10843 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10844
10845 SmallVector<Expr *, 8> Vars;
10846 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010847 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10848 SourceLocation ELoc;
10849 SourceRange ERange;
10850 Expr *SimpleRefExpr = RefExpr;
10851 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10852 /*AllowArraySection=*/false);
10853 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010854 // It will be analyzed later.
10855 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010856 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010857 ValueDecl *D = Res.first;
10858 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010859 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010860
Alexey Bataev1efd1662016-03-29 10:59:56 +000010861 QualType QType = D->getType();
10862 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010863
10864 // OpenMP [2.8.1, simd construct, Restrictions]
10865 // The type of list items appearing in the aligned clause must be
10866 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010867 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010868 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010869 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010870 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010871 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010872 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010873 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010874 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010875 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010876 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010877 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010878 continue;
10879 }
10880
10881 // OpenMP [2.8.1, simd construct, Restrictions]
10882 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010883 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010884 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010885 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10886 << getOpenMPClauseName(OMPC_aligned);
10887 continue;
10888 }
10889
Alexey Bataev1efd1662016-03-29 10:59:56 +000010890 DeclRefExpr *Ref = nullptr;
10891 if (!VD && IsOpenMPCapturedDecl(D))
10892 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10893 Vars.push_back(DefaultFunctionArrayConversion(
10894 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10895 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010896 }
10897
10898 // OpenMP [2.8.1, simd construct, Description]
10899 // The parameter of the aligned clause, alignment, must be a constant
10900 // positive integer expression.
10901 // If no optional parameter is specified, implementation-defined default
10902 // alignments for SIMD instructions on the target platforms are assumed.
10903 if (Alignment != nullptr) {
10904 ExprResult AlignResult =
10905 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10906 if (AlignResult.isInvalid())
10907 return nullptr;
10908 Alignment = AlignResult.get();
10909 }
10910 if (Vars.empty())
10911 return nullptr;
10912
10913 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10914 EndLoc, Vars, Alignment);
10915}
10916
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010917OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10918 SourceLocation StartLoc,
10919 SourceLocation LParenLoc,
10920 SourceLocation EndLoc) {
10921 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010922 SmallVector<Expr *, 8> SrcExprs;
10923 SmallVector<Expr *, 8> DstExprs;
10924 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010925 for (auto &RefExpr : VarList) {
10926 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10927 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010928 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010929 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010930 SrcExprs.push_back(nullptr);
10931 DstExprs.push_back(nullptr);
10932 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010933 continue;
10934 }
10935
Alexey Bataeved09d242014-05-28 05:53:51 +000010936 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010937 // OpenMP [2.1, C/C++]
10938 // A list item is a variable name.
10939 // OpenMP [2.14.4.1, Restrictions, p.1]
10940 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010941 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010942 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010943 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10944 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010945 continue;
10946 }
10947
10948 Decl *D = DE->getDecl();
10949 VarDecl *VD = cast<VarDecl>(D);
10950
10951 QualType Type = VD->getType();
10952 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10953 // It will be analyzed later.
10954 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010955 SrcExprs.push_back(nullptr);
10956 DstExprs.push_back(nullptr);
10957 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010958 continue;
10959 }
10960
10961 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10962 // A list item that appears in a copyin clause must be threadprivate.
10963 if (!DSAStack->isThreadPrivate(VD)) {
10964 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010965 << getOpenMPClauseName(OMPC_copyin)
10966 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010967 continue;
10968 }
10969
10970 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10971 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010972 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010973 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010974 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010975 auto *SrcVD =
10976 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10977 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010978 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010979 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10980 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010981 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10982 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010983 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010984 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010985 // For arrays generate assignment operation for single element and replace
10986 // it by the original array element in CodeGen.
10987 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10988 PseudoDstExpr, PseudoSrcExpr);
10989 if (AssignmentOp.isInvalid())
10990 continue;
10991 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10992 /*DiscardedValue=*/true);
10993 if (AssignmentOp.isInvalid())
10994 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010995
10996 DSAStack->addDSA(VD, DE, OMPC_copyin);
10997 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010998 SrcExprs.push_back(PseudoSrcExpr);
10999 DstExprs.push_back(PseudoDstExpr);
11000 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011001 }
11002
Alexey Bataeved09d242014-05-28 05:53:51 +000011003 if (Vars.empty())
11004 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011005
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011006 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11007 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011008}
11009
Alexey Bataevbae9a792014-06-27 10:37:06 +000011010OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11011 SourceLocation StartLoc,
11012 SourceLocation LParenLoc,
11013 SourceLocation EndLoc) {
11014 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011015 SmallVector<Expr *, 8> SrcExprs;
11016 SmallVector<Expr *, 8> DstExprs;
11017 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011018 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011019 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11020 SourceLocation ELoc;
11021 SourceRange ERange;
11022 Expr *SimpleRefExpr = RefExpr;
11023 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11024 /*AllowArraySection=*/false);
11025 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011026 // It will be analyzed later.
11027 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011028 SrcExprs.push_back(nullptr);
11029 DstExprs.push_back(nullptr);
11030 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011031 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011032 ValueDecl *D = Res.first;
11033 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011034 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011035
Alexey Bataeve122da12016-03-17 10:50:17 +000011036 QualType Type = D->getType();
11037 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011038
11039 // OpenMP [2.14.4.2, Restrictions, p.2]
11040 // A list item that appears in a copyprivate clause may not appear in a
11041 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011042 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11043 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011044 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11045 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011046 Diag(ELoc, diag::err_omp_wrong_dsa)
11047 << getOpenMPClauseName(DVar.CKind)
11048 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011049 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011050 continue;
11051 }
11052
11053 // OpenMP [2.11.4.2, Restrictions, p.1]
11054 // All list items that appear in a copyprivate clause must be either
11055 // threadprivate or private in the enclosing context.
11056 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011057 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011058 if (DVar.CKind == OMPC_shared) {
11059 Diag(ELoc, diag::err_omp_required_access)
11060 << getOpenMPClauseName(OMPC_copyprivate)
11061 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011062 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011063 continue;
11064 }
11065 }
11066 }
11067
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011068 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011069 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011070 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011071 << getOpenMPClauseName(OMPC_copyprivate) << Type
11072 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011073 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011074 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011075 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011076 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011077 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011078 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011079 continue;
11080 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011081
Alexey Bataevbae9a792014-06-27 10:37:06 +000011082 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11083 // A variable of class type (or array thereof) that appears in a
11084 // copyin clause requires an accessible, unambiguous copy assignment
11085 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011086 Type = Context.getBaseElementType(Type.getNonReferenceType())
11087 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011088 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011089 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11090 D->hasAttrs() ? &D->getAttrs() : nullptr);
11091 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011092 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011093 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11094 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011095 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011096 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011097 PseudoDstExpr, PseudoSrcExpr);
11098 if (AssignmentOp.isInvalid())
11099 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011100 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011101 /*DiscardedValue=*/true);
11102 if (AssignmentOp.isInvalid())
11103 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011104
11105 // No need to mark vars as copyprivate, they are already threadprivate or
11106 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011107 assert(VD || IsOpenMPCapturedDecl(D));
11108 Vars.push_back(
11109 VD ? RefExpr->IgnoreParens()
11110 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011111 SrcExprs.push_back(PseudoSrcExpr);
11112 DstExprs.push_back(PseudoDstExpr);
11113 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011114 }
11115
11116 if (Vars.empty())
11117 return nullptr;
11118
Alexey Bataeva63048e2015-03-23 06:18:07 +000011119 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11120 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011121}
11122
Alexey Bataev6125da92014-07-21 11:26:11 +000011123OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11124 SourceLocation StartLoc,
11125 SourceLocation LParenLoc,
11126 SourceLocation EndLoc) {
11127 if (VarList.empty())
11128 return nullptr;
11129
11130 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11131}
Alexey Bataevdea47612014-07-23 07:46:59 +000011132
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011133OMPClause *
11134Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11135 SourceLocation DepLoc, SourceLocation ColonLoc,
11136 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11137 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011138 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011139 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011140 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011141 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011142 return nullptr;
11143 }
11144 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011145 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11146 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011147 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011148 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011149 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11150 /*Last=*/OMPC_DEPEND_unknown, Except)
11151 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011152 return nullptr;
11153 }
11154 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011155 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011156 llvm::APSInt DepCounter(/*BitWidth=*/32);
11157 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11158 if (DepKind == OMPC_DEPEND_sink) {
11159 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11160 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11161 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011162 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011163 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011164 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11165 DSAStack->getParentOrderedRegionParam()) {
11166 for (auto &RefExpr : VarList) {
11167 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000011168 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011169 // It will be analyzed later.
11170 Vars.push_back(RefExpr);
11171 continue;
11172 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011173
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011174 SourceLocation ELoc = RefExpr->getExprLoc();
11175 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11176 if (DepKind == OMPC_DEPEND_sink) {
11177 if (DepCounter >= TotalDepCount) {
11178 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11179 continue;
11180 }
11181 ++DepCounter;
11182 // OpenMP [2.13.9, Summary]
11183 // depend(dependence-type : vec), where dependence-type is:
11184 // 'sink' and where vec is the iteration vector, which has the form:
11185 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11186 // where n is the value specified by the ordered clause in the loop
11187 // directive, xi denotes the loop iteration variable of the i-th nested
11188 // loop associated with the loop directive, and di is a constant
11189 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000011190 if (CurContext->isDependentContext()) {
11191 // It will be analyzed later.
11192 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011193 continue;
11194 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011195 SimpleExpr = SimpleExpr->IgnoreImplicit();
11196 OverloadedOperatorKind OOK = OO_None;
11197 SourceLocation OOLoc;
11198 Expr *LHS = SimpleExpr;
11199 Expr *RHS = nullptr;
11200 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11201 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11202 OOLoc = BO->getOperatorLoc();
11203 LHS = BO->getLHS()->IgnoreParenImpCasts();
11204 RHS = BO->getRHS()->IgnoreParenImpCasts();
11205 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11206 OOK = OCE->getOperator();
11207 OOLoc = OCE->getOperatorLoc();
11208 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11209 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11210 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11211 OOK = MCE->getMethodDecl()
11212 ->getNameInfo()
11213 .getName()
11214 .getCXXOverloadedOperator();
11215 OOLoc = MCE->getCallee()->getExprLoc();
11216 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11217 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11218 }
11219 SourceLocation ELoc;
11220 SourceRange ERange;
11221 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11222 /*AllowArraySection=*/false);
11223 if (Res.second) {
11224 // It will be analyzed later.
11225 Vars.push_back(RefExpr);
11226 }
11227 ValueDecl *D = Res.first;
11228 if (!D)
11229 continue;
11230
11231 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11232 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11233 continue;
11234 }
11235 if (RHS) {
11236 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11237 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11238 if (RHSRes.isInvalid())
11239 continue;
11240 }
11241 if (!CurContext->isDependentContext() &&
11242 DSAStack->getParentOrderedRegionParam() &&
11243 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000011244 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11245 DepCounter.getZExtValue());
11246 if (VD) {
11247 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11248 << 1 << VD;
11249 } else {
11250 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11251 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011252 continue;
11253 }
11254 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011255 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011256 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011257 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000011258 (ASE &&
11259 !ASE->getBase()
11260 ->getType()
11261 .getNonReferenceType()
11262 ->isPointerType() &&
11263 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011264 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11265 << RefExpr->getSourceRange();
11266 continue;
11267 }
11268 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11269 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000011270 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011271 RefExpr->IgnoreParenImpCasts());
11272 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11273 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11274 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11275 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011276 continue;
11277 }
11278 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011279 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11280 }
11281
11282 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11283 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011284 DSAStack->getParentOrderedRegionParam() &&
11285 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11286 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011287 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11288 }
11289 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11290 Vars.empty())
11291 return nullptr;
11292 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011293 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11294 DepKind, DepLoc, ColonLoc, Vars);
11295 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11296 DSAStack->addDoacrossDependClause(C, OpsOffs);
11297 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011298}
Michael Wonge710d542015-08-07 16:16:36 +000011299
11300OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11301 SourceLocation LParenLoc,
11302 SourceLocation EndLoc) {
11303 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011304 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011305
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011306 // OpenMP [2.9.1, Restrictions]
11307 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011308 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11309 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011310 return nullptr;
11311
Alexey Bataev931e19b2017-10-02 16:32:39 +000011312 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011313 OpenMPDirectiveKind CaptureRegion =
11314 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11315 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev931e19b2017-10-02 16:32:39 +000011316 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11317 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11318 HelperValStmt = buildPreInits(Context, Captures);
11319 }
11320
11321 return new (Context)
11322 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011323}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011324
Kelvin Li0bff7af2015-11-23 05:32:03 +000011325static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11326 DSAStackTy *Stack, QualType QTy) {
11327 NamedDecl *ND;
11328 if (QTy->isIncompleteType(&ND)) {
11329 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11330 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011331 }
11332 return true;
11333}
11334
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011335/// \brief Return true if it can be proven that the provided array expression
11336/// (array section or array subscript) does NOT specify the whole size of the
11337/// array whose base type is \a BaseQTy.
11338static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11339 const Expr *E,
11340 QualType BaseQTy) {
11341 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11342
11343 // If this is an array subscript, it refers to the whole size if the size of
11344 // the dimension is constant and equals 1. Also, an array section assumes the
11345 // format of an array subscript if no colon is used.
11346 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11347 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11348 return ATy->getSize().getSExtValue() != 1;
11349 // Size can't be evaluated statically.
11350 return false;
11351 }
11352
11353 assert(OASE && "Expecting array section if not an array subscript.");
11354 auto *LowerBound = OASE->getLowerBound();
11355 auto *Length = OASE->getLength();
11356
11357 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011358 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011359 if (LowerBound) {
11360 llvm::APSInt ConstLowerBound;
11361 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11362 return false; // Can't get the integer value as a constant.
11363 if (ConstLowerBound.getSExtValue())
11364 return true;
11365 }
11366
11367 // If we don't have a length we covering the whole dimension.
11368 if (!Length)
11369 return false;
11370
11371 // If the base is a pointer, we don't have a way to get the size of the
11372 // pointee.
11373 if (BaseQTy->isPointerType())
11374 return false;
11375
11376 // We can only check if the length is the same as the size of the dimension
11377 // if we have a constant array.
11378 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11379 if (!CATy)
11380 return false;
11381
11382 llvm::APSInt ConstLength;
11383 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11384 return false; // Can't get the integer value as a constant.
11385
11386 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11387}
11388
11389// Return true if it can be proven that the provided array expression (array
11390// section or array subscript) does NOT specify a single element of the array
11391// whose base type is \a BaseQTy.
11392static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011393 const Expr *E,
11394 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011395 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11396
11397 // An array subscript always refer to a single element. Also, an array section
11398 // assumes the format of an array subscript if no colon is used.
11399 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11400 return false;
11401
11402 assert(OASE && "Expecting array section if not an array subscript.");
11403 auto *Length = OASE->getLength();
11404
11405 // If we don't have a length we have to check if the array has unitary size
11406 // for this dimension. Also, we should always expect a length if the base type
11407 // is pointer.
11408 if (!Length) {
11409 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11410 return ATy->getSize().getSExtValue() != 1;
11411 // We cannot assume anything.
11412 return false;
11413 }
11414
11415 // Check if the length evaluates to 1.
11416 llvm::APSInt ConstLength;
11417 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11418 return false; // Can't get the integer value as a constant.
11419
11420 return ConstLength.getSExtValue() != 1;
11421}
11422
Samuel Antao661c0902016-05-26 17:39:58 +000011423// Return the expression of the base of the mappable expression or null if it
11424// cannot be determined and do all the necessary checks to see if the expression
11425// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011426// components of the expression.
11427static Expr *CheckMapClauseExpressionBase(
11428 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011429 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011430 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011431 SourceLocation ELoc = E->getExprLoc();
11432 SourceRange ERange = E->getSourceRange();
11433
11434 // The base of elements of list in a map clause have to be either:
11435 // - a reference to variable or field.
11436 // - a member expression.
11437 // - an array expression.
11438 //
11439 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11440 // reference to 'r'.
11441 //
11442 // If we have:
11443 //
11444 // struct SS {
11445 // Bla S;
11446 // foo() {
11447 // #pragma omp target map (S.Arr[:12]);
11448 // }
11449 // }
11450 //
11451 // We want to retrieve the member expression 'this->S';
11452
11453 Expr *RelevantExpr = nullptr;
11454
Samuel Antao5de996e2016-01-22 20:21:36 +000011455 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11456 // If a list item is an array section, it must specify contiguous storage.
11457 //
11458 // For this restriction it is sufficient that we make sure only references
11459 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011460 // exist except in the rightmost expression (unless they cover the whole
11461 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011462 //
11463 // r.ArrS[3:5].Arr[6:7]
11464 //
11465 // r.ArrS[3:5].x
11466 //
11467 // but these would be valid:
11468 // r.ArrS[3].Arr[6:7]
11469 //
11470 // r.ArrS[3].x
11471
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011472 bool AllowUnitySizeArraySection = true;
11473 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011474
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011475 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011476 E = E->IgnoreParenImpCasts();
11477
11478 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11479 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011480 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011481
11482 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011483
11484 // If we got a reference to a declaration, we should not expect any array
11485 // section before that.
11486 AllowUnitySizeArraySection = false;
11487 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011488
11489 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011490 CurComponents.emplace_back(CurE, CurE->getDecl());
11491 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011492 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11493
11494 if (isa<CXXThisExpr>(BaseE))
11495 // We found a base expression: this->Val.
11496 RelevantExpr = CurE;
11497 else
11498 E = BaseE;
11499
11500 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011501 if (!NoDiagnose) {
11502 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11503 << CurE->getSourceRange();
11504 return nullptr;
11505 }
11506 if (RelevantExpr)
11507 return nullptr;
11508 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011509 }
11510
11511 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11512
11513 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11514 // A bit-field cannot appear in a map clause.
11515 //
11516 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011517 if (!NoDiagnose) {
11518 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11519 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11520 return nullptr;
11521 }
11522 if (RelevantExpr)
11523 return nullptr;
11524 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011525 }
11526
11527 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11528 // If the type of a list item is a reference to a type T then the type
11529 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011530 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011531
11532 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11533 // A list item cannot be a variable that is a member of a structure with
11534 // a union type.
11535 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011536 if (auto *RT = CurType->getAs<RecordType>()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011537 if (RT->isUnionType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011538 if (!NoDiagnose) {
11539 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11540 << CurE->getSourceRange();
11541 return nullptr;
11542 }
11543 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011544 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011545 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011546
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011547 // If we got a member expression, we should not expect any array section
11548 // before that:
11549 //
11550 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11551 // If a list item is an element of a structure, only the rightmost symbol
11552 // of the variable reference can be an array section.
11553 //
11554 AllowUnitySizeArraySection = false;
11555 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011556
11557 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011558 CurComponents.emplace_back(CurE, FD);
11559 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011560 E = CurE->getBase()->IgnoreParenImpCasts();
11561
11562 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011563 if (!NoDiagnose) {
11564 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11565 << 0 << CurE->getSourceRange();
11566 return nullptr;
11567 }
11568 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011569 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011570
11571 // If we got an array subscript that express the whole dimension we
11572 // can have any array expressions before. If it only expressing part of
11573 // the dimension, we can only have unitary-size array expressions.
11574 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11575 E->getType()))
11576 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011577
11578 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011579 CurComponents.emplace_back(CurE, nullptr);
11580 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011581 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011582 E = CurE->getBase()->IgnoreParenImpCasts();
11583
Alexey Bataev27041fa2017-12-05 15:22:49 +000011584 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011585 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11586
Samuel Antao5de996e2016-01-22 20:21:36 +000011587 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11588 // If the type of a list item is a reference to a type T then the type
11589 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011590 if (CurType->isReferenceType())
11591 CurType = CurType->getPointeeType();
11592
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011593 bool IsPointer = CurType->isAnyPointerType();
11594
11595 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011596 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11597 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011598 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011599 }
11600
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011601 bool NotWhole =
11602 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11603 bool NotUnity =
11604 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11605
Samuel Antaodab51bb2016-07-18 23:22:11 +000011606 if (AllowWholeSizeArraySection) {
11607 // Any array section is currently allowed. Allowing a whole size array
11608 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011609 //
11610 // If this array section refers to the whole dimension we can still
11611 // accept other array sections before this one, except if the base is a
11612 // pointer. Otherwise, only unitary sections are accepted.
11613 if (NotWhole || IsPointer)
11614 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011615 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011616 // A unity or whole array section is not allowed and that is not
11617 // compatible with the properties of the current array section.
11618 SemaRef.Diag(
11619 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11620 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011621 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011622 }
Samuel Antao90927002016-04-26 14:54:23 +000011623
11624 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011625 CurComponents.emplace_back(CurE, nullptr);
11626 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011627 if (!NoDiagnose) {
11628 // If nothing else worked, this is not a valid map clause expression.
11629 SemaRef.Diag(
11630 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11631 << ERange;
11632 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011633 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011634 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011635 }
11636
11637 return RelevantExpr;
11638}
11639
11640// Return true if expression E associated with value VD has conflicts with other
11641// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011642static bool CheckMapConflicts(
11643 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11644 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011645 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11646 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011647 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011648 SourceLocation ELoc = E->getExprLoc();
11649 SourceRange ERange = E->getSourceRange();
11650
11651 // In order to easily check the conflicts we need to match each component of
11652 // the expression under test with the components of the expressions that are
11653 // already in the stack.
11654
Samuel Antao5de996e2016-01-22 20:21:36 +000011655 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011656 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011657 "Map clause expression with unexpected base!");
11658
11659 // Variables to help detecting enclosing problems in data environment nests.
11660 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011661 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011662
Samuel Antao90927002016-04-26 14:54:23 +000011663 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11664 VD, CurrentRegionOnly,
11665 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011666 StackComponents,
11667 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011668
Samuel Antao5de996e2016-01-22 20:21:36 +000011669 assert(!StackComponents.empty() &&
11670 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011671 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011672 "Map clause expression with unexpected base!");
11673
Samuel Antao90927002016-04-26 14:54:23 +000011674 // The whole expression in the stack.
11675 auto *RE = StackComponents.front().getAssociatedExpression();
11676
Samuel Antao5de996e2016-01-22 20:21:36 +000011677 // Expressions must start from the same base. Here we detect at which
11678 // point both expressions diverge from each other and see if we can
11679 // detect if the memory referred to both expressions is contiguous and
11680 // do not overlap.
11681 auto CI = CurComponents.rbegin();
11682 auto CE = CurComponents.rend();
11683 auto SI = StackComponents.rbegin();
11684 auto SE = StackComponents.rend();
11685 for (; CI != CE && SI != SE; ++CI, ++SI) {
11686
11687 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11688 // At most one list item can be an array item derived from a given
11689 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011690 if (CurrentRegionOnly &&
11691 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11692 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11693 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11694 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11695 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011696 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011697 << CI->getAssociatedExpression()->getSourceRange();
11698 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11699 diag::note_used_here)
11700 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011701 return true;
11702 }
11703
11704 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011705 if (CI->getAssociatedExpression()->getStmtClass() !=
11706 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011707 break;
11708
11709 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011710 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011711 break;
11712 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011713 // Check if the extra components of the expressions in the enclosing
11714 // data environment are redundant for the current base declaration.
11715 // If they are, the maps completely overlap, which is legal.
11716 for (; SI != SE; ++SI) {
11717 QualType Type;
11718 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011719 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011720 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011721 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11722 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011723 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11724 Type =
11725 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11726 }
11727 if (Type.isNull() || Type->isAnyPointerType() ||
11728 CheckArrayExpressionDoesNotReferToWholeSize(
11729 SemaRef, SI->getAssociatedExpression(), Type))
11730 break;
11731 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011732
11733 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11734 // List items of map clauses in the same construct must not share
11735 // original storage.
11736 //
11737 // If the expressions are exactly the same or one is a subset of the
11738 // other, it means they are sharing storage.
11739 if (CI == CE && SI == SE) {
11740 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011741 if (CKind == OMPC_map)
11742 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11743 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011744 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011745 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11746 << ERange;
11747 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011748 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11749 << RE->getSourceRange();
11750 return true;
11751 } else {
11752 // If we find the same expression in the enclosing data environment,
11753 // that is legal.
11754 IsEnclosedByDataEnvironmentExpr = true;
11755 return false;
11756 }
11757 }
11758
Samuel Antao90927002016-04-26 14:54:23 +000011759 QualType DerivedType =
11760 std::prev(CI)->getAssociatedDeclaration()->getType();
11761 SourceLocation DerivedLoc =
11762 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011763
11764 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11765 // If the type of a list item is a reference to a type T then the type
11766 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011767 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011768
11769 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11770 // A variable for which the type is pointer and an array section
11771 // derived from that variable must not appear as list items of map
11772 // clauses of the same construct.
11773 //
11774 // Also, cover one of the cases in:
11775 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11776 // If any part of the original storage of a list item has corresponding
11777 // storage in the device data environment, all of the original storage
11778 // must have corresponding storage in the device data environment.
11779 //
11780 if (DerivedType->isAnyPointerType()) {
11781 if (CI == CE || SI == SE) {
11782 SemaRef.Diag(
11783 DerivedLoc,
11784 diag::err_omp_pointer_mapped_along_with_derived_section)
11785 << DerivedLoc;
11786 } else {
11787 assert(CI != CE && SI != SE);
11788 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11789 << DerivedLoc;
11790 }
11791 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11792 << RE->getSourceRange();
11793 return true;
11794 }
11795
11796 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11797 // List items of map clauses in the same construct must not share
11798 // original storage.
11799 //
11800 // An expression is a subset of the other.
11801 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011802 if (CKind == OMPC_map)
11803 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11804 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011805 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011806 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11807 << ERange;
11808 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011809 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11810 << RE->getSourceRange();
11811 return true;
11812 }
11813
11814 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011815 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011816 if (!CurrentRegionOnly && SI != SE)
11817 EnclosingExpr = RE;
11818
11819 // The current expression is a subset of the expression in the data
11820 // environment.
11821 IsEnclosedByDataEnvironmentExpr |=
11822 (!CurrentRegionOnly && CI != CE && SI == SE);
11823
11824 return false;
11825 });
11826
11827 if (CurrentRegionOnly)
11828 return FoundError;
11829
11830 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11831 // If any part of the original storage of a list item has corresponding
11832 // storage in the device data environment, all of the original storage must
11833 // have corresponding storage in the device data environment.
11834 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11835 // If a list item is an element of a structure, and a different element of
11836 // the structure has a corresponding list item in the device data environment
11837 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011838 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011839 // data environment prior to the task encountering the construct.
11840 //
11841 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11842 SemaRef.Diag(ELoc,
11843 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11844 << ERange;
11845 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11846 << EnclosingExpr->getSourceRange();
11847 return true;
11848 }
11849
11850 return FoundError;
11851}
11852
Samuel Antao661c0902016-05-26 17:39:58 +000011853namespace {
11854// Utility struct that gathers all the related lists associated with a mappable
11855// expression.
11856struct MappableVarListInfo final {
11857 // The list of expressions.
11858 ArrayRef<Expr *> VarList;
11859 // The list of processed expressions.
11860 SmallVector<Expr *, 16> ProcessedVarList;
11861 // The mappble components for each expression.
11862 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11863 // The base declaration of the variable.
11864 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11865
11866 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11867 // We have a list of components and base declarations for each entry in the
11868 // variable list.
11869 VarComponents.reserve(VarList.size());
11870 VarBaseDeclarations.reserve(VarList.size());
11871 }
11872};
11873}
11874
11875// Check the validity of the provided variable list for the provided clause kind
11876// \a CKind. In the check process the valid expressions, and mappable expression
11877// components and variables are extracted and used to fill \a Vars,
11878// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11879// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11880static void
11881checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11882 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11883 SourceLocation StartLoc,
11884 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11885 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011886 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11887 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011888 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011889
Samuel Antao90927002016-04-26 14:54:23 +000011890 // Keep track of the mappable components and base declarations in this clause.
11891 // Each entry in the list is going to have a list of components associated. We
11892 // record each set of the components so that we can build the clause later on.
11893 // In the end we should have the same amount of declarations and component
11894 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011895
Samuel Antao661c0902016-05-26 17:39:58 +000011896 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011897 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011898 SourceLocation ELoc = RE->getExprLoc();
11899
Kelvin Li0bff7af2015-11-23 05:32:03 +000011900 auto *VE = RE->IgnoreParenLValueCasts();
11901
11902 if (VE->isValueDependent() || VE->isTypeDependent() ||
11903 VE->isInstantiationDependent() ||
11904 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011905 // We can only analyze this information once the missing information is
11906 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011907 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011908 continue;
11909 }
11910
11911 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011912
Samuel Antao5de996e2016-01-22 20:21:36 +000011913 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011914 SemaRef.Diag(ELoc,
11915 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011916 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011917 continue;
11918 }
11919
Samuel Antao90927002016-04-26 14:54:23 +000011920 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11921 ValueDecl *CurDeclaration = nullptr;
11922
11923 // Obtain the array or member expression bases if required. Also, fill the
11924 // components array with all the components identified in the process.
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011925 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
11926 CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000011927 if (!BE)
11928 continue;
11929
Samuel Antao90927002016-04-26 14:54:23 +000011930 assert(!CurComponents.empty() &&
11931 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011932
Samuel Antao90927002016-04-26 14:54:23 +000011933 // For the following checks, we rely on the base declaration which is
11934 // expected to be associated with the last component. The declaration is
11935 // expected to be a variable or a field (if 'this' is being mapped).
11936 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11937 assert(CurDeclaration && "Null decl on map clause.");
11938 assert(
11939 CurDeclaration->isCanonicalDecl() &&
11940 "Expecting components to have associated only canonical declarations.");
11941
11942 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11943 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011944
11945 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011946 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011947
11948 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011949 // threadprivate variables cannot appear in a map clause.
11950 // OpenMP 4.5 [2.10.5, target update Construct]
11951 // threadprivate variables cannot appear in a from clause.
11952 if (VD && DSAS->isThreadPrivate(VD)) {
11953 auto DVar = DSAS->getTopDSA(VD, false);
11954 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11955 << getOpenMPClauseName(CKind);
11956 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011957 continue;
11958 }
11959
Samuel Antao5de996e2016-01-22 20:21:36 +000011960 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11961 // A list item cannot appear in both a map clause and a data-sharing
11962 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011963
Samuel Antao5de996e2016-01-22 20:21:36 +000011964 // Check conflicts with other map clause expressions. We check the conflicts
11965 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011966 // environment, because the restrictions are different. We only have to
11967 // check conflicts across regions for the map clauses.
11968 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11969 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011970 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011971 if (CKind == OMPC_map &&
11972 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11973 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011974 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011975
Samuel Antao661c0902016-05-26 17:39:58 +000011976 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011977 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11978 // If the type of a list item is a reference to a type T then the type will
11979 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011980 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011981
Samuel Antao661c0902016-05-26 17:39:58 +000011982 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11983 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011984 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011985 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011986 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11987 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011988 continue;
11989
Samuel Antao661c0902016-05-26 17:39:58 +000011990 if (CKind == OMPC_map) {
11991 // target enter data
11992 // OpenMP [2.10.2, Restrictions, p. 99]
11993 // A map-type must be specified in all map clauses and must be either
11994 // to or alloc.
11995 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11996 if (DKind == OMPD_target_enter_data &&
11997 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11998 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11999 << (IsMapTypeImplicit ? 1 : 0)
12000 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12001 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012002 continue;
12003 }
Samuel Antao661c0902016-05-26 17:39:58 +000012004
12005 // target exit_data
12006 // OpenMP [2.10.3, Restrictions, p. 102]
12007 // A map-type must be specified in all map clauses and must be either
12008 // from, release, or delete.
12009 if (DKind == OMPD_target_exit_data &&
12010 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12011 MapType == OMPC_MAP_delete)) {
12012 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12013 << (IsMapTypeImplicit ? 1 : 0)
12014 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12015 << getOpenMPDirectiveName(DKind);
12016 continue;
12017 }
12018
12019 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12020 // A list item cannot appear in both a map clause and a data-sharing
12021 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000012022 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000012023 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000012024 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000012025 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12026 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000012027 auto DVar = DSAS->getTopDSA(VD, false);
12028 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012029 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012030 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012031 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012032 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12033 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12034 continue;
12035 }
12036 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012037 }
12038
Samuel Antao90927002016-04-26 14:54:23 +000012039 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012040 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012041
12042 // Store the components in the stack so that they can be used to check
12043 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012044 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12045 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012046
12047 // Save the components and declaration to create the clause. For purposes of
12048 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012049 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012050 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12051 MVLI.VarComponents.back().append(CurComponents.begin(),
12052 CurComponents.end());
12053 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12054 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012055 }
Samuel Antao661c0902016-05-26 17:39:58 +000012056}
12057
12058OMPClause *
12059Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12060 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12061 SourceLocation MapLoc, SourceLocation ColonLoc,
12062 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12063 SourceLocation LParenLoc, SourceLocation EndLoc) {
12064 MappableVarListInfo MVLI(VarList);
12065 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12066 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012067
Samuel Antao5de996e2016-01-22 20:21:36 +000012068 // We need to produce a map clause even if we don't have variables so that
12069 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012070 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12071 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12072 MVLI.VarComponents, MapTypeModifier, MapType,
12073 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012074}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012075
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012076QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12077 TypeResult ParsedType) {
12078 assert(ParsedType.isUsable());
12079
12080 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12081 if (ReductionType.isNull())
12082 return QualType();
12083
12084 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12085 // A type name in a declare reduction directive cannot be a function type, an
12086 // array type, a reference type, or a type qualified with const, volatile or
12087 // restrict.
12088 if (ReductionType.hasQualifiers()) {
12089 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12090 return QualType();
12091 }
12092
12093 if (ReductionType->isFunctionType()) {
12094 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12095 return QualType();
12096 }
12097 if (ReductionType->isReferenceType()) {
12098 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12099 return QualType();
12100 }
12101 if (ReductionType->isArrayType()) {
12102 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12103 return QualType();
12104 }
12105 return ReductionType;
12106}
12107
12108Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12109 Scope *S, DeclContext *DC, DeclarationName Name,
12110 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12111 AccessSpecifier AS, Decl *PrevDeclInScope) {
12112 SmallVector<Decl *, 8> Decls;
12113 Decls.reserve(ReductionTypes.size());
12114
12115 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012116 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012117 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12118 // A reduction-identifier may not be re-declared in the current scope for the
12119 // same type or for a type that is compatible according to the base language
12120 // rules.
12121 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12122 OMPDeclareReductionDecl *PrevDRD = nullptr;
12123 bool InCompoundScope = true;
12124 if (S != nullptr) {
12125 // Find previous declaration with the same name not referenced in other
12126 // declarations.
12127 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12128 InCompoundScope =
12129 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12130 LookupName(Lookup, S);
12131 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12132 /*AllowInlineNamespace=*/false);
12133 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12134 auto Filter = Lookup.makeFilter();
12135 while (Filter.hasNext()) {
12136 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12137 if (InCompoundScope) {
12138 auto I = UsedAsPrevious.find(PrevDecl);
12139 if (I == UsedAsPrevious.end())
12140 UsedAsPrevious[PrevDecl] = false;
12141 if (auto *D = PrevDecl->getPrevDeclInScope())
12142 UsedAsPrevious[D] = true;
12143 }
12144 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12145 PrevDecl->getLocation();
12146 }
12147 Filter.done();
12148 if (InCompoundScope) {
12149 for (auto &PrevData : UsedAsPrevious) {
12150 if (!PrevData.second) {
12151 PrevDRD = PrevData.first;
12152 break;
12153 }
12154 }
12155 }
12156 } else if (PrevDeclInScope != nullptr) {
12157 auto *PrevDRDInScope = PrevDRD =
12158 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12159 do {
12160 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12161 PrevDRDInScope->getLocation();
12162 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12163 } while (PrevDRDInScope != nullptr);
12164 }
12165 for (auto &TyData : ReductionTypes) {
12166 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12167 bool Invalid = false;
12168 if (I != PreviousRedeclTypes.end()) {
12169 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12170 << TyData.first;
12171 Diag(I->second, diag::note_previous_definition);
12172 Invalid = true;
12173 }
12174 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12175 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12176 Name, TyData.first, PrevDRD);
12177 DC->addDecl(DRD);
12178 DRD->setAccess(AS);
12179 Decls.push_back(DRD);
12180 if (Invalid)
12181 DRD->setInvalidDecl();
12182 else
12183 PrevDRD = DRD;
12184 }
12185
12186 return DeclGroupPtrTy::make(
12187 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12188}
12189
12190void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12191 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12192
12193 // Enter new function scope.
12194 PushFunctionScope();
12195 getCurFunction()->setHasBranchProtectedScope();
12196 getCurFunction()->setHasOMPDeclareReductionCombiner();
12197
12198 if (S != nullptr)
12199 PushDeclContext(S, DRD);
12200 else
12201 CurContext = DRD;
12202
Faisal Valid143a0c2017-04-01 21:30:49 +000012203 PushExpressionEvaluationContext(
12204 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012205
12206 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012207 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12208 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12209 // uses semantics of argument handles by value, but it should be passed by
12210 // reference. C lang does not support references, so pass all parameters as
12211 // pointers.
12212 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012213 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012214 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012215 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12216 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12217 // uses semantics of argument handles by value, but it should be passed by
12218 // reference. C lang does not support references, so pass all parameters as
12219 // pointers.
12220 // Create 'T omp_out;' variable.
12221 auto *OmpOutParm =
12222 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12223 if (S != nullptr) {
12224 PushOnScopeChains(OmpInParm, S);
12225 PushOnScopeChains(OmpOutParm, S);
12226 } else {
12227 DRD->addDecl(OmpInParm);
12228 DRD->addDecl(OmpOutParm);
12229 }
12230}
12231
12232void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12233 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12234 DiscardCleanupsInEvaluationContext();
12235 PopExpressionEvaluationContext();
12236
12237 PopDeclContext();
12238 PopFunctionScopeInfo();
12239
12240 if (Combiner != nullptr)
12241 DRD->setCombiner(Combiner);
12242 else
12243 DRD->setInvalidDecl();
12244}
12245
Alexey Bataev070f43a2017-09-06 14:49:58 +000012246VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012247 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12248
12249 // Enter new function scope.
12250 PushFunctionScope();
12251 getCurFunction()->setHasBranchProtectedScope();
12252
12253 if (S != nullptr)
12254 PushDeclContext(S, DRD);
12255 else
12256 CurContext = DRD;
12257
Faisal Valid143a0c2017-04-01 21:30:49 +000012258 PushExpressionEvaluationContext(
12259 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012260
12261 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012262 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12263 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12264 // uses semantics of argument handles by value, but it should be passed by
12265 // reference. C lang does not support references, so pass all parameters as
12266 // pointers.
12267 // Create 'T omp_priv;' variable.
12268 auto *OmpPrivParm =
12269 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012270 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12271 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12272 // uses semantics of argument handles by value, but it should be passed by
12273 // reference. C lang does not support references, so pass all parameters as
12274 // pointers.
12275 // Create 'T omp_orig;' variable.
12276 auto *OmpOrigParm =
12277 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012278 if (S != nullptr) {
12279 PushOnScopeChains(OmpPrivParm, S);
12280 PushOnScopeChains(OmpOrigParm, S);
12281 } else {
12282 DRD->addDecl(OmpPrivParm);
12283 DRD->addDecl(OmpOrigParm);
12284 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012285 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012286}
12287
Alexey Bataev070f43a2017-09-06 14:49:58 +000012288void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12289 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012290 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12291 DiscardCleanupsInEvaluationContext();
12292 PopExpressionEvaluationContext();
12293
12294 PopDeclContext();
12295 PopFunctionScopeInfo();
12296
Alexey Bataev070f43a2017-09-06 14:49:58 +000012297 if (Initializer != nullptr) {
12298 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12299 } else if (OmpPrivParm->hasInit()) {
12300 DRD->setInitializer(OmpPrivParm->getInit(),
12301 OmpPrivParm->isDirectInit()
12302 ? OMPDeclareReductionDecl::DirectInit
12303 : OMPDeclareReductionDecl::CopyInit);
12304 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012305 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012306 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012307}
12308
12309Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12310 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12311 for (auto *D : DeclReductions.get()) {
12312 if (IsValid) {
12313 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12314 if (S != nullptr)
12315 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12316 } else
12317 D->setInvalidDecl();
12318 }
12319 return DeclReductions;
12320}
12321
David Majnemer9d168222016-08-05 17:44:54 +000012322OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012323 SourceLocation StartLoc,
12324 SourceLocation LParenLoc,
12325 SourceLocation EndLoc) {
12326 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012327 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012328
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012329 // OpenMP [teams Constrcut, Restrictions]
12330 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012331 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12332 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012333 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012334
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012335 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012336 OpenMPDirectiveKind CaptureRegion =
12337 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12338 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012339 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12340 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12341 HelperValStmt = buildPreInits(Context, Captures);
12342 }
12343
12344 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12345 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012346}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012347
12348OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12349 SourceLocation StartLoc,
12350 SourceLocation LParenLoc,
12351 SourceLocation EndLoc) {
12352 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012353 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012354
12355 // OpenMP [teams Constrcut, Restrictions]
12356 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012357 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12358 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012359 return nullptr;
12360
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012361 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012362 OpenMPDirectiveKind CaptureRegion =
12363 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12364 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012365 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12366 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12367 HelperValStmt = buildPreInits(Context, Captures);
12368 }
12369
12370 return new (Context) OMPThreadLimitClause(
12371 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012372}
Alexey Bataeva0569352015-12-01 10:17:31 +000012373
12374OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12375 SourceLocation StartLoc,
12376 SourceLocation LParenLoc,
12377 SourceLocation EndLoc) {
12378 Expr *ValExpr = Priority;
12379
12380 // OpenMP [2.9.1, task Constrcut]
12381 // The priority-value is a non-negative numerical scalar expression.
12382 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12383 /*StrictlyPositive=*/false))
12384 return nullptr;
12385
12386 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12387}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012388
12389OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12390 SourceLocation StartLoc,
12391 SourceLocation LParenLoc,
12392 SourceLocation EndLoc) {
12393 Expr *ValExpr = Grainsize;
12394
12395 // OpenMP [2.9.2, taskloop Constrcut]
12396 // The parameter of the grainsize clause must be a positive integer
12397 // expression.
12398 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12399 /*StrictlyPositive=*/true))
12400 return nullptr;
12401
12402 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12403}
Alexey Bataev382967a2015-12-08 12:06:20 +000012404
12405OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12406 SourceLocation StartLoc,
12407 SourceLocation LParenLoc,
12408 SourceLocation EndLoc) {
12409 Expr *ValExpr = NumTasks;
12410
12411 // OpenMP [2.9.2, taskloop Constrcut]
12412 // The parameter of the num_tasks clause must be a positive integer
12413 // expression.
12414 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12415 /*StrictlyPositive=*/true))
12416 return nullptr;
12417
12418 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12419}
12420
Alexey Bataev28c75412015-12-15 08:19:24 +000012421OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12422 SourceLocation LParenLoc,
12423 SourceLocation EndLoc) {
12424 // OpenMP [2.13.2, critical construct, Description]
12425 // ... where hint-expression is an integer constant expression that evaluates
12426 // to a valid lock hint.
12427 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12428 if (HintExpr.isInvalid())
12429 return nullptr;
12430 return new (Context)
12431 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12432}
12433
Carlo Bertollib4adf552016-01-15 18:50:31 +000012434OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12435 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12436 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12437 SourceLocation EndLoc) {
12438 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12439 std::string Values;
12440 Values += "'";
12441 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12442 Values += "'";
12443 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12444 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12445 return nullptr;
12446 }
12447 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012448 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012449 if (ChunkSize) {
12450 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12451 !ChunkSize->isInstantiationDependent() &&
12452 !ChunkSize->containsUnexpandedParameterPack()) {
12453 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12454 ExprResult Val =
12455 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12456 if (Val.isInvalid())
12457 return nullptr;
12458
12459 ValExpr = Val.get();
12460
12461 // OpenMP [2.7.1, Restrictions]
12462 // chunk_size must be a loop invariant integer expression with a positive
12463 // value.
12464 llvm::APSInt Result;
12465 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12466 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12467 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12468 << "dist_schedule" << ChunkSize->getSourceRange();
12469 return nullptr;
12470 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012471 } else if (getOpenMPCaptureRegionForClause(
12472 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12473 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012474 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000012475 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12476 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12477 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012478 }
12479 }
12480 }
12481
12482 return new (Context)
12483 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012484 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012485}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012486
12487OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12488 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12489 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12490 SourceLocation KindLoc, SourceLocation EndLoc) {
12491 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012492 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012493 std::string Value;
12494 SourceLocation Loc;
12495 Value += "'";
12496 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12497 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012498 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012499 Loc = MLoc;
12500 } else {
12501 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012502 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012503 Loc = KindLoc;
12504 }
12505 Value += "'";
12506 Diag(Loc, diag::err_omp_unexpected_clause_value)
12507 << Value << getOpenMPClauseName(OMPC_defaultmap);
12508 return nullptr;
12509 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012510 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012511
12512 return new (Context)
12513 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12514}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012515
12516bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12517 DeclContext *CurLexicalContext = getCurLexicalContext();
12518 if (!CurLexicalContext->isFileContext() &&
12519 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012520 !CurLexicalContext->isExternCXXContext() &&
12521 !isa<CXXRecordDecl>(CurLexicalContext) &&
12522 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12523 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12524 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012525 Diag(Loc, diag::err_omp_region_not_file_context);
12526 return false;
12527 }
12528 if (IsInOpenMPDeclareTargetContext) {
12529 Diag(Loc, diag::err_omp_enclosed_declare_target);
12530 return false;
12531 }
12532
12533 IsInOpenMPDeclareTargetContext = true;
12534 return true;
12535}
12536
12537void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12538 assert(IsInOpenMPDeclareTargetContext &&
12539 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12540
12541 IsInOpenMPDeclareTargetContext = false;
12542}
12543
David Majnemer9d168222016-08-05 17:44:54 +000012544void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12545 CXXScopeSpec &ScopeSpec,
12546 const DeclarationNameInfo &Id,
12547 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12548 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012549 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12550 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12551
12552 if (Lookup.isAmbiguous())
12553 return;
12554 Lookup.suppressDiagnostics();
12555
12556 if (!Lookup.isSingleResult()) {
12557 if (TypoCorrection Corrected =
12558 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12559 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12560 CTK_ErrorRecovery)) {
12561 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12562 << Id.getName());
12563 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12564 return;
12565 }
12566
12567 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12568 return;
12569 }
12570
12571 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12572 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12573 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12574 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12575
12576 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12577 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12578 ND->addAttr(A);
12579 if (ASTMutationListener *ML = Context.getASTMutationListener())
12580 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12581 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12582 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12583 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12584 << Id.getName();
12585 }
12586 } else
12587 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12588}
12589
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012590static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12591 Sema &SemaRef, Decl *D) {
12592 if (!D)
12593 return;
12594 Decl *LD = nullptr;
12595 if (isa<TagDecl>(D)) {
12596 LD = cast<TagDecl>(D)->getDefinition();
12597 } else if (isa<VarDecl>(D)) {
12598 LD = cast<VarDecl>(D)->getDefinition();
12599
12600 // If this is an implicit variable that is legal and we do not need to do
12601 // anything.
12602 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012603 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12604 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12605 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012606 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012607 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012608 return;
12609 }
12610
12611 } else if (isa<FunctionDecl>(D)) {
12612 const FunctionDecl *FD = nullptr;
12613 if (cast<FunctionDecl>(D)->hasBody(FD))
12614 LD = const_cast<FunctionDecl *>(FD);
12615
12616 // If the definition is associated with the current declaration in the
12617 // target region (it can be e.g. a lambda) that is legal and we do not need
12618 // to do anything else.
12619 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012620 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12621 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12622 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012623 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012624 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012625 return;
12626 }
12627 }
12628 if (!LD)
12629 LD = D;
12630 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12631 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12632 // Outlined declaration is not declared target.
12633 if (LD->isOutOfLine()) {
12634 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12635 SemaRef.Diag(SL, diag::note_used_here) << SR;
12636 } else {
12637 DeclContext *DC = LD->getDeclContext();
12638 while (DC) {
12639 if (isa<FunctionDecl>(DC) &&
12640 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12641 break;
12642 DC = DC->getParent();
12643 }
12644 if (DC)
12645 return;
12646
12647 // Is not declared in target context.
12648 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12649 SemaRef.Diag(SL, diag::note_used_here) << SR;
12650 }
12651 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012652 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12653 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12654 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012655 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012656 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012657 }
12658}
12659
12660static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12661 Sema &SemaRef, DSAStackTy *Stack,
12662 ValueDecl *VD) {
12663 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12664 return true;
12665 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12666 return false;
12667 return true;
12668}
12669
12670void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12671 if (!D || D->isInvalidDecl())
12672 return;
12673 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12674 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12675 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12676 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12677 if (DSAStack->isThreadPrivate(VD)) {
12678 Diag(SL, diag::err_omp_threadprivate_in_target);
12679 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12680 return;
12681 }
12682 }
12683 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12684 // Problem if any with var declared with incomplete type will be reported
12685 // as normal, so no need to check it here.
12686 if ((E || !VD->getType()->isIncompleteType()) &&
12687 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12688 // Mark decl as declared target to prevent further diagnostic.
12689 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012690 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12691 Context, OMPDeclareTargetDeclAttr::MT_To);
12692 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012693 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012694 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012695 }
12696 return;
12697 }
12698 }
12699 if (!E) {
12700 // Checking declaration inside declare target region.
12701 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12702 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012703 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12704 Context, OMPDeclareTargetDeclAttr::MT_To);
12705 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012706 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012707 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012708 }
12709 return;
12710 }
12711 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12712}
Samuel Antao661c0902016-05-26 17:39:58 +000012713
12714OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12715 SourceLocation StartLoc,
12716 SourceLocation LParenLoc,
12717 SourceLocation EndLoc) {
12718 MappableVarListInfo MVLI(VarList);
12719 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12720 if (MVLI.ProcessedVarList.empty())
12721 return nullptr;
12722
12723 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12724 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12725 MVLI.VarComponents);
12726}
Samuel Antaoec172c62016-05-26 17:49:04 +000012727
12728OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12729 SourceLocation StartLoc,
12730 SourceLocation LParenLoc,
12731 SourceLocation EndLoc) {
12732 MappableVarListInfo MVLI(VarList);
12733 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12734 if (MVLI.ProcessedVarList.empty())
12735 return nullptr;
12736
12737 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12738 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12739 MVLI.VarComponents);
12740}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012741
12742OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12743 SourceLocation StartLoc,
12744 SourceLocation LParenLoc,
12745 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012746 MappableVarListInfo MVLI(VarList);
12747 SmallVector<Expr *, 8> PrivateCopies;
12748 SmallVector<Expr *, 8> Inits;
12749
Carlo Bertolli2404b172016-07-13 15:37:16 +000012750 for (auto &RefExpr : VarList) {
12751 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12752 SourceLocation ELoc;
12753 SourceRange ERange;
12754 Expr *SimpleRefExpr = RefExpr;
12755 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12756 if (Res.second) {
12757 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012758 MVLI.ProcessedVarList.push_back(RefExpr);
12759 PrivateCopies.push_back(nullptr);
12760 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012761 }
12762 ValueDecl *D = Res.first;
12763 if (!D)
12764 continue;
12765
12766 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012767 Type = Type.getNonReferenceType().getUnqualifiedType();
12768
12769 auto *VD = dyn_cast<VarDecl>(D);
12770
12771 // Item should be a pointer or reference to pointer.
12772 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012773 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12774 << 0 << RefExpr->getSourceRange();
12775 continue;
12776 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012777
12778 // Build the private variable and the expression that refers to it.
12779 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12780 D->hasAttrs() ? &D->getAttrs() : nullptr);
12781 if (VDPrivate->isInvalidDecl())
12782 continue;
12783
12784 CurContext->addDecl(VDPrivate);
12785 auto VDPrivateRefExpr = buildDeclRefExpr(
12786 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12787
12788 // Add temporary variable to initialize the private copy of the pointer.
12789 auto *VDInit =
12790 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12791 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12792 RefExpr->getExprLoc());
12793 AddInitializerToDecl(VDPrivate,
12794 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012795 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012796
12797 // If required, build a capture to implement the privatization initialized
12798 // with the current list item value.
12799 DeclRefExpr *Ref = nullptr;
12800 if (!VD)
12801 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12802 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12803 PrivateCopies.push_back(VDPrivateRefExpr);
12804 Inits.push_back(VDInitRefExpr);
12805
12806 // We need to add a data sharing attribute for this variable to make sure it
12807 // is correctly captured. A variable that shows up in a use_device_ptr has
12808 // similar properties of a first private variable.
12809 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12810
12811 // Create a mappable component for the list item. List items in this clause
12812 // only need a component.
12813 MVLI.VarBaseDeclarations.push_back(D);
12814 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12815 MVLI.VarComponents.back().push_back(
12816 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012817 }
12818
Samuel Antaocc10b852016-07-28 14:23:26 +000012819 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012820 return nullptr;
12821
Samuel Antaocc10b852016-07-28 14:23:26 +000012822 return OMPUseDevicePtrClause::Create(
12823 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12824 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012825}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012826
12827OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12828 SourceLocation StartLoc,
12829 SourceLocation LParenLoc,
12830 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012831 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012832 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012833 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012834 SourceLocation ELoc;
12835 SourceRange ERange;
12836 Expr *SimpleRefExpr = RefExpr;
12837 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12838 if (Res.second) {
12839 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012840 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012841 }
12842 ValueDecl *D = Res.first;
12843 if (!D)
12844 continue;
12845
12846 QualType Type = D->getType();
12847 // item should be a pointer or array or reference to pointer or array
12848 if (!Type.getNonReferenceType()->isPointerType() &&
12849 !Type.getNonReferenceType()->isArrayType()) {
12850 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12851 << 0 << RefExpr->getSourceRange();
12852 continue;
12853 }
Samuel Antao6890b092016-07-28 14:25:09 +000012854
12855 // Check if the declaration in the clause does not show up in any data
12856 // sharing attribute.
12857 auto DVar = DSAStack->getTopDSA(D, false);
12858 if (isOpenMPPrivate(DVar.CKind)) {
12859 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12860 << getOpenMPClauseName(DVar.CKind)
12861 << getOpenMPClauseName(OMPC_is_device_ptr)
12862 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12863 ReportOriginalDSA(*this, DSAStack, D, DVar);
12864 continue;
12865 }
12866
12867 Expr *ConflictExpr;
12868 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012869 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012870 [&ConflictExpr](
12871 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12872 OpenMPClauseKind) -> bool {
12873 ConflictExpr = R.front().getAssociatedExpression();
12874 return true;
12875 })) {
12876 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12877 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12878 << ConflictExpr->getSourceRange();
12879 continue;
12880 }
12881
12882 // Store the components in the stack so that they can be used to check
12883 // against other clauses later on.
12884 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12885 DSAStack->addMappableExpressionComponents(
12886 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12887
12888 // Record the expression we've just processed.
12889 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12890
12891 // Create a mappable component for the list item. List items in this clause
12892 // only need a component. We use a null declaration to signal fields in
12893 // 'this'.
12894 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12895 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12896 "Unexpected device pointer expression!");
12897 MVLI.VarBaseDeclarations.push_back(
12898 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12899 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12900 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012901 }
12902
Samuel Antao6890b092016-07-28 14:25:09 +000012903 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012904 return nullptr;
12905
Samuel Antao6890b092016-07-28 14:25:09 +000012906 return OMPIsDevicePtrClause::Create(
12907 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12908 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012909}