blob: bf89eb0b2f2664ac795ac8ed29e4f58c41174966 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataevf47c4b42017-09-26 13:47:31 +000038static Expr *CheckMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41 OpenMPClauseKind CKind);
42
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
44/// \brief Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000046 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000048 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// \brief Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000059class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000061 struct DSAVarData final {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataevf189cb72017-07-24 14:52:13 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataev8b427062016-05-25 12:36:08 +000073 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000075
Alexey Bataev758e55e2013-09-06 18:03:48 +000076private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000077 struct DSAInfo final {
78 OpenMPClauseKind Attributes = OMPC_unknown;
79 /// Pointer to a reference expression and a flag which shows that the
80 /// variable is marked as lastprivate(true) or not (false).
81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000083 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000084 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000086 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000088 /// Struct that associates a component with the clause kind where they are
89 /// found.
90 struct MappedExprComponentTy {
91 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92 OpenMPClauseKind Kind = OMPC_unknown;
93 };
94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000095 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000096 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000098 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +0000101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000115
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000116 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000117 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000118 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000119 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000120 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000121 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000123 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000127 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000129 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131 /// get the data (loop counters etc.) about enclosing loop-based construct.
132 /// This data is required during codegen.
133 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000134 /// \brief first argument (Expr *) contains optional argument of the
135 /// 'ordered' clause, the second one is true if the regions has 'ordered'
136 /// clause, false otherwise.
137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000138 bool NowaitRegion = false;
139 bool CancelRegion = false;
140 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000141 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000142 /// Reference to the taskgroup task_reduction reference expression.
143 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000145 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000148 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 };
150
Axel Naumann323862e2016-02-03 10:45:22 +0000151 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152
153 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000154 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000157 /// \brief true, if check for DSA must be from parent directive, false, if
158 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000159 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000160 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000161 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000162 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165
David Majnemer9d168222016-08-05 17:44:54 +0000166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000167
168 /// \brief Checks if the variable is a local for OpenMP region.
169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000170
Alexey Bataev4b465392017-04-26 15:06:24 +0000171 bool isStackEmpty() const {
172 return Stack.empty() ||
173 Stack.back().second != CurrentNonCapturingFunctionScope ||
174 Stack.back().first.empty();
175 }
176
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000178 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000179
Alexey Bataevaac108a2015-06-23 04:51:00 +0000180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
181 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000183 bool isForceVarCapturing() const { return ForceCapturing; }
184 void setForceVarCapturing(bool V) { ForceCapturing = V; }
185
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000187 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000188 if (Stack.empty() ||
189 Stack.back().second != CurrentNonCapturingFunctionScope)
190 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
191 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
192 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000193 }
194
195 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000196 assert(!Stack.back().first.empty() &&
197 "Data-sharing attributes stack is empty!");
198 Stack.back().first.pop_back();
199 }
200
201 /// Start new OpenMP region stack in new non-capturing function.
202 void pushFunction() {
203 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
204 assert(!isa<CapturingScopeInfo>(CurFnScope));
205 CurrentNonCapturingFunctionScope = CurFnScope;
206 }
207 /// Pop region stack for non-capturing function.
208 void popFunction(const FunctionScopeInfo *OldFSI) {
209 if (!Stack.empty() && Stack.back().second == OldFSI) {
210 assert(Stack.back().first.empty());
211 Stack.pop_back();
212 }
213 CurrentNonCapturingFunctionScope = nullptr;
214 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
215 if (!isa<CapturingScopeInfo>(FSI)) {
216 CurrentNonCapturingFunctionScope = FSI;
217 break;
218 }
219 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220 }
221
Alexey Bataev28c75412015-12-15 08:19:24 +0000222 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
223 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
224 }
225 const std::pair<OMPCriticalDirective *, llvm::APSInt>
226 getCriticalWithHint(const DeclarationNameInfo &Name) const {
227 auto I = Criticals.find(Name.getAsString());
228 if (I != Criticals.end())
229 return I->second;
230 return std::make_pair(nullptr, llvm::APSInt());
231 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000232 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000233 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000234 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000235 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000236
Alexey Bataev9c821032015-04-30 04:23:23 +0000237 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000238 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000239 /// \brief Check if the specified variable is a loop control variable for
240 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000241 /// \return The index of the loop control variable in the list of associated
242 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000243 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000244 /// \brief Check if the specified variable is a loop control variable for
245 /// parent region.
246 /// \return The index of the loop control variable in the list of associated
247 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000248 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000249 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
250 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000251 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000252
Alexey Bataev758e55e2013-09-06 18:03:48 +0000253 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000254 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
255 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256
Alexey Bataevfa312f32017-07-21 18:48:21 +0000257 /// Adds additional information for the reduction items with the reduction id
258 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000259 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
260 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000261 /// Adds additional information for the reduction items with the reduction id
262 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000265 /// Returns the location and reduction operation from the innermost parent
266 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000267 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000268 BinaryOperatorKind &BOK,
269 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000270 /// Returns the location and reduction operation from the innermost parent
271 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000272 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000273 const Expr *&ReductionRef,
274 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000275 /// Return reduction reference expression for the current taskgroup.
276 Expr *getTaskgroupReductionRef() const {
277 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
278 "taskgroup reference expression requested for non taskgroup "
279 "directive.");
280 return Stack.back().first.back().TaskgroupReductionRef;
281 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000282 /// Checks if the given \p VD declaration is actually a taskgroup reduction
283 /// descriptor variable at the \p Level of OpenMP regions.
284 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
285 return Stack.back().first[Level].TaskgroupReductionRef &&
286 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
287 ->getDecl() == VD;
288 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000289
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 /// \brief Returns data sharing attributes from top of the stack for the
291 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000292 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000293 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000294 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000295 /// \brief Checks if the specified variables has data-sharing attributes which
296 /// match specified \a CPred predicate in any directive which matches \a DPred
297 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000298 DSAVarData hasDSA(ValueDecl *D,
299 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
300 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
301 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000302 /// \brief Checks if the specified variables has data-sharing attributes which
303 /// match specified \a CPred predicate in any innermost directive which
304 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000305 DSAVarData
306 hasInnermostDSA(ValueDecl *D,
307 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
308 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
309 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000310 /// \brief Checks if the specified variables has explicit data-sharing
311 /// attributes which match specified \a CPred predicate at the specified
312 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000313 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000314 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000315 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000316
317 /// \brief Returns true if the directive at level \Level matches in the
318 /// specified \a DPred predicate.
319 bool hasExplicitDirective(
320 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
321 unsigned Level);
322
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000323 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000324 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
325 const DeclarationNameInfo &,
326 SourceLocation)> &DPred,
327 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000328
Alexey Bataev758e55e2013-09-06 18:03:48 +0000329 /// \brief Returns currently analyzed directive.
330 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000331 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000332 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000333 /// \brief Returns parent directive.
334 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 if (isStackEmpty() || Stack.back().first.size() == 1)
336 return OMPD_unknown;
337 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000338 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000339
340 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000341 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000342 assert(!isStackEmpty());
343 Stack.back().first.back().DefaultAttr = DSA_none;
344 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000345 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000346 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000347 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000348 assert(!isStackEmpty());
349 Stack.back().first.back().DefaultAttr = DSA_shared;
350 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000351 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000352 /// Set default data mapping attribute to 'tofrom:scalar'.
353 void setDefaultDMAToFromScalar(SourceLocation Loc) {
354 assert(!isStackEmpty());
355 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
356 Stack.back().first.back().DefaultMapAttrLoc = Loc;
357 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000358
359 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000360 return isStackEmpty() ? DSA_unspecified
361 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000362 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000363 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000364 return isStackEmpty() ? SourceLocation()
365 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000366 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000367 DefaultMapAttributes getDefaultDMA() const {
368 return isStackEmpty() ? DMA_unspecified
369 : Stack.back().first.back().DefaultMapAttr;
370 }
371 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
372 return Stack.back().first[Level].DefaultMapAttr;
373 }
374 SourceLocation getDefaultDMALocation() const {
375 return isStackEmpty() ? SourceLocation()
376 : Stack.back().first.back().DefaultMapAttrLoc;
377 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000378
Alexey Bataevf29276e2014-06-18 04:14:57 +0000379 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000380 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000381 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000382 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000383 }
384
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000385 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000386 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000387 assert(!isStackEmpty());
388 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
389 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000390 }
391 /// \brief Returns true, if parent region is ordered (has associated
392 /// 'ordered' clause), false - otherwise.
393 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000394 if (isStackEmpty() || Stack.back().first.size() == 1)
395 return false;
396 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000397 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000398 /// \brief Returns optional parameter for the ordered region.
399 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000400 if (isStackEmpty() || Stack.back().first.size() == 1)
401 return nullptr;
402 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000403 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000404 /// \brief Marks current region as nowait (it has a 'nowait' clause).
405 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000406 assert(!isStackEmpty());
407 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000408 }
409 /// \brief Returns true, if parent region is nowait (has associated
410 /// 'nowait' clause), false - otherwise.
411 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000412 if (isStackEmpty() || Stack.back().first.size() == 1)
413 return false;
414 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000415 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000416 /// \brief Marks parent region as cancel region.
417 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000418 if (!isStackEmpty() && Stack.back().first.size() > 1) {
419 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
420 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
421 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000422 }
423 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000424 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000425 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000426 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000427
Alexey Bataev9c821032015-04-30 04:23:23 +0000428 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000429 void setAssociatedLoops(unsigned Val) {
430 assert(!isStackEmpty());
431 Stack.back().first.back().AssociatedLoops = Val;
432 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000433 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000434 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000435 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000436 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000437
Alexey Bataev13314bf2014-10-09 04:18:56 +0000438 /// \brief Marks current target region as one with closely nested teams
439 /// region.
440 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000441 if (!isStackEmpty() && Stack.back().first.size() > 1) {
442 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
443 TeamsRegionLoc;
444 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000445 }
446 /// \brief Returns true, if current region has closely nested teams region.
447 bool hasInnerTeamsRegion() const {
448 return getInnerTeamsRegionLoc().isValid();
449 }
450 /// \brief Returns location of the nested teams region (if any).
451 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000452 return isStackEmpty() ? SourceLocation()
453 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000454 }
455
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000456 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000457 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000458 }
459 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000460 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000461 }
462 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000463 return isStackEmpty() ? SourceLocation()
464 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000465 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000466
Samuel Antao4c8035b2016-12-12 18:00:20 +0000467 /// Do the check specified in \a Check to all component lists and return true
468 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000469 bool checkMappableExprComponentListsForDecl(
470 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000471 const llvm::function_ref<
472 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
473 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000474 if (isStackEmpty())
475 return false;
476 auto SI = Stack.back().first.rbegin();
477 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000478
479 if (SI == SE)
480 return false;
481
482 if (CurrentRegionOnly) {
483 SE = std::next(SI);
484 } else {
485 ++SI;
486 }
487
488 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000489 auto MI = SI->MappedExprComponents.find(VD);
490 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000491 for (auto &L : MI->second.Components)
492 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000493 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000494 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000495 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000496 }
497
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000498 /// Do the check specified in \a Check to all component lists at a given level
499 /// and return true if any issue is found.
500 bool checkMappableExprComponentListsForDeclAtLevel(
501 ValueDecl *VD, unsigned Level,
502 const llvm::function_ref<
503 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
504 OpenMPClauseKind)> &Check) {
505 if (isStackEmpty())
506 return false;
507
508 auto StartI = Stack.back().first.begin();
509 auto EndI = Stack.back().first.end();
510 if (std::distance(StartI, EndI) <= (int)Level)
511 return false;
512 std::advance(StartI, Level);
513
514 auto MI = StartI->MappedExprComponents.find(VD);
515 if (MI != StartI->MappedExprComponents.end())
516 for (auto &L : MI->second.Components)
517 if (Check(L, MI->second.Kind))
518 return true;
519 return false;
520 }
521
Samuel Antao4c8035b2016-12-12 18:00:20 +0000522 /// Create a new mappable expression component list associated with a given
523 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000524 void addMappableExpressionComponents(
525 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000526 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
527 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000528 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000529 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000530 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000531 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000532 MEC.Components.resize(MEC.Components.size() + 1);
533 MEC.Components.back().append(Components.begin(), Components.end());
534 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000535 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000536
537 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000538 assert(!isStackEmpty());
539 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000540 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000541 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000542 assert(!isStackEmpty() && Stack.back().first.size() > 1);
543 auto &StackElem = *std::next(Stack.back().first.rbegin());
544 assert(isOpenMPWorksharingDirective(StackElem.Directive));
545 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000546 }
547 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
548 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000549 assert(!isStackEmpty());
550 auto &StackElem = Stack.back().first.back();
551 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
552 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000553 return llvm::make_range(Ref.begin(), Ref.end());
554 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000555 return llvm::make_range(StackElem.DoacrossDepends.end(),
556 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000557 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000558};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000559bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000560 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
561 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000562}
Alexey Bataeved09d242014-05-28 05:53:51 +0000563} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000564
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000565static Expr *getExprAsWritten(Expr *E) {
566 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
567 E = ExprTemp->getSubExpr();
568
569 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
570 E = MTE->GetTemporaryExpr();
571
572 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
573 E = Binder->getSubExpr();
574
575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
576 E = ICE->getSubExprAsWritten();
577 return E->IgnoreParens();
578}
579
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000581 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
582 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
583 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000584 auto *VD = dyn_cast<VarDecl>(D);
585 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000586 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000587 VD = VD->getCanonicalDecl();
588 D = VD;
589 } else {
590 assert(FD);
591 FD = FD->getCanonicalDecl();
592 D = FD;
593 }
594 return D;
595}
596
David Majnemer9d168222016-08-05 17:44:54 +0000597DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000598 ValueDecl *D) {
599 D = getCanonicalDecl(D);
600 auto *VD = dyn_cast<VarDecl>(D);
601 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000602 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000603 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000604 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
605 // in a region but not in construct]
606 // File-scope or namespace-scope variables referenced in called routines
607 // in the region are shared unless they appear in a threadprivate
608 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000609 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000610 DVar.CKind = OMPC_shared;
611
612 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
613 // in a region but not in construct]
614 // Variables with static storage duration that are declared in called
615 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000616 if (VD && VD->hasGlobalStorage())
617 DVar.CKind = OMPC_shared;
618
619 // Non-static data members are shared by default.
620 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000621 DVar.CKind = OMPC_shared;
622
Alexey Bataev758e55e2013-09-06 18:03:48 +0000623 return DVar;
624 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000625
Alexey Bataevec3da872014-01-31 05:15:34 +0000626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
627 // in a Construct, C/C++, predetermined, p.1]
628 // Variables with automatic storage duration that are declared in a scope
629 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000630 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
631 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000632 DVar.CKind = OMPC_private;
633 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000634 }
635
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000636 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000637 // Explicitly specified attributes and local variables with predetermined
638 // attributes.
639 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000640 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000641 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000642 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000643 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000644 return DVar;
645 }
646
647 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
648 // in a Construct, C/C++, implicitly determined, p.1]
649 // In a parallel or task construct, the data-sharing attributes of these
650 // variables are determined by the default clause, if present.
651 switch (Iter->DefaultAttr) {
652 case DSA_shared:
653 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000654 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000655 return DVar;
656 case DSA_none:
657 return DVar;
658 case DSA_unspecified:
659 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
660 // in a Construct, implicitly determined, p.2]
661 // In a parallel construct, if no default clause is present, these
662 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000664 if (isOpenMPParallelDirective(DVar.DKind) ||
665 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000666 DVar.CKind = OMPC_shared;
667 return DVar;
668 }
669
670 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
671 // in a Construct, implicitly determined, p.4]
672 // In a task construct, if no default clause is present, a variable that in
673 // the enclosing context is determined to be shared by all implicit tasks
674 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000675 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000676 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000677 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000678 do {
679 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000681 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000682 // In a task construct, if no default clause is present, a variable
683 // whose data-sharing attribute is not determined by the rules above is
684 // firstprivate.
685 DVarTemp = getDSA(I, D);
686 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000687 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000688 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000689 return DVar;
690 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000691 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000692 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000693 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 return DVar;
695 }
696 }
697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
698 // in a Construct, implicitly determined, p.3]
699 // For constructs other than task, if no default clause is present, these
700 // variables inherit their data-sharing attributes from the enclosing
701 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000702 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000703}
704
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000705Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000706 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000707 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000708 auto &StackElem = Stack.back().first.back();
709 auto It = StackElem.AlignedMap.find(D);
710 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000711 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000712 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000713 return nullptr;
714 } else {
715 assert(It->second && "Unexpected nullptr expr in the aligned map");
716 return It->second;
717 }
718 return nullptr;
719}
720
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000721void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000722 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000723 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000724 auto &StackElem = Stack.back().first.back();
725 StackElem.LCVMap.insert(
726 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000727}
728
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000729DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000730 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000731 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000732 auto &StackElem = Stack.back().first.back();
733 auto It = StackElem.LCVMap.find(D);
734 if (It != StackElem.LCVMap.end())
735 return It->second;
736 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000737}
738
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000739DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000740 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
741 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000742 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000743 auto &StackElem = *std::next(Stack.back().first.rbegin());
744 auto It = StackElem.LCVMap.find(D);
745 if (It != StackElem.LCVMap.end())
746 return It->second;
747 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000748}
749
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000750ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000751 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
752 "Data-sharing attributes stack is empty");
753 auto &StackElem = *std::next(Stack.back().first.rbegin());
754 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000755 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000756 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000757 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000758 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000759 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000760}
761
Alexey Bataev90c228f2016-02-08 09:29:13 +0000762void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
763 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000764 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000765 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000766 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000767 Data.Attributes = A;
768 Data.RefExpr.setPointer(E);
769 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000771 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
772 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
774 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
775 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
776 (isLoopControlVariable(D).first && A == OMPC_private));
777 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
778 Data.RefExpr.setInt(/*IntVal=*/true);
779 return;
780 }
781 const bool IsLastprivate =
782 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
783 Data.Attributes = A;
784 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
785 Data.PrivateCopy = PrivateCopy;
786 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000787 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000788 Data.Attributes = A;
789 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
790 Data.PrivateCopy = nullptr;
791 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000792 }
793}
794
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000795/// \brief Build a variable declaration for OpenMP loop iteration variable.
796static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
797 StringRef Name, const AttrVec *Attrs = nullptr) {
798 DeclContext *DC = SemaRef.CurContext;
799 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
800 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
801 VarDecl *Decl =
802 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
803 if (Attrs) {
804 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
805 I != E; ++I)
806 Decl->addAttr(*I);
807 }
808 Decl->setImplicit();
809 return Decl;
810}
811
812static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
813 SourceLocation Loc,
814 bool RefersToCapture = false) {
815 D->setReferenced();
816 D->markUsed(S.Context);
817 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
818 SourceLocation(), D, RefersToCapture, Loc, Ty,
819 VK_LValue);
820}
821
822void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
823 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000824 D = getCanonicalDecl(D);
825 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000826 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000827 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000828 "Additional reduction info may be specified only for reduction items.");
829 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
830 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000831 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000832 "Additional reduction info may be specified only once for reduction "
833 "items.");
834 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000835 Expr *&TaskgroupReductionRef =
836 Stack.back().first.back().TaskgroupReductionRef;
837 if (!TaskgroupReductionRef) {
838 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
839 SemaRef.Context.VoidPtrTy, ".task_red.");
840 TaskgroupReductionRef = buildDeclRefExpr(
841 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
842 }
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) {
861 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
862 SemaRef.Context.VoidPtrTy, ".task_red.");
863 TaskgroupReductionRef = buildDeclRefExpr(
864 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
865 }
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;
969 }
970
Alexey Bataev4b465392017-04-26 15:06:24 +0000971 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000972 // Not in OpenMP execution region and top scope was already checked.
973 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000974
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000976 // in a Construct, C/C++, predetermined, p.4]
977 // Static data members are shared.
978 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
979 // in a Construct, C/C++, predetermined, p.7]
980 // Variables with static storage duration that are declared in a scope
981 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000982 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000983 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000984 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000985 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000986 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000987
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000988 DVar.CKind = OMPC_shared;
989 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000990 }
991
992 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000993 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
994 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
996 // in a Construct, C/C++, predetermined, p.6]
997 // Variables with const qualified type having no mutable member are
998 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000999 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001000 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001001 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1002 if (auto *CTD = CTSD->getSpecializedTemplate())
1003 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001004 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001005 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1006 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001007 // Variables with const-qualified type having no mutable member may be
1008 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001009 DSAVarData DVarTemp = hasDSA(
1010 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1011 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001012 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1013 return DVar;
1014
Alexey Bataev758e55e2013-09-06 18:03:48 +00001015 DVar.CKind = OMPC_shared;
1016 return DVar;
1017 }
1018
Alexey Bataev758e55e2013-09-06 18:03:48 +00001019 // Explicitly specified attributes and local variables with predetermined
1020 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001021 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001022 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001023 if (FromParent && I != EndI)
1024 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001025 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001026 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001027 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001028 DVar.CKind = I->SharingMap[D].Attributes;
1029 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001030 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001031 }
1032
1033 return DVar;
1034}
1035
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001036DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1037 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001038 if (isStackEmpty()) {
1039 StackTy::reverse_iterator I;
1040 return getDSA(I, D);
1041 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001042 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001043 auto StartI = Stack.back().first.rbegin();
1044 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001045 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001046 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001047 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048}
1049
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001050DSAStackTy::DSAVarData
1051DSAStackTy::hasDSA(ValueDecl *D,
1052 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1053 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1054 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001055 if (isStackEmpty())
1056 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001057 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001058 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001059 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001060 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001061 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001062 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001063 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001064 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001065 auto NewI = I;
1066 DSAVarData DVar = getDSA(NewI, D);
1067 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001068 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001069 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001070 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001071}
1072
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001073DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1074 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1075 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1076 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001077 if (isStackEmpty())
1078 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001079 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001080 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001081 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001082 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001083 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001084 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001085 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001086 auto NewI = StartI;
1087 DSAVarData DVar = getDSA(NewI, D);
1088 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001089}
1090
Alexey Bataevaac108a2015-06-23 04:51:00 +00001091bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001092 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001093 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001094 if (CPred(ClauseKindMode))
1095 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001096 if (isStackEmpty())
1097 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001098 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001099 auto StartI = Stack.back().first.begin();
1100 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001101 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001102 return false;
1103 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001104 return (StartI->SharingMap.count(D) > 0) &&
1105 StartI->SharingMap[D].RefExpr.getPointer() &&
1106 CPred(StartI->SharingMap[D].Attributes) &&
1107 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001108}
1109
Samuel Antao4be30e92015-10-02 17:14:03 +00001110bool DSAStackTy::hasExplicitDirective(
1111 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1112 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001113 if (isStackEmpty())
1114 return false;
1115 auto StartI = Stack.back().first.begin();
1116 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001117 if (std::distance(StartI, EndI) <= (int)Level)
1118 return false;
1119 std::advance(StartI, Level);
1120 return DPred(StartI->Directive);
1121}
1122
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001123bool DSAStackTy::hasDirective(
1124 const llvm::function_ref<bool(OpenMPDirectiveKind,
1125 const DeclarationNameInfo &, SourceLocation)>
1126 &DPred,
1127 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001128 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001129 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001130 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001131 auto StartI = std::next(Stack.back().first.rbegin());
1132 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001133 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001134 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001135 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1136 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1137 return true;
1138 }
1139 return false;
1140}
1141
Alexey Bataev758e55e2013-09-06 18:03:48 +00001142void Sema::InitDataSharingAttributesStack() {
1143 VarDataSharingAttributesStack = new DSAStackTy(*this);
1144}
1145
1146#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1147
Alexey Bataev4b465392017-04-26 15:06:24 +00001148void Sema::pushOpenMPFunctionRegion() {
1149 DSAStack->pushFunction();
1150}
1151
1152void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1153 DSAStack->popFunction(OldFSI);
1154}
1155
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001156bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001157 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1158
1159 auto &Ctx = getASTContext();
1160 bool IsByRef = true;
1161
1162 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001163 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001164 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001165
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001166 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001167 // This table summarizes how a given variable should be passed to the device
1168 // given its type and the clauses where it appears. This table is based on
1169 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1170 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1171 //
1172 // =========================================================================
1173 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1174 // | |(tofrom:scalar)| | pvt | | | |
1175 // =========================================================================
1176 // | scl | | | | - | | bycopy|
1177 // | scl | | - | x | - | - | bycopy|
1178 // | scl | | x | - | - | - | null |
1179 // | scl | x | | | - | | byref |
1180 // | scl | x | - | x | - | - | bycopy|
1181 // | scl | x | x | - | - | - | null |
1182 // | scl | | - | - | - | x | byref |
1183 // | scl | x | - | - | - | x | byref |
1184 //
1185 // | agg | n.a. | | | - | | byref |
1186 // | agg | n.a. | - | x | - | - | byref |
1187 // | agg | n.a. | x | - | - | - | null |
1188 // | agg | n.a. | - | - | - | x | byref |
1189 // | agg | n.a. | - | - | - | x[] | byref |
1190 //
1191 // | ptr | n.a. | | | - | | bycopy|
1192 // | ptr | n.a. | - | x | - | - | bycopy|
1193 // | ptr | n.a. | x | - | - | - | null |
1194 // | ptr | n.a. | - | - | - | x | byref |
1195 // | ptr | n.a. | - | - | - | x[] | bycopy|
1196 // | ptr | n.a. | - | - | x | | bycopy|
1197 // | ptr | n.a. | - | - | x | x | bycopy|
1198 // | ptr | n.a. | - | - | x | x[] | bycopy|
1199 // =========================================================================
1200 // Legend:
1201 // scl - scalar
1202 // ptr - pointer
1203 // agg - aggregate
1204 // x - applies
1205 // - - invalid in this combination
1206 // [] - mapped with an array section
1207 // byref - should be mapped by reference
1208 // byval - should be mapped by value
1209 // null - initialize a local variable to null on the device
1210 //
1211 // Observations:
1212 // - All scalar declarations that show up in a map clause have to be passed
1213 // by reference, because they may have been mapped in the enclosing data
1214 // environment.
1215 // - If the scalar value does not fit the size of uintptr, it has to be
1216 // passed by reference, regardless the result in the table above.
1217 // - For pointers mapped by value that have either an implicit map or an
1218 // array section, the runtime library may pass the NULL value to the
1219 // device instead of the value passed to it by the compiler.
1220
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001221 if (Ty->isReferenceType())
1222 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001223
1224 // Locate map clauses and see if the variable being captured is referred to
1225 // in any of those clauses. Here we only care about variables, not fields,
1226 // because fields are part of aggregates.
1227 bool IsVariableUsedInMapClause = false;
1228 bool IsVariableAssociatedWithSection = false;
1229
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001230 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1231 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001232 MapExprComponents,
1233 OpenMPClauseKind WhereFoundClauseKind) {
1234 // Only the map clause information influences how a variable is
1235 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001236 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001237 if (WhereFoundClauseKind != OMPC_map)
1238 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001239
1240 auto EI = MapExprComponents.rbegin();
1241 auto EE = MapExprComponents.rend();
1242
1243 assert(EI != EE && "Invalid map expression!");
1244
1245 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1246 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1247
1248 ++EI;
1249 if (EI == EE)
1250 return false;
1251
1252 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1253 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1254 isa<MemberExpr>(EI->getAssociatedExpression())) {
1255 IsVariableAssociatedWithSection = true;
1256 // There is nothing more we need to know about this variable.
1257 return true;
1258 }
1259
1260 // Keep looking for more map info.
1261 return false;
1262 });
1263
1264 if (IsVariableUsedInMapClause) {
1265 // If variable is identified in a map clause it is always captured by
1266 // reference except if it is a pointer that is dereferenced somehow.
1267 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1268 } else {
1269 // By default, all the data that has a scalar type is mapped by copy.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001270 IsByRef = !Ty->isScalarType() ||
1271 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
Samuel Antao86ace552016-04-27 22:40:57 +00001272 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001273 }
1274
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001275 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1276 IsByRef = !DSAStack->hasExplicitDSA(
1277 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1278 Level, /*NotLastprivate=*/true);
1279 }
1280
Samuel Antao86ace552016-04-27 22:40:57 +00001281 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001282 // and alignment, because the runtime library only deals with uintptr types.
1283 // If it does not fit the uintptr size, we need to pass the data by reference
1284 // instead.
1285 if (!IsByRef &&
1286 (Ctx.getTypeSizeInChars(Ty) >
1287 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001288 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001289 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001290 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001291
1292 return IsByRef;
1293}
1294
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001295unsigned Sema::getOpenMPNestingLevel() const {
1296 assert(getLangOpts().OpenMP);
1297 return DSAStack->getNestingLevel();
1298}
1299
Alexey Bataev90c228f2016-02-08 09:29:13 +00001300VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001301 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001302 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001303
1304 // If we are attempting to capture a global variable in a directive with
1305 // 'target' we return true so that this global is also mapped to the device.
1306 //
1307 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1308 // then it should not be captured. Therefore, an extra check has to be
1309 // inserted here once support for 'declare target' is added.
1310 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001311 auto *VD = dyn_cast<VarDecl>(D);
1312 if (VD && !VD->hasLocalStorage()) {
Alexey Bataev61498fb2017-08-29 19:30:57 +00001313 if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001314 !DSAStack->isClauseParsingMode())
1315 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001316 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001317 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1318 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001319 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001320 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001321 false))
1322 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001323 }
1324
Alexey Bataev48977c32015-08-04 08:10:48 +00001325 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1326 (!DSAStack->isClauseParsingMode() ||
1327 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001328 auto &&Info = DSAStack->isLoopControlVariable(D);
1329 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001330 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001331 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001332 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001333 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001334 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001335 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001336 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001337 DVarPrivate = DSAStack->hasDSA(
1338 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1339 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001340 if (DVarPrivate.CKind != OMPC_unknown)
1341 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001342 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001343 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001344}
1345
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001346bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001347 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1348 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001349 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1350 Level) ||
1351 // Consider taskgroup reduction descriptor variable a private to avoid
1352 // possible capture in the region.
1353 (DSAStack->hasExplicitDirective(
1354 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1355 Level) &&
1356 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001357}
1358
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001359void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1360 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1361 D = getCanonicalDecl(D);
1362 OpenMPClauseKind OMPC = OMPC_unknown;
1363 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1364 const unsigned NewLevel = I - 1;
1365 if (DSAStack->hasExplicitDSA(D,
1366 [&OMPC](const OpenMPClauseKind K) {
1367 if (isOpenMPPrivate(K)) {
1368 OMPC = K;
1369 return true;
1370 }
1371 return false;
1372 },
1373 NewLevel))
1374 break;
1375 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1376 D, NewLevel,
1377 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1378 OpenMPClauseKind) { return true; })) {
1379 OMPC = OMPC_map;
1380 break;
1381 }
1382 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1383 NewLevel)) {
1384 OMPC = OMPC_firstprivate;
1385 break;
1386 }
1387 }
1388 if (OMPC != OMPC_unknown)
1389 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1390}
1391
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001392bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001393 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1394 // Return true if the current level is no longer enclosed in a target region.
1395
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001396 auto *VD = dyn_cast<VarDecl>(D);
1397 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001398 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1399 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001400}
1401
Alexey Bataeved09d242014-05-28 05:53:51 +00001402void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001403
1404void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1405 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001406 Scope *CurScope, SourceLocation Loc) {
1407 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001408 PushExpressionEvaluationContext(
1409 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001410}
1411
Alexey Bataevaac108a2015-06-23 04:51:00 +00001412void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1413 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001414}
1415
Alexey Bataevaac108a2015-06-23 04:51:00 +00001416void Sema::EndOpenMPClause() {
1417 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001418}
1419
Alexey Bataev758e55e2013-09-06 18:03:48 +00001420void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001421 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1422 // A variable of class type (or array thereof) that appears in a lastprivate
1423 // clause requires an accessible, unambiguous default constructor for the
1424 // class type, unless the list item is also specified in a firstprivate
1425 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001426 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001427 for (auto *C : D->clauses()) {
1428 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1429 SmallVector<Expr *, 8> PrivateCopies;
1430 for (auto *DE : Clause->varlists()) {
1431 if (DE->isValueDependent() || DE->isTypeDependent()) {
1432 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001433 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001434 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001435 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001436 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1437 QualType Type = VD->getType().getNonReferenceType();
1438 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001439 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001440 // Generate helper private variable and initialize it with the
1441 // default value. The address of the original variable is replaced
1442 // by the address of the new private variable in CodeGen. This new
1443 // variable is not added to IdResolver, so the code in the OpenMP
1444 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001445 auto *VDPrivate = buildVarDecl(
1446 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001447 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001448 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001449 if (VDPrivate->isInvalidDecl())
1450 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001451 PrivateCopies.push_back(buildDeclRefExpr(
1452 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001453 } else {
1454 // The variable is also a firstprivate, so initialization sequence
1455 // for private copy is generated already.
1456 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001457 }
1458 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001459 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001460 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001461 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001462 }
1463 }
1464 }
1465
Alexey Bataev758e55e2013-09-06 18:03:48 +00001466 DSAStack->pop();
1467 DiscardCleanupsInEvaluationContext();
1468 PopExpressionEvaluationContext();
1469}
1470
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001471static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1472 Expr *NumIterations, Sema &SemaRef,
1473 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001474
Alexey Bataeva769e072013-03-22 06:34:35 +00001475namespace {
1476
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001477class VarDeclFilterCCC : public CorrectionCandidateCallback {
1478private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001479 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001480
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001481public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001482 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001483 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001484 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001485 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001486 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001487 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1488 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001489 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001490 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001491 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001492};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001493
1494class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1495private:
1496 Sema &SemaRef;
1497
1498public:
1499 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1500 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1501 NamedDecl *ND = Candidate.getCorrectionDecl();
1502 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1503 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1504 SemaRef.getCurScope());
1505 }
1506 return false;
1507 }
1508};
1509
Alexey Bataeved09d242014-05-28 05:53:51 +00001510} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001511
1512ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1513 CXXScopeSpec &ScopeSpec,
1514 const DeclarationNameInfo &Id) {
1515 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1516 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1517
1518 if (Lookup.isAmbiguous())
1519 return ExprError();
1520
1521 VarDecl *VD;
1522 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001523 if (TypoCorrection Corrected = CorrectTypo(
1524 Id, LookupOrdinaryName, CurScope, nullptr,
1525 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001526 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001527 PDiag(Lookup.empty()
1528 ? diag::err_undeclared_var_use_suggest
1529 : diag::err_omp_expected_var_arg_suggest)
1530 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001531 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001532 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001533 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1534 : diag::err_omp_expected_var_arg)
1535 << Id.getName();
1536 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001537 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001538 } else {
1539 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001540 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001541 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1542 return ExprError();
1543 }
1544 }
1545 Lookup.suppressDiagnostics();
1546
1547 // OpenMP [2.9.2, Syntax, C/C++]
1548 // Variables must be file-scope, namespace-scope, or static block-scope.
1549 if (!VD->hasGlobalStorage()) {
1550 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001551 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1552 bool IsDecl =
1553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001554 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1556 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001557 return ExprError();
1558 }
1559
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001560 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1561 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001562 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1563 // A threadprivate directive for file-scope variables must appear outside
1564 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001565 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1566 !getCurLexicalContext()->isTranslationUnit()) {
1567 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001568 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1569 bool IsDecl =
1570 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1571 Diag(VD->getLocation(),
1572 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1573 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001574 return ExprError();
1575 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001576 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1577 // A threadprivate directive for static class member variables must appear
1578 // in the class definition, in the same scope in which the member
1579 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001580 if (CanonicalVD->isStaticDataMember() &&
1581 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1582 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001583 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1584 bool IsDecl =
1585 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1586 Diag(VD->getLocation(),
1587 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1588 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001589 return ExprError();
1590 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001591 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1592 // A threadprivate directive for namespace-scope variables must appear
1593 // outside any definition or declaration other than the namespace
1594 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001595 if (CanonicalVD->getDeclContext()->isNamespace() &&
1596 (!getCurLexicalContext()->isFileContext() ||
1597 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1598 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001599 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1600 bool IsDecl =
1601 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1602 Diag(VD->getLocation(),
1603 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1604 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001605 return ExprError();
1606 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001607 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1608 // A threadprivate directive for static block-scope variables must appear
1609 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001610 if (CanonicalVD->isStaticLocal() && CurScope &&
1611 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001612 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001613 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1614 bool IsDecl =
1615 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1616 Diag(VD->getLocation(),
1617 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1618 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001619 return ExprError();
1620 }
1621
1622 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1623 // A threadprivate directive must lexically precede all references to any
1624 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001625 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001626 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001627 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001628 return ExprError();
1629 }
1630
1631 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001632 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1633 SourceLocation(), VD,
1634 /*RefersToEnclosingVariableOrCapture=*/false,
1635 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001636}
1637
Alexey Bataeved09d242014-05-28 05:53:51 +00001638Sema::DeclGroupPtrTy
1639Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1640 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001641 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001642 CurContext->addDecl(D);
1643 return DeclGroupPtrTy::make(DeclGroupRef(D));
1644 }
David Blaikie0403cb12016-01-15 23:43:25 +00001645 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001646}
1647
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001648namespace {
1649class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1650 Sema &SemaRef;
1651
1652public:
1653 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001654 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001655 if (VD->hasLocalStorage()) {
1656 SemaRef.Diag(E->getLocStart(),
1657 diag::err_omp_local_var_in_threadprivate_init)
1658 << E->getSourceRange();
1659 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1660 << VD << VD->getSourceRange();
1661 return true;
1662 }
1663 }
1664 return false;
1665 }
1666 bool VisitStmt(const Stmt *S) {
1667 for (auto Child : S->children()) {
1668 if (Child && Visit(Child))
1669 return true;
1670 }
1671 return false;
1672 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001673 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001674};
1675} // namespace
1676
Alexey Bataeved09d242014-05-28 05:53:51 +00001677OMPThreadPrivateDecl *
1678Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001679 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001680 for (auto &RefExpr : VarList) {
1681 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001682 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1683 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001684
Alexey Bataev376b4a42016-02-09 09:41:09 +00001685 // Mark variable as used.
1686 VD->setReferenced();
1687 VD->markUsed(Context);
1688
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001689 QualType QType = VD->getType();
1690 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1691 // It will be analyzed later.
1692 Vars.push_back(DE);
1693 continue;
1694 }
1695
Alexey Bataeva769e072013-03-22 06:34:35 +00001696 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1697 // A threadprivate variable must not have an incomplete type.
1698 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001699 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001700 continue;
1701 }
1702
1703 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1704 // A threadprivate variable must not have a reference type.
1705 if (VD->getType()->isReferenceType()) {
1706 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001707 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1708 bool IsDecl =
1709 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1710 Diag(VD->getLocation(),
1711 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1712 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001713 continue;
1714 }
1715
Samuel Antaof8b50122015-07-13 22:54:53 +00001716 // Check if this is a TLS variable. If TLS is not being supported, produce
1717 // the corresponding diagnostic.
1718 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1719 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1720 getLangOpts().OpenMPUseTLS &&
1721 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001722 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1723 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001724 Diag(ILoc, diag::err_omp_var_thread_local)
1725 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001726 bool IsDecl =
1727 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1728 Diag(VD->getLocation(),
1729 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1730 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001731 continue;
1732 }
1733
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001734 // Check if initial value of threadprivate variable reference variable with
1735 // local storage (it is not supported by runtime).
1736 if (auto Init = VD->getAnyInitializer()) {
1737 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001738 if (Checker.Visit(Init))
1739 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001740 }
1741
Alexey Bataeved09d242014-05-28 05:53:51 +00001742 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001743 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001744 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1745 Context, SourceRange(Loc, Loc)));
1746 if (auto *ML = Context.getASTMutationListener())
1747 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001748 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001749 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001750 if (!Vars.empty()) {
1751 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1752 Vars);
1753 D->setAccess(AS_public);
1754 }
1755 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001756}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001757
Alexey Bataev7ff55242014-06-19 09:13:45 +00001758static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001759 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001760 bool IsLoopIterVar = false) {
1761 if (DVar.RefExpr) {
1762 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1763 << getOpenMPClauseName(DVar.CKind);
1764 return;
1765 }
1766 enum {
1767 PDSA_StaticMemberShared,
1768 PDSA_StaticLocalVarShared,
1769 PDSA_LoopIterVarPrivate,
1770 PDSA_LoopIterVarLinear,
1771 PDSA_LoopIterVarLastprivate,
1772 PDSA_ConstVarShared,
1773 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001774 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001775 PDSA_LocalVarPrivate,
1776 PDSA_Implicit
1777 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001778 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001779 auto ReportLoc = D->getLocation();
1780 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001781 if (IsLoopIterVar) {
1782 if (DVar.CKind == OMPC_private)
1783 Reason = PDSA_LoopIterVarPrivate;
1784 else if (DVar.CKind == OMPC_lastprivate)
1785 Reason = PDSA_LoopIterVarLastprivate;
1786 else
1787 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001788 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1789 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001790 Reason = PDSA_TaskVarFirstprivate;
1791 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001792 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001793 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001794 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001795 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001796 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001797 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001798 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001799 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001800 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001801 ReportHint = true;
1802 Reason = PDSA_LocalVarPrivate;
1803 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001804 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001805 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001806 << Reason << ReportHint
1807 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1808 } else if (DVar.ImplicitDSALoc.isValid()) {
1809 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1810 << getOpenMPClauseName(DVar.CKind);
1811 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001812}
1813
Alexey Bataev758e55e2013-09-06 18:03:48 +00001814namespace {
1815class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1816 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001817 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001818 bool ErrorFound;
1819 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001820 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001821 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001822 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001823 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001824
Alexey Bataev758e55e2013-09-06 18:03:48 +00001825public:
1826 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001827 if (E->isTypeDependent() || E->isValueDependent() ||
1828 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1829 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001830 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001831 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001832 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001833 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001834 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001835
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001836 auto DVar = Stack->getTopDSA(VD, false);
1837 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001838 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001839 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001840
Alexey Bataevafe50572017-10-06 17:00:28 +00001841 // Skip internally declared static variables.
1842 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1843 return;
1844
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001845 auto ELoc = E->getExprLoc();
1846 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001847 // The default(none) clause requires that each variable that is referenced
1848 // in the construct, and does not have a predetermined data-sharing
1849 // attribute, must have its data-sharing attribute explicitly determined
1850 // by being listed in a data-sharing attribute clause.
1851 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001852 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001853 VarsWithInheritedDSA.count(VD) == 0) {
1854 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001855 return;
1856 }
1857
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001858 if (isOpenMPTargetExecutionDirective(DKind) &&
1859 !Stack->isLoopControlVariable(VD).first) {
1860 if (!Stack->checkMappableExprComponentListsForDecl(
1861 VD, /*CurrentRegionOnly=*/true,
1862 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1863 StackComponents,
1864 OpenMPClauseKind) {
1865 // Variable is used if it has been marked as an array, array
1866 // section or the variable iself.
1867 return StackComponents.size() == 1 ||
1868 std::all_of(
1869 std::next(StackComponents.rbegin()),
1870 StackComponents.rend(),
1871 [](const OMPClauseMappableExprCommon::
1872 MappableComponent &MC) {
1873 return MC.getAssociatedDeclaration() ==
1874 nullptr &&
1875 (isa<OMPArraySectionExpr>(
1876 MC.getAssociatedExpression()) ||
1877 isa<ArraySubscriptExpr>(
1878 MC.getAssociatedExpression()));
1879 });
1880 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001881 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001882 // By default lambdas are captured as firstprivates.
1883 if (const auto *RD =
1884 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001885 IsFirstprivate = RD->isLambda();
1886 IsFirstprivate =
1887 IsFirstprivate ||
1888 (VD->getType().getNonReferenceType()->isScalarType() &&
1889 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1890 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001891 ImplicitFirstprivate.emplace_back(E);
1892 else
1893 ImplicitMap.emplace_back(E);
1894 return;
1895 }
1896 }
1897
Alexey Bataev758e55e2013-09-06 18:03:48 +00001898 // OpenMP [2.9.3.6, Restrictions, p.2]
1899 // A list item that appears in a reduction clause of the innermost
1900 // enclosing worksharing or parallel construct may not be accessed in an
1901 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001902 DVar = Stack->hasInnermostDSA(
1903 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1904 [](OpenMPDirectiveKind K) -> bool {
1905 return isOpenMPParallelDirective(K) ||
1906 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1907 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001908 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001909 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001910 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001911 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1912 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001913 return;
1914 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001915
1916 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001917 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001918 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1919 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001920 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001921 }
1922 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001923 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001924 if (E->isTypeDependent() || E->isValueDependent() ||
1925 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1926 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001927 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1928 if (!FD)
1929 return;
1930 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001931 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001932 auto DVar = Stack->getTopDSA(FD, false);
1933 // Check if the variable has explicit DSA set and stop analysis if it
1934 // so.
1935 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1936 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001937
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001938 if (isOpenMPTargetExecutionDirective(DKind) &&
1939 !Stack->isLoopControlVariable(FD).first &&
1940 !Stack->checkMappableExprComponentListsForDecl(
1941 FD, /*CurrentRegionOnly=*/true,
1942 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1943 StackComponents,
1944 OpenMPClauseKind) {
1945 return isa<CXXThisExpr>(
1946 cast<MemberExpr>(
1947 StackComponents.back().getAssociatedExpression())
1948 ->getBase()
1949 ->IgnoreParens());
1950 })) {
1951 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1952 // A bit-field cannot appear in a map clause.
1953 //
1954 if (FD->isBitField()) {
1955 SemaRef.Diag(E->getMemberLoc(),
1956 diag::err_omp_bit_fields_forbidden_in_clause)
1957 << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001958 return;
1959 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001960 ImplicitMap.emplace_back(E);
1961 return;
1962 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001963
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001964 auto ELoc = E->getExprLoc();
1965 // OpenMP [2.9.3.6, Restrictions, p.2]
1966 // A list item that appears in a reduction clause of the innermost
1967 // enclosing worksharing or parallel construct may not be accessed in
1968 // an explicit task.
1969 DVar = Stack->hasInnermostDSA(
1970 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1971 [](OpenMPDirectiveKind K) -> bool {
1972 return isOpenMPParallelDirective(K) ||
1973 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1974 },
1975 /*FromParent=*/true);
1976 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1977 ErrorFound = true;
1978 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1979 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1980 return;
1981 }
1982
1983 // Define implicit data-sharing attributes for task.
1984 DVar = Stack->getImplicitDSA(FD, false);
1985 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1986 !Stack->isLoopControlVariable(FD).first)
1987 ImplicitFirstprivate.push_back(E);
1988 return;
1989 }
1990 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
1991 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
1992 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
1993 auto *VD = cast<ValueDecl>(
1994 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
1995 if (!Stack->checkMappableExprComponentListsForDecl(
1996 VD, /*CurrentRegionOnly=*/true,
1997 [&CurComponents](
1998 OMPClauseMappableExprCommon::MappableExprComponentListRef
1999 StackComponents,
2000 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002001 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002002 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002003 for (const auto &SC : llvm::reverse(StackComponents)) {
2004 // Do both expressions have the same kind?
2005 if (CCI->getAssociatedExpression()->getStmtClass() !=
2006 SC.getAssociatedExpression()->getStmtClass())
2007 if (!(isa<OMPArraySectionExpr>(
2008 SC.getAssociatedExpression()) &&
2009 isa<ArraySubscriptExpr>(
2010 CCI->getAssociatedExpression())))
2011 return false;
2012
2013 Decl *CCD = CCI->getAssociatedDeclaration();
2014 Decl *SCD = SC.getAssociatedDeclaration();
2015 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2016 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2017 if (SCD != CCD)
2018 return false;
2019 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002020 if (CCI == CCE)
2021 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002022 }
2023 return true;
2024 })) {
2025 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002026 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002027 } else
2028 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002029 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002030 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002031 for (auto *C : S->clauses()) {
2032 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002033 // for task|target directives.
2034 // Skip analysis of arguments of implicitly defined map clause for target
2035 // directives.
2036 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2037 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002038 for (auto *CC : C->children()) {
2039 if (CC)
2040 Visit(CC);
2041 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002042 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002043 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002044 }
2045 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002046 for (auto *C : S->children()) {
2047 if (C && !isa<OMPExecutableDirective>(C))
2048 Visit(C);
2049 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002050 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002051
2052 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002053 ArrayRef<Expr *> getImplicitFirstprivate() const {
2054 return ImplicitFirstprivate;
2055 }
2056 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002057 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002058 return VarsWithInheritedDSA;
2059 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002060
Alexey Bataev7ff55242014-06-19 09:13:45 +00002061 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2062 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002063};
Alexey Bataeved09d242014-05-28 05:53:51 +00002064} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002065
Alexey Bataevbae9a792014-06-27 10:37:06 +00002066void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002067 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002068 case OMPD_parallel:
2069 case OMPD_parallel_for:
2070 case OMPD_parallel_for_simd:
2071 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002072 case OMPD_teams:
2073 case OMPD_teams_distribute: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002074 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002075 QualType KmpInt32PtrTy =
2076 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002077 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002078 std::make_pair(".global_tid.", KmpInt32PtrTy),
2079 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2080 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002081 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002082 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2083 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002084 break;
2085 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002086 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002087 case OMPD_target_parallel: {
2088 Sema::CapturedParamNameType ParamsTarget[] = {
2089 std::make_pair(StringRef(), QualType()) // __context with shared vars
2090 };
2091 // Start a captured region for 'target' with no implicit parameters.
2092 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2093 ParamsTarget);
2094 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2095 QualType KmpInt32PtrTy =
2096 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002097 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002098 std::make_pair(".global_tid.", KmpInt32PtrTy),
2099 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2100 std::make_pair(StringRef(), QualType()) // __context with shared vars
2101 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002102 // Start a captured region for 'teams' or 'parallel'. Both regions have
2103 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002104 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002105 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002106 break;
2107 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002108 case OMPD_simd:
2109 case OMPD_for:
2110 case OMPD_for_simd:
2111 case OMPD_sections:
2112 case OMPD_section:
2113 case OMPD_single:
2114 case OMPD_master:
2115 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002116 case OMPD_taskgroup:
2117 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00002118 case OMPD_ordered:
2119 case OMPD_atomic:
2120 case OMPD_target_data:
2121 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00002122 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00002123 case OMPD_target_parallel_for_simd:
2124 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002125 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002126 std::make_pair(StringRef(), QualType()) // __context with shared vars
2127 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002128 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2129 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002130 break;
2131 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002132 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002133 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002134 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2135 FunctionProtoType::ExtProtoInfo EPI;
2136 EPI.Variadic = true;
2137 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002138 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002139 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002140 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2141 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2142 std::make_pair(".copy_fn.",
2143 Context.getPointerType(CopyFnType).withConst()),
2144 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002145 std::make_pair(StringRef(), QualType()) // __context with shared vars
2146 };
2147 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2148 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002149 // Mark this captured region as inlined, because we don't use outlined
2150 // function directly.
2151 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2152 AlwaysInlineAttr::CreateImplicit(
2153 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002154 break;
2155 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002156 case OMPD_taskloop:
2157 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002158 QualType KmpInt32Ty =
2159 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2160 QualType KmpUInt64Ty =
2161 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2162 QualType KmpInt64Ty =
2163 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2164 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2165 FunctionProtoType::ExtProtoInfo EPI;
2166 EPI.Variadic = true;
2167 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002168 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002169 std::make_pair(".global_tid.", KmpInt32Ty),
2170 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2171 std::make_pair(".privates.",
2172 Context.VoidPtrTy.withConst().withRestrict()),
2173 std::make_pair(
2174 ".copy_fn.",
2175 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2176 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2177 std::make_pair(".lb.", KmpUInt64Ty),
2178 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2179 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002180 std::make_pair(".reductions.",
2181 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002182 std::make_pair(StringRef(), QualType()) // __context with shared vars
2183 };
2184 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2185 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002186 // Mark this captured region as inlined, because we don't use outlined
2187 // function directly.
2188 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2189 AlwaysInlineAttr::CreateImplicit(
2190 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002191 break;
2192 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002193 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002194 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002195 case OMPD_distribute_parallel_for:
Kelvin Li579e41c2016-11-30 23:51:03 +00002196 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002197 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00002198 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00002199 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002200 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002201 case OMPD_target_teams_distribute_parallel_for_simd:
2202 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002203 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2204 QualType KmpInt32PtrTy =
2205 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2206 Sema::CapturedParamNameType Params[] = {
2207 std::make_pair(".global_tid.", KmpInt32PtrTy),
2208 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2209 std::make_pair(".previous.lb.", Context.getSizeType()),
2210 std::make_pair(".previous.ub.", Context.getSizeType()),
2211 std::make_pair(StringRef(), QualType()) // __context with shared vars
2212 };
2213 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2214 Params);
2215 break;
2216 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002217 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002218 case OMPD_taskyield:
2219 case OMPD_barrier:
2220 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002221 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002222 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002223 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00002224 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00002225 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002226 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002227 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002228 case OMPD_declare_target:
2229 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00002230 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00002231 llvm_unreachable("OpenMP Directive is not allowed");
2232 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002233 llvm_unreachable("Unknown OpenMP directive");
2234 }
2235}
2236
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002237int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2238 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2239 getOpenMPCaptureRegions(CaptureRegions, DKind);
2240 return CaptureRegions.size();
2241}
2242
Alexey Bataev3392d762016-02-16 11:18:12 +00002243static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002244 Expr *CaptureExpr, bool WithInit,
2245 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002246 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002247 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002248 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002249 QualType Ty = Init->getType();
2250 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2251 if (S.getLangOpts().CPlusPlus)
2252 Ty = C.getLValueReferenceType(Ty);
2253 else {
2254 Ty = C.getPointerType(Ty);
2255 ExprResult Res =
2256 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2257 if (!Res.isUsable())
2258 return nullptr;
2259 Init = Res.get();
2260 }
Alexey Bataev61205072016-03-02 04:57:40 +00002261 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002262 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002263 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2264 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002265 if (!WithInit)
2266 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002267 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002268 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002269 return CED;
2270}
2271
Alexey Bataev61205072016-03-02 04:57:40 +00002272static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2273 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002274 OMPCapturedExprDecl *CD;
2275 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2276 CD = cast<OMPCapturedExprDecl>(VD);
2277 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002278 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2279 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002280 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002281 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002282}
2283
Alexey Bataev5a3af132016-03-29 08:58:54 +00002284static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2285 if (!Ref) {
2286 auto *CD =
2287 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2288 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2289 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2290 CaptureExpr->getExprLoc());
2291 }
2292 ExprResult Res = Ref;
2293 if (!S.getLangOpts().CPlusPlus &&
2294 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2295 Ref->getType()->isPointerType())
2296 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2297 if (!Res.isUsable())
2298 return ExprError();
2299 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002300}
2301
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002302namespace {
2303// OpenMP directives parsed in this section are represented as a
2304// CapturedStatement with an associated statement. If a syntax error
2305// is detected during the parsing of the associated statement, the
2306// compiler must abort processing and close the CapturedStatement.
2307//
2308// Combined directives such as 'target parallel' have more than one
2309// nested CapturedStatements. This RAII ensures that we unwind out
2310// of all the nested CapturedStatements when an error is found.
2311class CaptureRegionUnwinderRAII {
2312private:
2313 Sema &S;
2314 bool &ErrorFound;
2315 OpenMPDirectiveKind DKind;
2316
2317public:
2318 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2319 OpenMPDirectiveKind DKind)
2320 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2321 ~CaptureRegionUnwinderRAII() {
2322 if (ErrorFound) {
2323 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2324 while (--ThisCaptureLevel >= 0)
2325 S.ActOnCapturedRegionError();
2326 }
2327 }
2328};
2329} // namespace
2330
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002331StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2332 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002333 bool ErrorFound = false;
2334 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2335 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002336 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002337 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002338 return StmtError();
2339 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002340
2341 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002342 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002343 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002344 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002345 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002346 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002347 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2348 Clause->getClauseKind() == OMPC_in_reduction) {
2349 // Capture taskgroup task_reduction descriptors inside the tasking regions
2350 // with the corresponding in_reduction items.
2351 auto *IRC = cast<OMPInReductionClause>(Clause);
2352 for (auto *E : IRC->taskgroup_descriptors())
2353 if (E)
2354 MarkDeclarationsReferencedInExpr(E);
2355 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002356 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002357 Clause->getClauseKind() == OMPC_copyprivate ||
2358 (getLangOpts().OpenMPUseTLS &&
2359 getASTContext().getTargetInfo().isTLSSupported() &&
2360 Clause->getClauseKind() == OMPC_copyin)) {
2361 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002362 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002363 for (auto *VarRef : Clause->children()) {
2364 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002365 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002366 }
2367 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002368 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002369 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002370 if (auto *C = OMPClauseWithPreInit::get(Clause))
2371 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002372 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2373 if (auto *E = C->getPostUpdateExpr())
2374 MarkDeclarationsReferencedInExpr(E);
2375 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002376 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002377 if (Clause->getClauseKind() == OMPC_schedule)
2378 SC = cast<OMPScheduleClause>(Clause);
2379 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002380 OC = cast<OMPOrderedClause>(Clause);
2381 else if (Clause->getClauseKind() == OMPC_linear)
2382 LCs.push_back(cast<OMPLinearClause>(Clause));
2383 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002384 // OpenMP, 2.7.1 Loop Construct, Restrictions
2385 // The nonmonotonic modifier cannot be specified if an ordered clause is
2386 // specified.
2387 if (SC &&
2388 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2389 SC->getSecondScheduleModifier() ==
2390 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2391 OC) {
2392 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2393 ? SC->getFirstScheduleModifierLoc()
2394 : SC->getSecondScheduleModifierLoc(),
2395 diag::err_omp_schedule_nonmonotonic_ordered)
2396 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2397 ErrorFound = true;
2398 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002399 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2400 for (auto *C : LCs) {
2401 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2402 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2403 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002404 ErrorFound = true;
2405 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002406 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2407 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2408 OC->getNumForLoops()) {
2409 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2410 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2411 ErrorFound = true;
2412 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002413 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002414 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002415 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002416 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002417 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2418 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2419 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2420 // Mark all variables in private list clauses as used in inner region.
2421 // Required for proper codegen of combined directives.
2422 // TODO: add processing for other clauses.
2423 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2424 for (auto *C : PICs) {
2425 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2426 // Find the particular capture region for the clause if the
2427 // directive is a combined one with multiple capture regions.
2428 // If the directive is not a combined one, the capture region
2429 // associated with the clause is OMPD_unknown and is generated
2430 // only once.
2431 if (CaptureRegion == ThisCaptureRegion ||
2432 CaptureRegion == OMPD_unknown) {
2433 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2434 for (auto *D : DS->decls())
2435 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2436 }
2437 }
2438 }
2439 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002440 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002441 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002442 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002443}
2444
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002445static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2446 OpenMPDirectiveKind CancelRegion,
2447 SourceLocation StartLoc) {
2448 // CancelRegion is only needed for cancel and cancellation_point.
2449 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2450 return false;
2451
2452 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2453 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2454 return false;
2455
2456 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2457 << getOpenMPDirectiveName(CancelRegion);
2458 return true;
2459}
2460
2461static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002462 OpenMPDirectiveKind CurrentRegion,
2463 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002464 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002465 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002466 if (Stack->getCurScope()) {
2467 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002468 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002469 bool NestingProhibited = false;
2470 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002471 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002472 enum {
2473 NoRecommend,
2474 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002475 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002476 ShouldBeInTargetRegion,
2477 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002478 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002479 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002480 // OpenMP [2.16, Nesting of Regions]
2481 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002482 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002483 // An ordered construct with the simd clause is the only OpenMP
2484 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002485 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002486 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2487 // message.
2488 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2489 ? diag::err_omp_prohibited_region_simd
2490 : diag::warn_omp_nesting_simd);
2491 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002492 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002493 if (ParentRegion == OMPD_atomic) {
2494 // OpenMP [2.16, Nesting of Regions]
2495 // OpenMP constructs may not be nested inside an atomic region.
2496 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2497 return true;
2498 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002499 if (CurrentRegion == OMPD_section) {
2500 // OpenMP [2.7.2, sections Construct, Restrictions]
2501 // Orphaned section directives are prohibited. That is, the section
2502 // directives must appear within the sections construct and must not be
2503 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002504 if (ParentRegion != OMPD_sections &&
2505 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002506 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2507 << (ParentRegion != OMPD_unknown)
2508 << getOpenMPDirectiveName(ParentRegion);
2509 return true;
2510 }
2511 return false;
2512 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002513 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002514 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002515 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002516 if (ParentRegion == OMPD_unknown &&
2517 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002518 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002519 if (CurrentRegion == OMPD_cancellation_point ||
2520 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002521 // OpenMP [2.16, Nesting of Regions]
2522 // A cancellation point construct for which construct-type-clause is
2523 // taskgroup must be nested inside a task construct. A cancellation
2524 // point construct for which construct-type-clause is not taskgroup must
2525 // be closely nested inside an OpenMP construct that matches the type
2526 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002527 // A cancel construct for which construct-type-clause is taskgroup must be
2528 // nested inside a task construct. A cancel construct for which
2529 // construct-type-clause is not taskgroup must be closely nested inside an
2530 // OpenMP construct that matches the type specified in
2531 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002532 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002533 !((CancelRegion == OMPD_parallel &&
2534 (ParentRegion == OMPD_parallel ||
2535 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002536 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002537 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2538 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002539 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2540 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002541 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2542 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002543 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002544 // OpenMP [2.16, Nesting of Regions]
2545 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002546 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002547 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002548 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002549 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2550 // OpenMP [2.16, Nesting of Regions]
2551 // A critical region may not be nested (closely or otherwise) inside a
2552 // critical region with the same name. Note that this restriction is not
2553 // sufficient to prevent deadlock.
2554 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002555 bool DeadLock = Stack->hasDirective(
2556 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2557 const DeclarationNameInfo &DNI,
2558 SourceLocation Loc) -> bool {
2559 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2560 PreviousCriticalLoc = Loc;
2561 return true;
2562 } else
2563 return false;
2564 },
2565 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002566 if (DeadLock) {
2567 SemaRef.Diag(StartLoc,
2568 diag::err_omp_prohibited_region_critical_same_name)
2569 << CurrentName.getName();
2570 if (PreviousCriticalLoc.isValid())
2571 SemaRef.Diag(PreviousCriticalLoc,
2572 diag::note_omp_previous_critical_region);
2573 return true;
2574 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002575 } else if (CurrentRegion == OMPD_barrier) {
2576 // OpenMP [2.16, Nesting of Regions]
2577 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002578 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002579 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2580 isOpenMPTaskingDirective(ParentRegion) ||
2581 ParentRegion == OMPD_master ||
2582 ParentRegion == OMPD_critical ||
2583 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002584 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002585 !isOpenMPParallelDirective(CurrentRegion) &&
2586 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002587 // OpenMP [2.16, Nesting of Regions]
2588 // A worksharing region may not be closely nested inside a worksharing,
2589 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002590 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2591 isOpenMPTaskingDirective(ParentRegion) ||
2592 ParentRegion == OMPD_master ||
2593 ParentRegion == OMPD_critical ||
2594 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002595 Recommend = ShouldBeInParallelRegion;
2596 } else if (CurrentRegion == OMPD_ordered) {
2597 // OpenMP [2.16, Nesting of Regions]
2598 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002599 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002600 // An ordered region must be closely nested inside a loop region (or
2601 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002602 // OpenMP [2.8.1,simd Construct, Restrictions]
2603 // An ordered construct with the simd clause is the only OpenMP construct
2604 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002605 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002606 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002607 !(isOpenMPSimdDirective(ParentRegion) ||
2608 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002609 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002610 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002611 // OpenMP [2.16, Nesting of Regions]
2612 // If specified, a teams construct must be contained within a target
2613 // construct.
2614 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002615 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002616 Recommend = ShouldBeInTargetRegion;
2617 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2618 }
Kelvin Libf594a52016-12-17 05:48:59 +00002619 if (!NestingProhibited &&
2620 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2621 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2622 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002623 // OpenMP [2.16, Nesting of Regions]
2624 // distribute, parallel, parallel sections, parallel workshare, and the
2625 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2626 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002627 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2628 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002629 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002630 }
David Majnemer9d168222016-08-05 17:44:54 +00002631 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002632 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002633 // OpenMP 4.5 [2.17 Nesting of Regions]
2634 // The region associated with the distribute construct must be strictly
2635 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002636 NestingProhibited =
2637 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002638 Recommend = ShouldBeInTeamsRegion;
2639 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002640 if (!NestingProhibited &&
2641 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2642 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2643 // OpenMP 4.5 [2.17 Nesting of Regions]
2644 // If a target, target update, target data, target enter data, or
2645 // target exit data construct is encountered during execution of a
2646 // target region, the behavior is unspecified.
2647 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002648 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2649 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002650 if (isOpenMPTargetExecutionDirective(K)) {
2651 OffendingRegion = K;
2652 return true;
2653 } else
2654 return false;
2655 },
2656 false /* don't skip top directive */);
2657 CloseNesting = false;
2658 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002659 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002660 if (OrphanSeen) {
2661 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2662 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2663 } else {
2664 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2665 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2666 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2667 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002668 return true;
2669 }
2670 }
2671 return false;
2672}
2673
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002674static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2675 ArrayRef<OMPClause *> Clauses,
2676 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2677 bool ErrorFound = false;
2678 unsigned NamedModifiersNumber = 0;
2679 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2680 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002681 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002682 for (const auto *C : Clauses) {
2683 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2684 // At most one if clause without a directive-name-modifier can appear on
2685 // the directive.
2686 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2687 if (FoundNameModifiers[CurNM]) {
2688 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2689 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2690 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2691 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002692 } else if (CurNM != OMPD_unknown) {
2693 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002694 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002695 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002696 FoundNameModifiers[CurNM] = IC;
2697 if (CurNM == OMPD_unknown)
2698 continue;
2699 // Check if the specified name modifier is allowed for the current
2700 // directive.
2701 // At most one if clause with the particular directive-name-modifier can
2702 // appear on the directive.
2703 bool MatchFound = false;
2704 for (auto NM : AllowedNameModifiers) {
2705 if (CurNM == NM) {
2706 MatchFound = true;
2707 break;
2708 }
2709 }
2710 if (!MatchFound) {
2711 S.Diag(IC->getNameModifierLoc(),
2712 diag::err_omp_wrong_if_directive_name_modifier)
2713 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2714 ErrorFound = true;
2715 }
2716 }
2717 }
2718 // If any if clause on the directive includes a directive-name-modifier then
2719 // all if clauses on the directive must include a directive-name-modifier.
2720 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2721 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2722 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2723 diag::err_omp_no_more_if_clause);
2724 } else {
2725 std::string Values;
2726 std::string Sep(", ");
2727 unsigned AllowedCnt = 0;
2728 unsigned TotalAllowedNum =
2729 AllowedNameModifiers.size() - NamedModifiersNumber;
2730 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2731 ++Cnt) {
2732 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2733 if (!FoundNameModifiers[NM]) {
2734 Values += "'";
2735 Values += getOpenMPDirectiveName(NM);
2736 Values += "'";
2737 if (AllowedCnt + 2 == TotalAllowedNum)
2738 Values += " or ";
2739 else if (AllowedCnt + 1 != TotalAllowedNum)
2740 Values += Sep;
2741 ++AllowedCnt;
2742 }
2743 }
2744 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2745 diag::err_omp_unnamed_if_clause)
2746 << (TotalAllowedNum > 1) << Values;
2747 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002748 for (auto Loc : NameModifierLoc) {
2749 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2750 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002751 ErrorFound = true;
2752 }
2753 return ErrorFound;
2754}
2755
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002756StmtResult Sema::ActOnOpenMPExecutableDirective(
2757 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2758 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2759 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002760 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002761 // First check CancelRegion which is then used in checkNestingOfRegions.
2762 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2763 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002764 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002765 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002766
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002767 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002768 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002769 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002770 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002771 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002772 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2773
2774 // Check default data sharing attributes for referenced variables.
2775 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002776 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2777 Stmt *S = AStmt;
2778 while (--ThisCaptureLevel >= 0)
2779 S = cast<CapturedStmt>(S)->getCapturedStmt();
2780 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002781 if (DSAChecker.isErrorFound())
2782 return StmtError();
2783 // Generate list of implicitly defined firstprivate variables.
2784 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002785
Alexey Bataev88202be2017-07-27 13:20:36 +00002786 SmallVector<Expr *, 4> ImplicitFirstprivates(
2787 DSAChecker.getImplicitFirstprivate().begin(),
2788 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002789 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2790 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002791 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2792 for (auto *C : Clauses) {
2793 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2794 for (auto *E : IRC->taskgroup_descriptors())
2795 if (E)
2796 ImplicitFirstprivates.emplace_back(E);
2797 }
2798 }
2799 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002800 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002801 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2802 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002803 ClausesWithImplicit.push_back(Implicit);
2804 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002805 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002806 } else
2807 ErrorFound = true;
2808 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002809 if (!ImplicitMaps.empty()) {
2810 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2811 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2812 SourceLocation(), SourceLocation(), ImplicitMaps,
2813 SourceLocation(), SourceLocation(), SourceLocation())) {
2814 ClausesWithImplicit.emplace_back(Implicit);
2815 ErrorFound |=
2816 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2817 } else
2818 ErrorFound = true;
2819 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002820 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002821
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002822 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002823 switch (Kind) {
2824 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002825 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2826 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002827 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002828 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002829 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002830 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2831 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002832 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002833 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002834 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2835 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002836 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002837 case OMPD_for_simd:
2838 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2839 EndLoc, VarsWithInheritedDSA);
2840 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002841 case OMPD_sections:
2842 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2843 EndLoc);
2844 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002845 case OMPD_section:
2846 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002847 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002848 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2849 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002850 case OMPD_single:
2851 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2852 EndLoc);
2853 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002854 case OMPD_master:
2855 assert(ClausesWithImplicit.empty() &&
2856 "No clauses are allowed for 'omp master' directive");
2857 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2858 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002859 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002860 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2861 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002862 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002863 case OMPD_parallel_for:
2864 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2865 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002866 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002867 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002868 case OMPD_parallel_for_simd:
2869 Res = ActOnOpenMPParallelForSimdDirective(
2870 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002871 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002872 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002873 case OMPD_parallel_sections:
2874 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2875 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002876 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002877 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002878 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002879 Res =
2880 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002881 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002882 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002883 case OMPD_taskyield:
2884 assert(ClausesWithImplicit.empty() &&
2885 "No clauses are allowed for 'omp taskyield' directive");
2886 assert(AStmt == nullptr &&
2887 "No associated statement allowed for 'omp taskyield' directive");
2888 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2889 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002890 case OMPD_barrier:
2891 assert(ClausesWithImplicit.empty() &&
2892 "No clauses are allowed for 'omp barrier' directive");
2893 assert(AStmt == nullptr &&
2894 "No associated statement allowed for 'omp barrier' directive");
2895 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2896 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002897 case OMPD_taskwait:
2898 assert(ClausesWithImplicit.empty() &&
2899 "No clauses are allowed for 'omp taskwait' directive");
2900 assert(AStmt == nullptr &&
2901 "No associated statement allowed for 'omp taskwait' directive");
2902 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2903 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002904 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002905 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2906 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002907 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002908 case OMPD_flush:
2909 assert(AStmt == nullptr &&
2910 "No associated statement allowed for 'omp flush' directive");
2911 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2912 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002913 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002914 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2915 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002916 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002917 case OMPD_atomic:
2918 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2919 EndLoc);
2920 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002921 case OMPD_teams:
2922 Res =
2923 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2924 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002925 case OMPD_target:
2926 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2927 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002928 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002929 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002930 case OMPD_target_parallel:
2931 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2932 StartLoc, EndLoc);
2933 AllowedNameModifiers.push_back(OMPD_target);
2934 AllowedNameModifiers.push_back(OMPD_parallel);
2935 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002936 case OMPD_target_parallel_for:
2937 Res = ActOnOpenMPTargetParallelForDirective(
2938 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2939 AllowedNameModifiers.push_back(OMPD_target);
2940 AllowedNameModifiers.push_back(OMPD_parallel);
2941 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002942 case OMPD_cancellation_point:
2943 assert(ClausesWithImplicit.empty() &&
2944 "No clauses are allowed for 'omp cancellation point' directive");
2945 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2946 "cancellation point' directive");
2947 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2948 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002949 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002950 assert(AStmt == nullptr &&
2951 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002952 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2953 CancelRegion);
2954 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002955 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002956 case OMPD_target_data:
2957 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2958 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002959 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002960 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002961 case OMPD_target_enter_data:
2962 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2963 EndLoc);
2964 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2965 break;
Samuel Antao72590762016-01-19 20:04:50 +00002966 case OMPD_target_exit_data:
2967 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2968 EndLoc);
2969 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2970 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002971 case OMPD_taskloop:
2972 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2973 EndLoc, VarsWithInheritedDSA);
2974 AllowedNameModifiers.push_back(OMPD_taskloop);
2975 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002976 case OMPD_taskloop_simd:
2977 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2978 EndLoc, VarsWithInheritedDSA);
2979 AllowedNameModifiers.push_back(OMPD_taskloop);
2980 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002981 case OMPD_distribute:
2982 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2983 EndLoc, VarsWithInheritedDSA);
2984 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002985 case OMPD_target_update:
2986 assert(!AStmt && "Statement is not allowed for target update");
2987 Res =
2988 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2989 AllowedNameModifiers.push_back(OMPD_target_update);
2990 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002991 case OMPD_distribute_parallel_for:
2992 Res = ActOnOpenMPDistributeParallelForDirective(
2993 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2994 AllowedNameModifiers.push_back(OMPD_parallel);
2995 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002996 case OMPD_distribute_parallel_for_simd:
2997 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2998 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2999 AllowedNameModifiers.push_back(OMPD_parallel);
3000 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003001 case OMPD_distribute_simd:
3002 Res = ActOnOpenMPDistributeSimdDirective(
3003 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3004 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003005 case OMPD_target_parallel_for_simd:
3006 Res = ActOnOpenMPTargetParallelForSimdDirective(
3007 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3008 AllowedNameModifiers.push_back(OMPD_target);
3009 AllowedNameModifiers.push_back(OMPD_parallel);
3010 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003011 case OMPD_target_simd:
3012 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3013 EndLoc, VarsWithInheritedDSA);
3014 AllowedNameModifiers.push_back(OMPD_target);
3015 break;
Kelvin Li02532872016-08-05 14:37:37 +00003016 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003017 Res = ActOnOpenMPTeamsDistributeDirective(
3018 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003019 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003020 case OMPD_teams_distribute_simd:
3021 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3022 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3023 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003024 case OMPD_teams_distribute_parallel_for_simd:
3025 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3026 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3027 AllowedNameModifiers.push_back(OMPD_parallel);
3028 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003029 case OMPD_teams_distribute_parallel_for:
3030 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3031 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3032 AllowedNameModifiers.push_back(OMPD_parallel);
3033 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003034 case OMPD_target_teams:
3035 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3036 EndLoc);
3037 AllowedNameModifiers.push_back(OMPD_target);
3038 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003039 case OMPD_target_teams_distribute:
3040 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3041 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3042 AllowedNameModifiers.push_back(OMPD_target);
3043 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003044 case OMPD_target_teams_distribute_parallel_for:
3045 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3046 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3047 AllowedNameModifiers.push_back(OMPD_target);
3048 AllowedNameModifiers.push_back(OMPD_parallel);
3049 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003050 case OMPD_target_teams_distribute_parallel_for_simd:
3051 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3052 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3053 AllowedNameModifiers.push_back(OMPD_target);
3054 AllowedNameModifiers.push_back(OMPD_parallel);
3055 break;
Kelvin Lida681182017-01-10 18:08:18 +00003056 case OMPD_target_teams_distribute_simd:
3057 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3059 AllowedNameModifiers.push_back(OMPD_target);
3060 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003061 case OMPD_declare_target:
3062 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003063 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003064 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003065 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003066 llvm_unreachable("OpenMP Directive is not allowed");
3067 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003068 llvm_unreachable("Unknown OpenMP directive");
3069 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003070
Alexey Bataev4acb8592014-07-07 13:01:15 +00003071 for (auto P : VarsWithInheritedDSA) {
3072 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3073 << P.first << P.second->getSourceRange();
3074 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003075 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3076
3077 if (!AllowedNameModifiers.empty())
3078 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3079 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003080
Alexey Bataeved09d242014-05-28 05:53:51 +00003081 if (ErrorFound)
3082 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003083 return Res;
3084}
3085
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003086Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3087 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003088 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003089 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3090 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003091 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003092 assert(Linears.size() == LinModifiers.size());
3093 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003094 if (!DG || DG.get().isNull())
3095 return DeclGroupPtrTy();
3096
3097 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003098 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003099 return DG;
3100 }
3101 auto *ADecl = DG.get().getSingleDecl();
3102 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3103 ADecl = FTD->getTemplatedDecl();
3104
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003105 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3106 if (!FD) {
3107 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003108 return DeclGroupPtrTy();
3109 }
3110
Alexey Bataev2af33e32016-04-07 12:45:37 +00003111 // OpenMP [2.8.2, declare simd construct, Description]
3112 // The parameter of the simdlen clause must be a constant positive integer
3113 // expression.
3114 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003115 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003116 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003117 // OpenMP [2.8.2, declare simd construct, Description]
3118 // The special this pointer can be used as if was one of the arguments to the
3119 // function in any of the linear, aligned, or uniform clauses.
3120 // The uniform clause declares one or more arguments to have an invariant
3121 // value for all concurrent invocations of the function in the execution of a
3122 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003123 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3124 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003125 for (auto *E : Uniforms) {
3126 E = E->IgnoreParenImpCasts();
3127 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3128 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3129 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3130 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003131 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3132 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003133 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003134 }
3135 if (isa<CXXThisExpr>(E)) {
3136 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003137 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003138 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003139 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3140 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003141 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003142 // OpenMP [2.8.2, declare simd construct, Description]
3143 // The aligned clause declares that the object to which each list item points
3144 // is aligned to the number of bytes expressed in the optional parameter of
3145 // the aligned clause.
3146 // The special this pointer can be used as if was one of the arguments to the
3147 // function in any of the linear, aligned, or uniform clauses.
3148 // The type of list items appearing in the aligned clause must be array,
3149 // pointer, reference to array, or reference to pointer.
3150 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3151 Expr *AlignedThis = nullptr;
3152 for (auto *E : Aligneds) {
3153 E = E->IgnoreParenImpCasts();
3154 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3155 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3156 auto *CanonPVD = PVD->getCanonicalDecl();
3157 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3158 FD->getParamDecl(PVD->getFunctionScopeIndex())
3159 ->getCanonicalDecl() == CanonPVD) {
3160 // OpenMP [2.8.1, simd construct, Restrictions]
3161 // A list-item cannot appear in more than one aligned clause.
3162 if (AlignedArgs.count(CanonPVD) > 0) {
3163 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3164 << 1 << E->getSourceRange();
3165 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3166 diag::note_omp_explicit_dsa)
3167 << getOpenMPClauseName(OMPC_aligned);
3168 continue;
3169 }
3170 AlignedArgs[CanonPVD] = E;
3171 QualType QTy = PVD->getType()
3172 .getNonReferenceType()
3173 .getUnqualifiedType()
3174 .getCanonicalType();
3175 const Type *Ty = QTy.getTypePtrOrNull();
3176 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3177 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3178 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3179 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3180 }
3181 continue;
3182 }
3183 }
3184 if (isa<CXXThisExpr>(E)) {
3185 if (AlignedThis) {
3186 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3187 << 2 << E->getSourceRange();
3188 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3189 << getOpenMPClauseName(OMPC_aligned);
3190 }
3191 AlignedThis = E;
3192 continue;
3193 }
3194 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3195 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3196 }
3197 // The optional parameter of the aligned clause, alignment, must be a constant
3198 // positive integer expression. If no optional parameter is specified,
3199 // implementation-defined default alignments for SIMD instructions on the
3200 // target platforms are assumed.
3201 SmallVector<Expr *, 4> NewAligns;
3202 for (auto *E : Alignments) {
3203 ExprResult Align;
3204 if (E)
3205 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3206 NewAligns.push_back(Align.get());
3207 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003208 // OpenMP [2.8.2, declare simd construct, Description]
3209 // The linear clause declares one or more list items to be private to a SIMD
3210 // lane and to have a linear relationship with respect to the iteration space
3211 // of a loop.
3212 // The special this pointer can be used as if was one of the arguments to the
3213 // function in any of the linear, aligned, or uniform clauses.
3214 // When a linear-step expression is specified in a linear clause it must be
3215 // either a constant integer expression or an integer-typed parameter that is
3216 // specified in a uniform clause on the directive.
3217 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3218 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3219 auto MI = LinModifiers.begin();
3220 for (auto *E : Linears) {
3221 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3222 ++MI;
3223 E = E->IgnoreParenImpCasts();
3224 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3225 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3226 auto *CanonPVD = PVD->getCanonicalDecl();
3227 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3228 FD->getParamDecl(PVD->getFunctionScopeIndex())
3229 ->getCanonicalDecl() == CanonPVD) {
3230 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3231 // A list-item cannot appear in more than one linear clause.
3232 if (LinearArgs.count(CanonPVD) > 0) {
3233 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3234 << getOpenMPClauseName(OMPC_linear)
3235 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3236 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3237 diag::note_omp_explicit_dsa)
3238 << getOpenMPClauseName(OMPC_linear);
3239 continue;
3240 }
3241 // Each argument can appear in at most one uniform or linear clause.
3242 if (UniformedArgs.count(CanonPVD) > 0) {
3243 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3244 << getOpenMPClauseName(OMPC_linear)
3245 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3246 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3247 diag::note_omp_explicit_dsa)
3248 << getOpenMPClauseName(OMPC_uniform);
3249 continue;
3250 }
3251 LinearArgs[CanonPVD] = E;
3252 if (E->isValueDependent() || E->isTypeDependent() ||
3253 E->isInstantiationDependent() ||
3254 E->containsUnexpandedParameterPack())
3255 continue;
3256 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3257 PVD->getOriginalType());
3258 continue;
3259 }
3260 }
3261 if (isa<CXXThisExpr>(E)) {
3262 if (UniformedLinearThis) {
3263 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3264 << getOpenMPClauseName(OMPC_linear)
3265 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3266 << E->getSourceRange();
3267 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3268 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3269 : OMPC_linear);
3270 continue;
3271 }
3272 UniformedLinearThis = E;
3273 if (E->isValueDependent() || E->isTypeDependent() ||
3274 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3275 continue;
3276 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3277 E->getType());
3278 continue;
3279 }
3280 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3281 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3282 }
3283 Expr *Step = nullptr;
3284 Expr *NewStep = nullptr;
3285 SmallVector<Expr *, 4> NewSteps;
3286 for (auto *E : Steps) {
3287 // Skip the same step expression, it was checked already.
3288 if (Step == E || !E) {
3289 NewSteps.push_back(E ? NewStep : nullptr);
3290 continue;
3291 }
3292 Step = E;
3293 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3294 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3295 auto *CanonPVD = PVD->getCanonicalDecl();
3296 if (UniformedArgs.count(CanonPVD) == 0) {
3297 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3298 << Step->getSourceRange();
3299 } else if (E->isValueDependent() || E->isTypeDependent() ||
3300 E->isInstantiationDependent() ||
3301 E->containsUnexpandedParameterPack() ||
3302 CanonPVD->getType()->hasIntegerRepresentation())
3303 NewSteps.push_back(Step);
3304 else {
3305 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3306 << Step->getSourceRange();
3307 }
3308 continue;
3309 }
3310 NewStep = Step;
3311 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3312 !Step->isInstantiationDependent() &&
3313 !Step->containsUnexpandedParameterPack()) {
3314 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3315 .get();
3316 if (NewStep)
3317 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3318 }
3319 NewSteps.push_back(NewStep);
3320 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003321 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3322 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003323 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003324 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3325 const_cast<Expr **>(Linears.data()), Linears.size(),
3326 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3327 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003328 ADecl->addAttr(NewAttr);
3329 return ConvertDeclToDeclGroup(ADecl);
3330}
3331
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003332StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3333 Stmt *AStmt,
3334 SourceLocation StartLoc,
3335 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003336 if (!AStmt)
3337 return StmtError();
3338
Alexey Bataev9959db52014-05-06 10:08:46 +00003339 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3340 // 1.2.2 OpenMP Language Terminology
3341 // Structured block - An executable statement with a single entry at the
3342 // top and a single exit at the bottom.
3343 // The point of exit cannot be a branch out of the structured block.
3344 // longjmp() and throw() must not violate the entry/exit criteria.
3345 CS->getCapturedDecl()->setNothrow();
3346
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003347 getCurFunction()->setHasBranchProtectedScope();
3348
Alexey Bataev25e5b442015-09-15 12:52:43 +00003349 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3350 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003351}
3352
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003353namespace {
3354/// \brief Helper class for checking canonical form of the OpenMP loops and
3355/// extracting iteration space of each loop in the loop nest, that will be used
3356/// for IR generation.
3357class OpenMPIterationSpaceChecker {
3358 /// \brief Reference to Sema.
3359 Sema &SemaRef;
3360 /// \brief A location for diagnostics (when there is no some better location).
3361 SourceLocation DefaultLoc;
3362 /// \brief A location for diagnostics (when increment is not compatible).
3363 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003364 /// \brief A source location for referring to loop init later.
3365 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003366 /// \brief A source location for referring to condition later.
3367 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003368 /// \brief A source location for referring to increment later.
3369 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003370 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003371 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003372 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003373 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003374 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003375 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003376 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003377 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003378 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003379 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003380 /// \brief This flag is true when condition is one of:
3381 /// Var < UB
3382 /// Var <= UB
3383 /// UB > Var
3384 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003385 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003386 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003387 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003388 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003389 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003390
3391public:
3392 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003393 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003394 /// \brief Check init-expr for canonical loop form and save loop counter
3395 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003396 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003397 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3398 /// for less/greater and for strict/non-strict comparison.
3399 bool CheckCond(Expr *S);
3400 /// \brief Check incr-expr for canonical loop form and return true if it
3401 /// does not conform, otherwise save loop step (#Step).
3402 bool CheckInc(Expr *S);
3403 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003404 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003405 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003406 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003407 /// \brief Source range of the loop init.
3408 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3409 /// \brief Source range of the loop condition.
3410 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3411 /// \brief Source range of the loop increment.
3412 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3413 /// \brief True if the step should be subtracted.
3414 bool ShouldSubtractStep() const { return SubtractStep; }
3415 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003416 Expr *
3417 BuildNumIterations(Scope *S, const bool LimitedType,
3418 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003419 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003420 Expr *BuildPreCond(Scope *S, Expr *Cond,
3421 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003422 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003423 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3424 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003425 /// \brief Build reference expression to the private counter be used for
3426 /// codegen.
3427 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003428 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003429 Expr *BuildCounterInit() const;
3430 /// \brief Build step of the counter be used for codegen.
3431 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003432 /// \brief Return true if any expression is dependent.
3433 bool Dependent() const;
3434
3435private:
3436 /// \brief Check the right-hand side of an assignment in the increment
3437 /// expression.
3438 bool CheckIncRHS(Expr *RHS);
3439 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003440 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003441 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003442 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003443 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003444 /// \brief Helper to set loop increment.
3445 bool SetStep(Expr *NewStep, bool Subtract);
3446};
3447
3448bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003449 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003450 assert(!LB && !UB && !Step);
3451 return false;
3452 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003453 return LCDecl->getType()->isDependentType() ||
3454 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3455 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003456}
3457
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003458bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3459 Expr *NewLCRefExpr,
3460 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003461 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003463 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003464 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003465 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003466 LCDecl = getCanonicalDecl(NewLCDecl);
3467 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003468 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3469 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003470 if ((Ctor->isCopyOrMoveConstructor() ||
3471 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3472 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003473 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003474 LB = NewLB;
3475 return false;
3476}
3477
3478bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003479 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003480 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003481 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3482 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003483 if (!NewUB)
3484 return true;
3485 UB = NewUB;
3486 TestIsLessOp = LessOp;
3487 TestIsStrictOp = StrictOp;
3488 ConditionSrcRange = SR;
3489 ConditionLoc = SL;
3490 return false;
3491}
3492
3493bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3494 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003495 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003496 if (!NewStep)
3497 return true;
3498 if (!NewStep->isValueDependent()) {
3499 // Check that the step is integer expression.
3500 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003501 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3502 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003503 if (Val.isInvalid())
3504 return true;
3505 NewStep = Val.get();
3506
3507 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3508 // If test-expr is of form var relational-op b and relational-op is < or
3509 // <= then incr-expr must cause var to increase on each iteration of the
3510 // loop. If test-expr is of form var relational-op b and relational-op is
3511 // > or >= then incr-expr must cause var to decrease on each iteration of
3512 // the loop.
3513 // If test-expr is of form b relational-op var and relational-op is < or
3514 // <= then incr-expr must cause var to decrease on each iteration of the
3515 // loop. If test-expr is of form b relational-op var and relational-op is
3516 // > or >= then incr-expr must cause var to increase on each iteration of
3517 // the loop.
3518 llvm::APSInt Result;
3519 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3520 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3521 bool IsConstNeg =
3522 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003523 bool IsConstPos =
3524 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003525 bool IsConstZero = IsConstant && !Result.getBoolValue();
3526 if (UB && (IsConstZero ||
3527 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003528 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003529 SemaRef.Diag(NewStep->getExprLoc(),
3530 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003531 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003532 SemaRef.Diag(ConditionLoc,
3533 diag::note_omp_loop_cond_requres_compatible_incr)
3534 << TestIsLessOp << ConditionSrcRange;
3535 return true;
3536 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003537 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003538 NewStep =
3539 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3540 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003541 Subtract = !Subtract;
3542 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003543 }
3544
3545 Step = NewStep;
3546 SubtractStep = Subtract;
3547 return false;
3548}
3549
Alexey Bataev9c821032015-04-30 04:23:23 +00003550bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003551 // Check init-expr for canonical loop form and save loop counter
3552 // variable - #Var and its initialization value - #LB.
3553 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3554 // var = lb
3555 // integer-type var = lb
3556 // random-access-iterator-type var = lb
3557 // pointer-type var = lb
3558 //
3559 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003560 if (EmitDiags) {
3561 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3562 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003563 return true;
3564 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003565 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3566 if (!ExprTemp->cleanupsHaveSideEffects())
3567 S = ExprTemp->getSubExpr();
3568
Alexander Musmana5f070a2014-10-01 06:03:56 +00003569 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003570 if (Expr *E = dyn_cast<Expr>(S))
3571 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003572 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003573 if (BO->getOpcode() == BO_Assign) {
3574 auto *LHS = BO->getLHS()->IgnoreParens();
3575 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3576 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3577 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3578 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3579 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3580 }
3581 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3582 if (ME->isArrow() &&
3583 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3584 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3585 }
3586 }
David Majnemer9d168222016-08-05 17:44:54 +00003587 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003588 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003589 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003590 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003591 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003592 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003593 SemaRef.Diag(S->getLocStart(),
3594 diag::ext_omp_loop_not_canonical_init)
3595 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003596 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003597 }
3598 }
3599 }
David Majnemer9d168222016-08-05 17:44:54 +00003600 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003601 if (CE->getOperator() == OO_Equal) {
3602 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003603 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003604 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3605 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3606 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3607 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3608 }
3609 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3610 if (ME->isArrow() &&
3611 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3612 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3613 }
3614 }
3615 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003616
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003617 if (Dependent() || SemaRef.CurContext->isDependentContext())
3618 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003619 if (EmitDiags) {
3620 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3621 << S->getSourceRange();
3622 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003623 return true;
3624}
3625
Alexey Bataev23b69422014-06-18 07:08:49 +00003626/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003627/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003628static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003629 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003630 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003631 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003632 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3633 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003634 if ((Ctor->isCopyOrMoveConstructor() ||
3635 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3636 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003637 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003638 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003639 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003640 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003641 }
3642 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3643 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3644 return getCanonicalDecl(ME->getMemberDecl());
3645 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003646}
3647
3648bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3649 // Check test-expr for canonical form, save upper-bound UB, flags for
3650 // less/greater and for strict/non-strict comparison.
3651 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3652 // var relational-op b
3653 // b relational-op var
3654 //
3655 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003656 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003657 return true;
3658 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003659 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003660 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003661 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003662 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003663 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003664 return SetUB(BO->getRHS(),
3665 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3666 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3667 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003668 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003669 return SetUB(BO->getLHS(),
3670 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3671 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3672 BO->getSourceRange(), BO->getOperatorLoc());
3673 }
David Majnemer9d168222016-08-05 17:44:54 +00003674 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003675 if (CE->getNumArgs() == 2) {
3676 auto Op = CE->getOperator();
3677 switch (Op) {
3678 case OO_Greater:
3679 case OO_GreaterEqual:
3680 case OO_Less:
3681 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003682 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003683 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3684 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3685 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003686 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003687 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3688 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3689 CE->getOperatorLoc());
3690 break;
3691 default:
3692 break;
3693 }
3694 }
3695 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 if (Dependent() || SemaRef.CurContext->isDependentContext())
3697 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003698 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003699 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003700 return true;
3701}
3702
3703bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3704 // RHS of canonical loop form increment can be:
3705 // var + incr
3706 // incr + var
3707 // var - incr
3708 //
3709 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003710 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003711 if (BO->isAdditiveOp()) {
3712 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003713 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003714 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003715 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003716 return SetStep(BO->getLHS(), false);
3717 }
David Majnemer9d168222016-08-05 17:44:54 +00003718 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003719 bool IsAdd = CE->getOperator() == OO_Plus;
3720 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003721 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003722 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003723 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003724 return SetStep(CE->getArg(0), false);
3725 }
3726 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003727 if (Dependent() || SemaRef.CurContext->isDependentContext())
3728 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003729 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003730 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003731 return true;
3732}
3733
3734bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3735 // Check incr-expr for canonical loop form and return true if it
3736 // does not conform.
3737 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3738 // ++var
3739 // var++
3740 // --var
3741 // var--
3742 // var += incr
3743 // var -= incr
3744 // var = var + incr
3745 // var = incr + var
3746 // var = var - incr
3747 //
3748 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003749 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003750 return true;
3751 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003752 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3753 if (!ExprTemp->cleanupsHaveSideEffects())
3754 S = ExprTemp->getSubExpr();
3755
Alexander Musmana5f070a2014-10-01 06:03:56 +00003756 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003757 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003758 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003759 if (UO->isIncrementDecrementOp() &&
3760 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003761 return SetStep(SemaRef
3762 .ActOnIntegerConstant(UO->getLocStart(),
3763 (UO->isDecrementOp() ? -1 : 1))
3764 .get(),
3765 false);
3766 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003767 switch (BO->getOpcode()) {
3768 case BO_AddAssign:
3769 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003770 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3772 break;
3773 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003774 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003775 return CheckIncRHS(BO->getRHS());
3776 break;
3777 default:
3778 break;
3779 }
David Majnemer9d168222016-08-05 17:44:54 +00003780 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003781 switch (CE->getOperator()) {
3782 case OO_PlusPlus:
3783 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003784 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003785 return SetStep(SemaRef
3786 .ActOnIntegerConstant(
3787 CE->getLocStart(),
3788 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3789 .get(),
3790 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003791 break;
3792 case OO_PlusEqual:
3793 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003794 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003795 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3796 break;
3797 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003798 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003799 return CheckIncRHS(CE->getArg(1));
3800 break;
3801 default:
3802 break;
3803 }
3804 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003805 if (Dependent() || SemaRef.CurContext->isDependentContext())
3806 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003807 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003808 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003809 return true;
3810}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003811
Alexey Bataev5a3af132016-03-29 08:58:54 +00003812static ExprResult
3813tryBuildCapture(Sema &SemaRef, Expr *Capture,
3814 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003815 if (SemaRef.CurContext->isDependentContext())
3816 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003817 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3818 return SemaRef.PerformImplicitConversion(
3819 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3820 /*AllowExplicit=*/true);
3821 auto I = Captures.find(Capture);
3822 if (I != Captures.end())
3823 return buildCapture(SemaRef, Capture, I->second);
3824 DeclRefExpr *Ref = nullptr;
3825 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3826 Captures[Capture] = Ref;
3827 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003828}
3829
Alexander Musmana5f070a2014-10-01 06:03:56 +00003830/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003831Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3832 Scope *S, const bool LimitedType,
3833 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003834 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003835 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003836 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003837 SemaRef.getLangOpts().CPlusPlus) {
3838 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003839 auto *UBExpr = TestIsLessOp ? UB : LB;
3840 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003841 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3842 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003843 if (!Upper || !Lower)
3844 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003845
3846 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3847
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003848 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003849 // BuildBinOp already emitted error, this one is to point user to upper
3850 // and lower bound, and to tell what is passed to 'operator-'.
3851 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3852 << Upper->getSourceRange() << Lower->getSourceRange();
3853 return nullptr;
3854 }
3855 }
3856
3857 if (!Diff.isUsable())
3858 return nullptr;
3859
3860 // Upper - Lower [- 1]
3861 if (TestIsStrictOp)
3862 Diff = SemaRef.BuildBinOp(
3863 S, DefaultLoc, BO_Sub, Diff.get(),
3864 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3865 if (!Diff.isUsable())
3866 return nullptr;
3867
3868 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003869 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3870 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003871 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003872 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003873 if (!Diff.isUsable())
3874 return nullptr;
3875
3876 // Parentheses (for dumping/debugging purposes only).
3877 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3878 if (!Diff.isUsable())
3879 return nullptr;
3880
3881 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003882 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003883 if (!Diff.isUsable())
3884 return nullptr;
3885
Alexander Musman174b3ca2014-10-06 11:16:29 +00003886 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003887 QualType Type = Diff.get()->getType();
3888 auto &C = SemaRef.Context;
3889 bool UseVarType = VarType->hasIntegerRepresentation() &&
3890 C.getTypeSize(Type) > C.getTypeSize(VarType);
3891 if (!Type->isIntegerType() || UseVarType) {
3892 unsigned NewSize =
3893 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3894 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3895 : Type->hasSignedIntegerRepresentation();
3896 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003897 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3898 Diff = SemaRef.PerformImplicitConversion(
3899 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3900 if (!Diff.isUsable())
3901 return nullptr;
3902 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003903 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003904 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003905 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3906 if (NewSize != C.getTypeSize(Type)) {
3907 if (NewSize < C.getTypeSize(Type)) {
3908 assert(NewSize == 64 && "incorrect loop var size");
3909 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3910 << InitSrcRange << ConditionSrcRange;
3911 }
3912 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003913 NewSize, Type->hasSignedIntegerRepresentation() ||
3914 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003915 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3916 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3917 Sema::AA_Converting, true);
3918 if (!Diff.isUsable())
3919 return nullptr;
3920 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003921 }
3922 }
3923
Alexander Musmana5f070a2014-10-01 06:03:56 +00003924 return Diff.get();
3925}
3926
Alexey Bataev5a3af132016-03-29 08:58:54 +00003927Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3928 Scope *S, Expr *Cond,
3929 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003930 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3931 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3932 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003933
Alexey Bataev5a3af132016-03-29 08:58:54 +00003934 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3935 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3936 if (!NewLB.isUsable() || !NewUB.isUsable())
3937 return nullptr;
3938
Alexey Bataev62dbb972015-04-22 11:59:37 +00003939 auto CondExpr = SemaRef.BuildBinOp(
3940 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3941 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003942 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003943 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003944 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3945 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003946 CondExpr = SemaRef.PerformImplicitConversion(
3947 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3948 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003949 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003950 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3951 // Otherwise use original loop conditon and evaluate it in runtime.
3952 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3953}
3954
Alexander Musmana5f070a2014-10-01 06:03:56 +00003955/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003956DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003957 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003958 auto *VD = dyn_cast<VarDecl>(LCDecl);
3959 if (!VD) {
3960 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3961 auto *Ref = buildDeclRefExpr(
3962 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003963 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3964 // If the loop control decl is explicitly marked as private, do not mark it
3965 // as captured again.
3966 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3967 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003968 return Ref;
3969 }
3970 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003971 DefaultLoc);
3972}
3973
3974Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003975 if (LCDecl && !LCDecl->isInvalidDecl()) {
3976 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003977 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003978 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3979 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003980 if (PrivateVar->isInvalidDecl())
3981 return nullptr;
3982 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3983 }
3984 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003985}
3986
Samuel Antao4c8035b2016-12-12 18:00:20 +00003987/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003988Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3989
3990/// \brief Build step of the counter be used for codegen.
3991Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3992
3993/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003994struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003995 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003996 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003997 /// \brief This expression calculates the number of iterations in the loop.
3998 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003999 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004000 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004001 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004002 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004003 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004004 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004005 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004006 /// \brief This is step for the #CounterVar used to generate its update:
4007 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004008 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004009 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004010 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004011 /// \brief Source range of the loop init.
4012 SourceRange InitSrcRange;
4013 /// \brief Source range of the loop condition.
4014 SourceRange CondSrcRange;
4015 /// \brief Source range of the loop increment.
4016 SourceRange IncSrcRange;
4017};
4018
Alexey Bataev23b69422014-06-18 07:08:49 +00004019} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004020
Alexey Bataev9c821032015-04-30 04:23:23 +00004021void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4022 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4023 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004024 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4025 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004026 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4027 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004028 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4029 if (auto *D = ISC.GetLoopDecl()) {
4030 auto *VD = dyn_cast<VarDecl>(D);
4031 if (!VD) {
4032 if (auto *Private = IsOpenMPCapturedDecl(D))
4033 VD = Private;
4034 else {
4035 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4036 /*WithInit=*/false);
4037 VD = cast<VarDecl>(Ref->getDecl());
4038 }
4039 }
4040 DSAStack->addLoopControlVariable(D, VD);
4041 }
4042 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004043 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004044 }
4045}
4046
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004047/// \brief Called on a for stmt to check and extract its iteration space
4048/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004049static bool CheckOpenMPIterationSpace(
4050 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4051 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004052 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004053 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004054 LoopIterationSpace &ResultIterSpace,
4055 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004056 // OpenMP [2.6, Canonical Loop Form]
4057 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004058 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004059 if (!For) {
4060 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004061 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4062 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4063 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4064 if (NestedLoopCount > 1) {
4065 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4066 SemaRef.Diag(DSA.getConstructLoc(),
4067 diag::note_omp_collapse_ordered_expr)
4068 << 2 << CollapseLoopCountExpr->getSourceRange()
4069 << OrderedLoopCountExpr->getSourceRange();
4070 else if (CollapseLoopCountExpr)
4071 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4072 diag::note_omp_collapse_ordered_expr)
4073 << 0 << CollapseLoopCountExpr->getSourceRange();
4074 else
4075 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4076 diag::note_omp_collapse_ordered_expr)
4077 << 1 << OrderedLoopCountExpr->getSourceRange();
4078 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004079 return true;
4080 }
4081 assert(For->getBody());
4082
4083 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4084
4085 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004086 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004087 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004088 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004089
4090 bool HasErrors = false;
4091
4092 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004093 if (auto *LCDecl = ISC.GetLoopDecl()) {
4094 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004095
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004096 // OpenMP [2.6, Canonical Loop Form]
4097 // Var is one of the following:
4098 // A variable of signed or unsigned integer type.
4099 // For C++, a variable of a random access iterator type.
4100 // For C, a variable of a pointer type.
4101 auto VarType = LCDecl->getType().getNonReferenceType();
4102 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4103 !VarType->isPointerType() &&
4104 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4105 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4106 << SemaRef.getLangOpts().CPlusPlus;
4107 HasErrors = true;
4108 }
4109
4110 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4111 // a Construct
4112 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4113 // parallel for construct is (are) private.
4114 // The loop iteration variable in the associated for-loop of a simd
4115 // construct with just one associated for-loop is linear with a
4116 // constant-linear-step that is the increment of the associated for-loop.
4117 // Exclude loop var from the list of variables with implicitly defined data
4118 // sharing attributes.
4119 VarsWithImplicitDSA.erase(LCDecl);
4120
4121 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4122 // in a Construct, C/C++].
4123 // The loop iteration variable in the associated for-loop of a simd
4124 // construct with just one associated for-loop may be listed in a linear
4125 // clause with a constant-linear-step that is the increment of the
4126 // associated for-loop.
4127 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4128 // parallel for construct may be listed in a private or lastprivate clause.
4129 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4130 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4131 // declared in the loop and it is predetermined as a private.
4132 auto PredeterminedCKind =
4133 isOpenMPSimdDirective(DKind)
4134 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4135 : OMPC_private;
4136 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4137 DVar.CKind != PredeterminedCKind) ||
4138 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4139 isOpenMPDistributeDirective(DKind)) &&
4140 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4141 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4142 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4143 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4144 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4145 << getOpenMPClauseName(PredeterminedCKind);
4146 if (DVar.RefExpr == nullptr)
4147 DVar.CKind = PredeterminedCKind;
4148 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4149 HasErrors = true;
4150 } else if (LoopDeclRefExpr != nullptr) {
4151 // Make the loop iteration variable private (for worksharing constructs),
4152 // linear (for simd directives with the only one associated loop) or
4153 // lastprivate (for simd directives with several collapsed or ordered
4154 // loops).
4155 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004156 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4157 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004158 /*FromParent=*/false);
4159 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4160 }
4161
4162 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4163
4164 // Check test-expr.
4165 HasErrors |= ISC.CheckCond(For->getCond());
4166
4167 // Check incr-expr.
4168 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004169 }
4170
Alexander Musmana5f070a2014-10-01 06:03:56 +00004171 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004172 return HasErrors;
4173
Alexander Musmana5f070a2014-10-01 06:03:56 +00004174 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004175 ResultIterSpace.PreCond =
4176 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004177 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004178 DSA.getCurScope(),
4179 (isOpenMPWorksharingDirective(DKind) ||
4180 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4181 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004182 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004183 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004184 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4185 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4186 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4187 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4188 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4189 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4190
Alexey Bataev62dbb972015-04-22 11:59:37 +00004191 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4192 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004193 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004194 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004195 ResultIterSpace.CounterInit == nullptr ||
4196 ResultIterSpace.CounterStep == nullptr);
4197
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004198 return HasErrors;
4199}
4200
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004201/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004202static ExprResult
4203BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4204 ExprResult Start,
4205 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004206 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004207 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4208 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004209 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004210 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004211 VarRef.get()->getType())) {
4212 NewStart = SemaRef.PerformImplicitConversion(
4213 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4214 /*AllowExplicit=*/true);
4215 if (!NewStart.isUsable())
4216 return ExprError();
4217 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004218
4219 auto Init =
4220 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4221 return Init;
4222}
4223
Alexander Musmana5f070a2014-10-01 06:03:56 +00004224/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004225static ExprResult
4226BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4227 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4228 ExprResult Step, bool Subtract,
4229 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004230 // Add parentheses (for debugging purposes only).
4231 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4232 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4233 !Step.isUsable())
4234 return ExprError();
4235
Alexey Bataev5a3af132016-03-29 08:58:54 +00004236 ExprResult NewStep = Step;
4237 if (Captures)
4238 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004239 if (NewStep.isInvalid())
4240 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004241 ExprResult Update =
4242 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004243 if (!Update.isUsable())
4244 return ExprError();
4245
Alexey Bataevc0214e02016-02-16 12:13:49 +00004246 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4247 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004248 ExprResult NewStart = Start;
4249 if (Captures)
4250 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004251 if (NewStart.isInvalid())
4252 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004253
Alexey Bataevc0214e02016-02-16 12:13:49 +00004254 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4255 ExprResult SavedUpdate = Update;
4256 ExprResult UpdateVal;
4257 if (VarRef.get()->getType()->isOverloadableType() ||
4258 NewStart.get()->getType()->isOverloadableType() ||
4259 Update.get()->getType()->isOverloadableType()) {
4260 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4261 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4262 Update =
4263 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4264 if (Update.isUsable()) {
4265 UpdateVal =
4266 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4267 VarRef.get(), SavedUpdate.get());
4268 if (UpdateVal.isUsable()) {
4269 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4270 UpdateVal.get());
4271 }
4272 }
4273 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4274 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004275
Alexey Bataevc0214e02016-02-16 12:13:49 +00004276 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4277 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4278 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4279 NewStart.get(), SavedUpdate.get());
4280 if (!Update.isUsable())
4281 return ExprError();
4282
Alexey Bataev11481f52016-02-17 10:29:05 +00004283 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4284 VarRef.get()->getType())) {
4285 Update = SemaRef.PerformImplicitConversion(
4286 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4287 if (!Update.isUsable())
4288 return ExprError();
4289 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004290
4291 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4292 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004293 return Update;
4294}
4295
4296/// \brief Convert integer expression \a E to make it have at least \a Bits
4297/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004298static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004299 if (E == nullptr)
4300 return ExprError();
4301 auto &C = SemaRef.Context;
4302 QualType OldType = E->getType();
4303 unsigned HasBits = C.getTypeSize(OldType);
4304 if (HasBits >= Bits)
4305 return ExprResult(E);
4306 // OK to convert to signed, because new type has more bits than old.
4307 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4308 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4309 true);
4310}
4311
4312/// \brief Check if the given expression \a E is a constant integer that fits
4313/// into \a Bits bits.
4314static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4315 if (E == nullptr)
4316 return false;
4317 llvm::APSInt Result;
4318 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4319 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4320 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004321}
4322
Alexey Bataev5a3af132016-03-29 08:58:54 +00004323/// Build preinits statement for the given declarations.
4324static Stmt *buildPreInits(ASTContext &Context,
4325 SmallVectorImpl<Decl *> &PreInits) {
4326 if (!PreInits.empty()) {
4327 return new (Context) DeclStmt(
4328 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4329 SourceLocation(), SourceLocation());
4330 }
4331 return nullptr;
4332}
4333
4334/// Build preinits statement for the given declarations.
4335static Stmt *buildPreInits(ASTContext &Context,
4336 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4337 if (!Captures.empty()) {
4338 SmallVector<Decl *, 16> PreInits;
4339 for (auto &Pair : Captures)
4340 PreInits.push_back(Pair.second->getDecl());
4341 return buildPreInits(Context, PreInits);
4342 }
4343 return nullptr;
4344}
4345
4346/// Build postupdate expression for the given list of postupdates expressions.
4347static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4348 Expr *PostUpdate = nullptr;
4349 if (!PostUpdates.empty()) {
4350 for (auto *E : PostUpdates) {
4351 Expr *ConvE = S.BuildCStyleCastExpr(
4352 E->getExprLoc(),
4353 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4354 E->getExprLoc(), E)
4355 .get();
4356 PostUpdate = PostUpdate
4357 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4358 PostUpdate, ConvE)
4359 .get()
4360 : ConvE;
4361 }
4362 }
4363 return PostUpdate;
4364}
4365
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004366/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004367/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4368/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004369static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004370CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4371 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4372 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004373 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004374 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004375 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004376 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004377 // Found 'collapse' clause - calculate collapse number.
4378 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004379 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004380 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004381 }
4382 if (OrderedLoopCountExpr) {
4383 // Found 'ordered' clause - calculate collapse number.
4384 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004385 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4386 if (Result.getLimitedValue() < NestedLoopCount) {
4387 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4388 diag::err_omp_wrong_ordered_loop_count)
4389 << OrderedLoopCountExpr->getSourceRange();
4390 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4391 diag::note_collapse_loop_count)
4392 << CollapseLoopCountExpr->getSourceRange();
4393 }
4394 NestedLoopCount = Result.getLimitedValue();
4395 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004396 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004397 // This is helper routine for loop directives (e.g., 'for', 'simd',
4398 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004399 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004400 SmallVector<LoopIterationSpace, 4> IterSpaces;
4401 IterSpaces.resize(NestedLoopCount);
4402 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004403 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004404 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004405 NestedLoopCount, CollapseLoopCountExpr,
4406 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004407 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004408 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004409 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004410 // OpenMP [2.8.1, simd construct, Restrictions]
4411 // All loops associated with the construct must be perfectly nested; that
4412 // is, there must be no intervening code nor any OpenMP directive between
4413 // any two loops.
4414 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004415 }
4416
Alexander Musmana5f070a2014-10-01 06:03:56 +00004417 Built.clear(/* size */ NestedLoopCount);
4418
4419 if (SemaRef.CurContext->isDependentContext())
4420 return NestedLoopCount;
4421
4422 // An example of what is generated for the following code:
4423 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004424 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004425 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004426 // for (k = 0; k < NK; ++k)
4427 // for (j = J0; j < NJ; j+=2) {
4428 // <loop body>
4429 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004430 //
4431 // We generate the code below.
4432 // Note: the loop body may be outlined in CodeGen.
4433 // Note: some counters may be C++ classes, operator- is used to find number of
4434 // iterations and operator+= to calculate counter value.
4435 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4436 // or i64 is currently supported).
4437 //
4438 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4439 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4440 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4441 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4442 // // similar updates for vars in clauses (e.g. 'linear')
4443 // <loop body (using local i and j)>
4444 // }
4445 // i = NI; // assign final values of counters
4446 // j = NJ;
4447 //
4448
4449 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4450 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004451 // Precondition tests if there is at least one iteration (all conditions are
4452 // true).
4453 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004454 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004455 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004456 32 /* Bits */, SemaRef
4457 .PerformImplicitConversion(
4458 N0->IgnoreImpCasts(), N0->getType(),
4459 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004460 .get(),
4461 SemaRef);
4462 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004463 64 /* Bits */, SemaRef
4464 .PerformImplicitConversion(
4465 N0->IgnoreImpCasts(), N0->getType(),
4466 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004467 .get(),
4468 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004469
4470 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4471 return NestedLoopCount;
4472
4473 auto &C = SemaRef.Context;
4474 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4475
4476 Scope *CurScope = DSA.getCurScope();
4477 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004478 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004479 PreCond =
4480 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4481 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004482 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004483 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004484 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004485 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4486 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004487 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004488 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004489 SemaRef
4490 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4491 Sema::AA_Converting,
4492 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004493 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004494 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004495 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004496 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004497 SemaRef
4498 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4499 Sema::AA_Converting,
4500 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004501 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004502 }
4503
4504 // Choose either the 32-bit or 64-bit version.
4505 ExprResult LastIteration = LastIteration64;
4506 if (LastIteration32.isUsable() &&
4507 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4508 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4509 FitsInto(
4510 32 /* Bits */,
4511 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4512 LastIteration64.get(), SemaRef)))
4513 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004514 QualType VType = LastIteration.get()->getType();
4515 QualType RealVType = VType;
4516 QualType StrideVType = VType;
4517 if (isOpenMPTaskLoopDirective(DKind)) {
4518 VType =
4519 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4520 StrideVType =
4521 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4522 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004523
4524 if (!LastIteration.isUsable())
4525 return 0;
4526
4527 // Save the number of iterations.
4528 ExprResult NumIterations = LastIteration;
4529 {
4530 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004531 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4532 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004533 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4534 if (!LastIteration.isUsable())
4535 return 0;
4536 }
4537
4538 // Calculate the last iteration number beforehand instead of doing this on
4539 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4540 llvm::APSInt Result;
4541 bool IsConstant =
4542 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4543 ExprResult CalcLastIteration;
4544 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004545 ExprResult SaveRef =
4546 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004547 LastIteration = SaveRef;
4548
4549 // Prepare SaveRef + 1.
4550 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004551 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004552 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4553 if (!NumIterations.isUsable())
4554 return 0;
4555 }
4556
4557 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4558
David Majnemer9d168222016-08-05 17:44:54 +00004559 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004560 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004561 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4562 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004563 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004564 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4565 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004566 SemaRef.AddInitializerToDecl(LBDecl,
4567 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4568 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004569
4570 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004571 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4572 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004573 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004574 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004575
4576 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4577 // This will be used to implement clause 'lastprivate'.
4578 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004579 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4580 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004581 SemaRef.AddInitializerToDecl(ILDecl,
4582 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4583 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004584
4585 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004586 VarDecl *STDecl =
4587 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4588 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004589 SemaRef.AddInitializerToDecl(STDecl,
4590 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4591 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004592
4593 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004594 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004595 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4596 UB.get(), LastIteration.get());
4597 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4598 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4599 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4600 CondOp.get());
4601 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004602
4603 // If we have a combined directive that combines 'distribute', 'for' or
4604 // 'simd' we need to be able to access the bounds of the schedule of the
4605 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4606 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4607 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004608
Carlo Bertolliffafe102017-04-20 00:39:39 +00004609 // Lower bound variable, initialized with zero.
4610 VarDecl *CombLBDecl =
4611 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4612 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4613 SemaRef.AddInitializerToDecl(
4614 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4615 /*DirectInit*/ false);
4616
4617 // Upper bound variable, initialized with last iteration number.
4618 VarDecl *CombUBDecl =
4619 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4620 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4621 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4622 /*DirectInit*/ false);
4623
4624 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4625 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4626 ExprResult CombCondOp =
4627 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4628 LastIteration.get(), CombUB.get());
4629 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4630 CombCondOp.get());
4631 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4632
4633 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004634 // We expect to have at least 2 more parameters than the 'parallel'
4635 // directive does - the lower and upper bounds of the previous schedule.
4636 assert(CD->getNumParams() >= 4 &&
4637 "Unexpected number of parameters in loop combined directive");
4638
4639 // Set the proper type for the bounds given what we learned from the
4640 // enclosed loops.
4641 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4642 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4643
4644 // Previous lower and upper bounds are obtained from the region
4645 // parameters.
4646 PrevLB =
4647 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4648 PrevUB =
4649 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4650 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004651 }
4652
4653 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004654 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004655 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004656 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004657 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4658 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004659 Expr *RHS =
4660 (isOpenMPWorksharingDirective(DKind) ||
4661 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4662 ? LB.get()
4663 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004664 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4665 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004666
4667 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4668 Expr *CombRHS =
4669 (isOpenMPWorksharingDirective(DKind) ||
4670 isOpenMPTaskLoopDirective(DKind) ||
4671 isOpenMPDistributeDirective(DKind))
4672 ? CombLB.get()
4673 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4674 CombInit =
4675 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4676 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4677 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004678 }
4679
Alexander Musmanc6388682014-12-15 07:07:06 +00004680 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004681 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004682 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004683 (isOpenMPWorksharingDirective(DKind) ||
4684 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004685 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4686 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4687 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004688 ExprResult CombCond;
4689 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4690 CombCond =
4691 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4692 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004693 // Loop increment (IV = IV + 1)
4694 SourceLocation IncLoc;
4695 ExprResult Inc =
4696 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4697 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4698 if (!Inc.isUsable())
4699 return 0;
4700 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004701 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4702 if (!Inc.isUsable())
4703 return 0;
4704
4705 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4706 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004707 // In combined construct, add combined version that use CombLB and CombUB
4708 // base variables for the update
4709 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004710 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4711 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004712 // LB + ST
4713 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4714 if (!NextLB.isUsable())
4715 return 0;
4716 // LB = LB + ST
4717 NextLB =
4718 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4719 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4720 if (!NextLB.isUsable())
4721 return 0;
4722 // UB + ST
4723 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4724 if (!NextUB.isUsable())
4725 return 0;
4726 // UB = UB + ST
4727 NextUB =
4728 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4729 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4730 if (!NextUB.isUsable())
4731 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004732 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4733 CombNextLB =
4734 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4735 if (!NextLB.isUsable())
4736 return 0;
4737 // LB = LB + ST
4738 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4739 CombNextLB.get());
4740 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4741 if (!CombNextLB.isUsable())
4742 return 0;
4743 // UB + ST
4744 CombNextUB =
4745 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4746 if (!CombNextUB.isUsable())
4747 return 0;
4748 // UB = UB + ST
4749 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4750 CombNextUB.get());
4751 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4752 if (!CombNextUB.isUsable())
4753 return 0;
4754 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004755 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004756
Carlo Bertolliffafe102017-04-20 00:39:39 +00004757 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004758 // directive with for as IV = IV + ST; ensure upper bound expression based
4759 // on PrevUB instead of NumIterations - used to implement 'for' when found
4760 // in combination with 'distribute', like in 'distribute parallel for'
4761 SourceLocation DistIncLoc;
4762 ExprResult DistCond, DistInc, PrevEUB;
4763 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4764 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4765 assert(DistCond.isUsable() && "distribute cond expr was not built");
4766
4767 DistInc =
4768 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4769 assert(DistInc.isUsable() && "distribute inc expr was not built");
4770 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4771 DistInc.get());
4772 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4773 assert(DistInc.isUsable() && "distribute inc expr was not built");
4774
4775 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4776 // construct
4777 SourceLocation DistEUBLoc;
4778 ExprResult IsUBGreater =
4779 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4780 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4781 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4782 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4783 CondOp.get());
4784 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4785 }
4786
Alexander Musmana5f070a2014-10-01 06:03:56 +00004787 // Build updates and final values of the loop counters.
4788 bool HasErrors = false;
4789 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004790 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004791 Built.Updates.resize(NestedLoopCount);
4792 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004793 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004794 {
4795 ExprResult Div;
4796 // Go from inner nested loop to outer.
4797 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4798 LoopIterationSpace &IS = IterSpaces[Cnt];
4799 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4800 // Build: Iter = (IV / Div) % IS.NumIters
4801 // where Div is product of previous iterations' IS.NumIters.
4802 ExprResult Iter;
4803 if (Div.isUsable()) {
4804 Iter =
4805 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4806 } else {
4807 Iter = IV;
4808 assert((Cnt == (int)NestedLoopCount - 1) &&
4809 "unusable div expected on first iteration only");
4810 }
4811
4812 if (Cnt != 0 && Iter.isUsable())
4813 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4814 IS.NumIterations);
4815 if (!Iter.isUsable()) {
4816 HasErrors = true;
4817 break;
4818 }
4819
Alexey Bataev39f915b82015-05-08 10:41:21 +00004820 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004821 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4822 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4823 IS.CounterVar->getExprLoc(),
4824 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004825 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004826 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004827 if (!Init.isUsable()) {
4828 HasErrors = true;
4829 break;
4830 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004831 ExprResult Update = BuildCounterUpdate(
4832 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4833 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004834 if (!Update.isUsable()) {
4835 HasErrors = true;
4836 break;
4837 }
4838
4839 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4840 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004841 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004842 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004843 if (!Final.isUsable()) {
4844 HasErrors = true;
4845 break;
4846 }
4847
4848 // Build Div for the next iteration: Div <- Div * IS.NumIters
4849 if (Cnt != 0) {
4850 if (Div.isUnset())
4851 Div = IS.NumIterations;
4852 else
4853 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4854 IS.NumIterations);
4855
4856 // Add parentheses (for debugging purposes only).
4857 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004858 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004859 if (!Div.isUsable()) {
4860 HasErrors = true;
4861 break;
4862 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004863 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004864 }
4865 if (!Update.isUsable() || !Final.isUsable()) {
4866 HasErrors = true;
4867 break;
4868 }
4869 // Save results
4870 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004871 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004872 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004873 Built.Updates[Cnt] = Update.get();
4874 Built.Finals[Cnt] = Final.get();
4875 }
4876 }
4877
4878 if (HasErrors)
4879 return 0;
4880
4881 // Save results
4882 Built.IterationVarRef = IV.get();
4883 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004884 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004885 Built.CalcLastIteration =
4886 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004887 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004888 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004889 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004890 Built.Init = Init.get();
4891 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004892 Built.LB = LB.get();
4893 Built.UB = UB.get();
4894 Built.IL = IL.get();
4895 Built.ST = ST.get();
4896 Built.EUB = EUB.get();
4897 Built.NLB = NextLB.get();
4898 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004899 Built.PrevLB = PrevLB.get();
4900 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004901 Built.DistInc = DistInc.get();
4902 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004903 Built.DistCombinedFields.LB = CombLB.get();
4904 Built.DistCombinedFields.UB = CombUB.get();
4905 Built.DistCombinedFields.EUB = CombEUB.get();
4906 Built.DistCombinedFields.Init = CombInit.get();
4907 Built.DistCombinedFields.Cond = CombCond.get();
4908 Built.DistCombinedFields.NLB = CombNextLB.get();
4909 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004910
Alexey Bataev8b427062016-05-25 12:36:08 +00004911 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4912 // Fill data for doacross depend clauses.
4913 for (auto Pair : DSA.getDoacrossDependClauses()) {
4914 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4915 Pair.first->setCounterValue(CounterVal);
4916 else {
4917 if (NestedLoopCount != Pair.second.size() ||
4918 NestedLoopCount != LoopMultipliers.size() + 1) {
4919 // Erroneous case - clause has some problems.
4920 Pair.first->setCounterValue(CounterVal);
4921 continue;
4922 }
4923 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4924 auto I = Pair.second.rbegin();
4925 auto IS = IterSpaces.rbegin();
4926 auto ILM = LoopMultipliers.rbegin();
4927 Expr *UpCounterVal = CounterVal;
4928 Expr *Multiplier = nullptr;
4929 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4930 if (I->first) {
4931 assert(IS->CounterStep);
4932 Expr *NormalizedOffset =
4933 SemaRef
4934 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4935 I->first, IS->CounterStep)
4936 .get();
4937 if (Multiplier) {
4938 NormalizedOffset =
4939 SemaRef
4940 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4941 NormalizedOffset, Multiplier)
4942 .get();
4943 }
4944 assert(I->second == OO_Plus || I->second == OO_Minus);
4945 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004946 UpCounterVal = SemaRef
4947 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4948 UpCounterVal, NormalizedOffset)
4949 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004950 }
4951 Multiplier = *ILM;
4952 ++I;
4953 ++IS;
4954 ++ILM;
4955 }
4956 Pair.first->setCounterValue(UpCounterVal);
4957 }
4958 }
4959
Alexey Bataevabfc0692014-06-25 06:52:00 +00004960 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004961}
4962
Alexey Bataev10e775f2015-07-30 11:36:16 +00004963static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004964 auto CollapseClauses =
4965 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4966 if (CollapseClauses.begin() != CollapseClauses.end())
4967 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004968 return nullptr;
4969}
4970
Alexey Bataev10e775f2015-07-30 11:36:16 +00004971static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004972 auto OrderedClauses =
4973 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4974 if (OrderedClauses.begin() != OrderedClauses.end())
4975 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004976 return nullptr;
4977}
4978
Kelvin Lic5609492016-07-15 04:39:07 +00004979static bool checkSimdlenSafelenSpecified(Sema &S,
4980 const ArrayRef<OMPClause *> Clauses) {
4981 OMPSafelenClause *Safelen = nullptr;
4982 OMPSimdlenClause *Simdlen = nullptr;
4983
4984 for (auto *Clause : Clauses) {
4985 if (Clause->getClauseKind() == OMPC_safelen)
4986 Safelen = cast<OMPSafelenClause>(Clause);
4987 else if (Clause->getClauseKind() == OMPC_simdlen)
4988 Simdlen = cast<OMPSimdlenClause>(Clause);
4989 if (Safelen && Simdlen)
4990 break;
4991 }
4992
4993 if (Simdlen && Safelen) {
4994 llvm::APSInt SimdlenRes, SafelenRes;
4995 auto SimdlenLength = Simdlen->getSimdlen();
4996 auto SafelenLength = Safelen->getSafelen();
4997 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4998 SimdlenLength->isInstantiationDependent() ||
4999 SimdlenLength->containsUnexpandedParameterPack())
5000 return false;
5001 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5002 SafelenLength->isInstantiationDependent() ||
5003 SafelenLength->containsUnexpandedParameterPack())
5004 return false;
5005 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5006 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5007 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5008 // If both simdlen and safelen clauses are specified, the value of the
5009 // simdlen parameter must be less than or equal to the value of the safelen
5010 // parameter.
5011 if (SimdlenRes > SafelenRes) {
5012 S.Diag(SimdlenLength->getExprLoc(),
5013 diag::err_omp_wrong_simdlen_safelen_values)
5014 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5015 return true;
5016 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005017 }
5018 return false;
5019}
5020
Alexey Bataev4acb8592014-07-07 13:01:15 +00005021StmtResult Sema::ActOnOpenMPSimdDirective(
5022 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5023 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005024 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005025 if (!AStmt)
5026 return StmtError();
5027
5028 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005029 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005030 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5031 // define the nested loops number.
5032 unsigned NestedLoopCount = CheckOpenMPLoop(
5033 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5034 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005035 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005036 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005037
Alexander Musmana5f070a2014-10-01 06:03:56 +00005038 assert((CurContext->isDependentContext() || B.builtAll()) &&
5039 "omp simd loop exprs were not built");
5040
Alexander Musman3276a272015-03-21 10:12:56 +00005041 if (!CurContext->isDependentContext()) {
5042 // Finalize the clauses that need pre-built expressions for CodeGen.
5043 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005044 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005045 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005046 B.NumIterations, *this, CurScope,
5047 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005048 return StmtError();
5049 }
5050 }
5051
Kelvin Lic5609492016-07-15 04:39:07 +00005052 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005053 return StmtError();
5054
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005055 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005056 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5057 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005058}
5059
Alexey Bataev4acb8592014-07-07 13:01:15 +00005060StmtResult Sema::ActOnOpenMPForDirective(
5061 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5062 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005063 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005064 if (!AStmt)
5065 return StmtError();
5066
5067 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005068 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005069 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5070 // define the nested loops number.
5071 unsigned NestedLoopCount = CheckOpenMPLoop(
5072 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5073 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005074 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005075 return StmtError();
5076
Alexander Musmana5f070a2014-10-01 06:03:56 +00005077 assert((CurContext->isDependentContext() || B.builtAll()) &&
5078 "omp for loop exprs were not built");
5079
Alexey Bataev54acd402015-08-04 11:18:19 +00005080 if (!CurContext->isDependentContext()) {
5081 // Finalize the clauses that need pre-built expressions for CodeGen.
5082 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005083 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005084 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005085 B.NumIterations, *this, CurScope,
5086 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005087 return StmtError();
5088 }
5089 }
5090
Alexey Bataevf29276e2014-06-18 04:14:57 +00005091 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005092 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005093 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005094}
5095
Alexander Musmanf82886e2014-09-18 05:12:34 +00005096StmtResult Sema::ActOnOpenMPForSimdDirective(
5097 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5098 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005099 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005100 if (!AStmt)
5101 return StmtError();
5102
5103 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005104 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005105 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5106 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005107 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005108 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5109 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5110 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005111 if (NestedLoopCount == 0)
5112 return StmtError();
5113
Alexander Musmanc6388682014-12-15 07:07:06 +00005114 assert((CurContext->isDependentContext() || B.builtAll()) &&
5115 "omp for simd loop exprs were not built");
5116
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005117 if (!CurContext->isDependentContext()) {
5118 // Finalize the clauses that need pre-built expressions for CodeGen.
5119 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005120 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005121 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005122 B.NumIterations, *this, CurScope,
5123 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005124 return StmtError();
5125 }
5126 }
5127
Kelvin Lic5609492016-07-15 04:39:07 +00005128 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005129 return StmtError();
5130
Alexander Musmanf82886e2014-09-18 05:12:34 +00005131 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005132 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5133 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005134}
5135
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005136StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5137 Stmt *AStmt,
5138 SourceLocation StartLoc,
5139 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005140 if (!AStmt)
5141 return StmtError();
5142
5143 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005144 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005145 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005146 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005147 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005148 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005149 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005150 return StmtError();
5151 // All associated statements must be '#pragma omp section' except for
5152 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005153 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005154 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5155 if (SectionStmt)
5156 Diag(SectionStmt->getLocStart(),
5157 diag::err_omp_sections_substmt_not_section);
5158 return StmtError();
5159 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005160 cast<OMPSectionDirective>(SectionStmt)
5161 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005162 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005163 } else {
5164 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5165 return StmtError();
5166 }
5167
5168 getCurFunction()->setHasBranchProtectedScope();
5169
Alexey Bataev25e5b442015-09-15 12:52:43 +00005170 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5171 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005172}
5173
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005174StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5175 SourceLocation StartLoc,
5176 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005177 if (!AStmt)
5178 return StmtError();
5179
5180 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005181
5182 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005183 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005184
Alexey Bataev25e5b442015-09-15 12:52:43 +00005185 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5186 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005187}
5188
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005189StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5190 Stmt *AStmt,
5191 SourceLocation StartLoc,
5192 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005193 if (!AStmt)
5194 return StmtError();
5195
5196 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005197
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005198 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005199
Alexey Bataev3255bf32015-01-19 05:20:46 +00005200 // OpenMP [2.7.3, single Construct, Restrictions]
5201 // The copyprivate clause must not be used with the nowait clause.
5202 OMPClause *Nowait = nullptr;
5203 OMPClause *Copyprivate = nullptr;
5204 for (auto *Clause : Clauses) {
5205 if (Clause->getClauseKind() == OMPC_nowait)
5206 Nowait = Clause;
5207 else if (Clause->getClauseKind() == OMPC_copyprivate)
5208 Copyprivate = Clause;
5209 if (Copyprivate && Nowait) {
5210 Diag(Copyprivate->getLocStart(),
5211 diag::err_omp_single_copyprivate_with_nowait);
5212 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5213 return StmtError();
5214 }
5215 }
5216
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005217 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5218}
5219
Alexander Musman80c22892014-07-17 08:54:58 +00005220StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5221 SourceLocation StartLoc,
5222 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005223 if (!AStmt)
5224 return StmtError();
5225
5226 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005227
5228 getCurFunction()->setHasBranchProtectedScope();
5229
5230 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5231}
5232
Alexey Bataev28c75412015-12-15 08:19:24 +00005233StmtResult Sema::ActOnOpenMPCriticalDirective(
5234 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5235 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005236 if (!AStmt)
5237 return StmtError();
5238
5239 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005240
Alexey Bataev28c75412015-12-15 08:19:24 +00005241 bool ErrorFound = false;
5242 llvm::APSInt Hint;
5243 SourceLocation HintLoc;
5244 bool DependentHint = false;
5245 for (auto *C : Clauses) {
5246 if (C->getClauseKind() == OMPC_hint) {
5247 if (!DirName.getName()) {
5248 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5249 ErrorFound = true;
5250 }
5251 Expr *E = cast<OMPHintClause>(C)->getHint();
5252 if (E->isTypeDependent() || E->isValueDependent() ||
5253 E->isInstantiationDependent())
5254 DependentHint = true;
5255 else {
5256 Hint = E->EvaluateKnownConstInt(Context);
5257 HintLoc = C->getLocStart();
5258 }
5259 }
5260 }
5261 if (ErrorFound)
5262 return StmtError();
5263 auto Pair = DSAStack->getCriticalWithHint(DirName);
5264 if (Pair.first && DirName.getName() && !DependentHint) {
5265 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5266 Diag(StartLoc, diag::err_omp_critical_with_hint);
5267 if (HintLoc.isValid()) {
5268 Diag(HintLoc, diag::note_omp_critical_hint_here)
5269 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5270 } else
5271 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5272 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5273 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5274 << 1
5275 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5276 /*Radix=*/10, /*Signed=*/false);
5277 } else
5278 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5279 }
5280 }
5281
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005282 getCurFunction()->setHasBranchProtectedScope();
5283
Alexey Bataev28c75412015-12-15 08:19:24 +00005284 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5285 Clauses, AStmt);
5286 if (!Pair.first && DirName.getName() && !DependentHint)
5287 DSAStack->addCriticalWithHint(Dir, Hint);
5288 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005289}
5290
Alexey Bataev4acb8592014-07-07 13:01:15 +00005291StmtResult Sema::ActOnOpenMPParallelForDirective(
5292 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5293 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005294 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005295 if (!AStmt)
5296 return StmtError();
5297
Alexey Bataev4acb8592014-07-07 13:01:15 +00005298 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5299 // 1.2.2 OpenMP Language Terminology
5300 // Structured block - An executable statement with a single entry at the
5301 // top and a single exit at the bottom.
5302 // The point of exit cannot be a branch out of the structured block.
5303 // longjmp() and throw() must not violate the entry/exit criteria.
5304 CS->getCapturedDecl()->setNothrow();
5305
Alexander Musmanc6388682014-12-15 07:07:06 +00005306 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005307 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5308 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005309 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005310 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5311 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5312 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005313 if (NestedLoopCount == 0)
5314 return StmtError();
5315
Alexander Musmana5f070a2014-10-01 06:03:56 +00005316 assert((CurContext->isDependentContext() || B.builtAll()) &&
5317 "omp parallel for loop exprs were not built");
5318
Alexey Bataev54acd402015-08-04 11:18:19 +00005319 if (!CurContext->isDependentContext()) {
5320 // Finalize the clauses that need pre-built expressions for CodeGen.
5321 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005322 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005323 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005324 B.NumIterations, *this, CurScope,
5325 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005326 return StmtError();
5327 }
5328 }
5329
Alexey Bataev4acb8592014-07-07 13:01:15 +00005330 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005331 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005332 NestedLoopCount, Clauses, AStmt, B,
5333 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005334}
5335
Alexander Musmane4e893b2014-09-23 09:33:00 +00005336StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5337 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5338 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005339 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005340 if (!AStmt)
5341 return StmtError();
5342
Alexander Musmane4e893b2014-09-23 09:33:00 +00005343 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5344 // 1.2.2 OpenMP Language Terminology
5345 // Structured block - An executable statement with a single entry at the
5346 // top and a single exit at the bottom.
5347 // The point of exit cannot be a branch out of the structured block.
5348 // longjmp() and throw() must not violate the entry/exit criteria.
5349 CS->getCapturedDecl()->setNothrow();
5350
Alexander Musmanc6388682014-12-15 07:07:06 +00005351 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005352 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5353 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005354 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005355 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5356 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5357 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005358 if (NestedLoopCount == 0)
5359 return StmtError();
5360
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005361 if (!CurContext->isDependentContext()) {
5362 // Finalize the clauses that need pre-built expressions for CodeGen.
5363 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005364 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005365 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005366 B.NumIterations, *this, CurScope,
5367 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005368 return StmtError();
5369 }
5370 }
5371
Kelvin Lic5609492016-07-15 04:39:07 +00005372 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005373 return StmtError();
5374
Alexander Musmane4e893b2014-09-23 09:33:00 +00005375 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005376 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005377 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005378}
5379
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005380StmtResult
5381Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5382 Stmt *AStmt, SourceLocation StartLoc,
5383 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005384 if (!AStmt)
5385 return StmtError();
5386
5387 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005388 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005389 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005390 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005391 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005392 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005393 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005394 return StmtError();
5395 // All associated statements must be '#pragma omp section' except for
5396 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005397 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005398 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5399 if (SectionStmt)
5400 Diag(SectionStmt->getLocStart(),
5401 diag::err_omp_parallel_sections_substmt_not_section);
5402 return StmtError();
5403 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005404 cast<OMPSectionDirective>(SectionStmt)
5405 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005406 }
5407 } else {
5408 Diag(AStmt->getLocStart(),
5409 diag::err_omp_parallel_sections_not_compound_stmt);
5410 return StmtError();
5411 }
5412
5413 getCurFunction()->setHasBranchProtectedScope();
5414
Alexey Bataev25e5b442015-09-15 12:52:43 +00005415 return OMPParallelSectionsDirective::Create(
5416 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005417}
5418
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005419StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5420 Stmt *AStmt, SourceLocation StartLoc,
5421 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005422 if (!AStmt)
5423 return StmtError();
5424
David Majnemer9d168222016-08-05 17:44:54 +00005425 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005426 // 1.2.2 OpenMP Language Terminology
5427 // Structured block - An executable statement with a single entry at the
5428 // top and a single exit at the bottom.
5429 // The point of exit cannot be a branch out of the structured block.
5430 // longjmp() and throw() must not violate the entry/exit criteria.
5431 CS->getCapturedDecl()->setNothrow();
5432
5433 getCurFunction()->setHasBranchProtectedScope();
5434
Alexey Bataev25e5b442015-09-15 12:52:43 +00005435 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5436 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005437}
5438
Alexey Bataev68446b72014-07-18 07:47:19 +00005439StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5440 SourceLocation EndLoc) {
5441 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5442}
5443
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005444StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5445 SourceLocation EndLoc) {
5446 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5447}
5448
Alexey Bataev2df347a2014-07-18 10:17:07 +00005449StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5450 SourceLocation EndLoc) {
5451 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5452}
5453
Alexey Bataev169d96a2017-07-18 20:17:46 +00005454StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5455 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005456 SourceLocation StartLoc,
5457 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005458 if (!AStmt)
5459 return StmtError();
5460
5461 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005462
5463 getCurFunction()->setHasBranchProtectedScope();
5464
Alexey Bataev169d96a2017-07-18 20:17:46 +00005465 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005466 AStmt,
5467 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005468}
5469
Alexey Bataev6125da92014-07-21 11:26:11 +00005470StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5471 SourceLocation StartLoc,
5472 SourceLocation EndLoc) {
5473 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5474 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5475}
5476
Alexey Bataev346265e2015-09-25 10:37:12 +00005477StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5478 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005479 SourceLocation StartLoc,
5480 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005481 OMPClause *DependFound = nullptr;
5482 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005483 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005484 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005485 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005486 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005487 for (auto *C : Clauses) {
5488 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5489 DependFound = C;
5490 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5491 if (DependSourceClause) {
5492 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5493 << getOpenMPDirectiveName(OMPD_ordered)
5494 << getOpenMPClauseName(OMPC_depend) << 2;
5495 ErrorFound = true;
5496 } else
5497 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005498 if (DependSinkClause) {
5499 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5500 << 0;
5501 ErrorFound = true;
5502 }
5503 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5504 if (DependSourceClause) {
5505 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5506 << 1;
5507 ErrorFound = true;
5508 }
5509 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005510 }
5511 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005512 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005513 else if (C->getClauseKind() == OMPC_simd)
5514 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005515 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005516 if (!ErrorFound && !SC &&
5517 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005518 // OpenMP [2.8.1,simd Construct, Restrictions]
5519 // An ordered construct with the simd clause is the only OpenMP construct
5520 // that can appear in the simd region.
5521 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005522 ErrorFound = true;
5523 } else if (DependFound && (TC || SC)) {
5524 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5525 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5526 ErrorFound = true;
5527 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5528 Diag(DependFound->getLocStart(),
5529 diag::err_omp_ordered_directive_without_param);
5530 ErrorFound = true;
5531 } else if (TC || Clauses.empty()) {
5532 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5533 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5534 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5535 << (TC != nullptr);
5536 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5537 ErrorFound = true;
5538 }
5539 }
5540 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005541 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005542
5543 if (AStmt) {
5544 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5545
5546 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005547 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005548
5549 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005550}
5551
Alexey Bataev1d160b12015-03-13 12:27:31 +00005552namespace {
5553/// \brief Helper class for checking expression in 'omp atomic [update]'
5554/// construct.
5555class OpenMPAtomicUpdateChecker {
5556 /// \brief Error results for atomic update expressions.
5557 enum ExprAnalysisErrorCode {
5558 /// \brief A statement is not an expression statement.
5559 NotAnExpression,
5560 /// \brief Expression is not builtin binary or unary operation.
5561 NotABinaryOrUnaryExpression,
5562 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5563 NotAnUnaryIncDecExpression,
5564 /// \brief An expression is not of scalar type.
5565 NotAScalarType,
5566 /// \brief A binary operation is not an assignment operation.
5567 NotAnAssignmentOp,
5568 /// \brief RHS part of the binary operation is not a binary expression.
5569 NotABinaryExpression,
5570 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5571 /// expression.
5572 NotABinaryOperator,
5573 /// \brief RHS binary operation does not have reference to the updated LHS
5574 /// part.
5575 NotAnUpdateExpression,
5576 /// \brief No errors is found.
5577 NoError
5578 };
5579 /// \brief Reference to Sema.
5580 Sema &SemaRef;
5581 /// \brief A location for note diagnostics (when error is found).
5582 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005583 /// \brief 'x' lvalue part of the source atomic expression.
5584 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005585 /// \brief 'expr' rvalue part of the source atomic expression.
5586 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005587 /// \brief Helper expression of the form
5588 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5589 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5590 Expr *UpdateExpr;
5591 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5592 /// important for non-associative operations.
5593 bool IsXLHSInRHSPart;
5594 BinaryOperatorKind Op;
5595 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005596 /// \brief true if the source expression is a postfix unary operation, false
5597 /// if it is a prefix unary operation.
5598 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005599
5600public:
5601 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005602 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005603 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005604 /// \brief Check specified statement that it is suitable for 'atomic update'
5605 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005606 /// expression. If DiagId and NoteId == 0, then only check is performed
5607 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005608 /// \param DiagId Diagnostic which should be emitted if error is found.
5609 /// \param NoteId Diagnostic note for the main error message.
5610 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005611 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005612 /// \brief Return the 'x' lvalue part of the source atomic expression.
5613 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005614 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5615 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005616 /// \brief Return the update expression used in calculation of the updated
5617 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5618 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5619 Expr *getUpdateExpr() const { return UpdateExpr; }
5620 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5621 /// false otherwise.
5622 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5623
Alexey Bataevb78ca832015-04-01 03:33:17 +00005624 /// \brief true if the source expression is a postfix unary operation, false
5625 /// if it is a prefix unary operation.
5626 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5627
Alexey Bataev1d160b12015-03-13 12:27:31 +00005628private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005629 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5630 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005631};
5632} // namespace
5633
5634bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5635 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5636 ExprAnalysisErrorCode ErrorFound = NoError;
5637 SourceLocation ErrorLoc, NoteLoc;
5638 SourceRange ErrorRange, NoteRange;
5639 // Allowed constructs are:
5640 // x = x binop expr;
5641 // x = expr binop x;
5642 if (AtomicBinOp->getOpcode() == BO_Assign) {
5643 X = AtomicBinOp->getLHS();
5644 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5645 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5646 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5647 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5648 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005649 Op = AtomicInnerBinOp->getOpcode();
5650 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005651 auto *LHS = AtomicInnerBinOp->getLHS();
5652 auto *RHS = AtomicInnerBinOp->getRHS();
5653 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5654 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5655 /*Canonical=*/true);
5656 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5657 /*Canonical=*/true);
5658 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5659 /*Canonical=*/true);
5660 if (XId == LHSId) {
5661 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005662 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005663 } else if (XId == RHSId) {
5664 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005665 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005666 } else {
5667 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5668 ErrorRange = AtomicInnerBinOp->getSourceRange();
5669 NoteLoc = X->getExprLoc();
5670 NoteRange = X->getSourceRange();
5671 ErrorFound = NotAnUpdateExpression;
5672 }
5673 } else {
5674 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5675 ErrorRange = AtomicInnerBinOp->getSourceRange();
5676 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5677 NoteRange = SourceRange(NoteLoc, NoteLoc);
5678 ErrorFound = NotABinaryOperator;
5679 }
5680 } else {
5681 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5682 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5683 ErrorFound = NotABinaryExpression;
5684 }
5685 } else {
5686 ErrorLoc = AtomicBinOp->getExprLoc();
5687 ErrorRange = AtomicBinOp->getSourceRange();
5688 NoteLoc = AtomicBinOp->getOperatorLoc();
5689 NoteRange = SourceRange(NoteLoc, NoteLoc);
5690 ErrorFound = NotAnAssignmentOp;
5691 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005692 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005693 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5694 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5695 return true;
5696 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005697 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005698 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005699}
5700
5701bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5702 unsigned NoteId) {
5703 ExprAnalysisErrorCode ErrorFound = NoError;
5704 SourceLocation ErrorLoc, NoteLoc;
5705 SourceRange ErrorRange, NoteRange;
5706 // Allowed constructs are:
5707 // x++;
5708 // x--;
5709 // ++x;
5710 // --x;
5711 // x binop= expr;
5712 // x = x binop expr;
5713 // x = expr binop x;
5714 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5715 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5716 if (AtomicBody->getType()->isScalarType() ||
5717 AtomicBody->isInstantiationDependent()) {
5718 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5719 AtomicBody->IgnoreParenImpCasts())) {
5720 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005721 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005722 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005723 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005724 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005725 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005726 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005727 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5728 AtomicBody->IgnoreParenImpCasts())) {
5729 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005730 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005731 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005732 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5733 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005734 // Check for Unary Operation
5735 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005736 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005737 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5738 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005739 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005740 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5741 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005742 } else {
5743 ErrorFound = NotAnUnaryIncDecExpression;
5744 ErrorLoc = AtomicUnaryOp->getExprLoc();
5745 ErrorRange = AtomicUnaryOp->getSourceRange();
5746 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5747 NoteRange = SourceRange(NoteLoc, NoteLoc);
5748 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005749 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005750 ErrorFound = NotABinaryOrUnaryExpression;
5751 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5752 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5753 }
5754 } else {
5755 ErrorFound = NotAScalarType;
5756 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5757 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5758 }
5759 } else {
5760 ErrorFound = NotAnExpression;
5761 NoteLoc = ErrorLoc = S->getLocStart();
5762 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5763 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005764 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005765 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5766 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5767 return true;
5768 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005769 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005770 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005771 // Build an update expression of form 'OpaqueValueExpr(x) binop
5772 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5773 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5774 auto *OVEX = new (SemaRef.getASTContext())
5775 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5776 auto *OVEExpr = new (SemaRef.getASTContext())
5777 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5778 auto Update =
5779 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5780 IsXLHSInRHSPart ? OVEExpr : OVEX);
5781 if (Update.isInvalid())
5782 return true;
5783 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5784 Sema::AA_Casting);
5785 if (Update.isInvalid())
5786 return true;
5787 UpdateExpr = Update.get();
5788 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005789 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005790}
5791
Alexey Bataev0162e452014-07-22 10:10:35 +00005792StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5793 Stmt *AStmt,
5794 SourceLocation StartLoc,
5795 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005796 if (!AStmt)
5797 return StmtError();
5798
David Majnemer9d168222016-08-05 17:44:54 +00005799 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005800 // 1.2.2 OpenMP Language Terminology
5801 // Structured block - An executable statement with a single entry at the
5802 // top and a single exit at the bottom.
5803 // The point of exit cannot be a branch out of the structured block.
5804 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005805 OpenMPClauseKind AtomicKind = OMPC_unknown;
5806 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005807 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005808 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005809 C->getClauseKind() == OMPC_update ||
5810 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005811 if (AtomicKind != OMPC_unknown) {
5812 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5813 << SourceRange(C->getLocStart(), C->getLocEnd());
5814 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5815 << getOpenMPClauseName(AtomicKind);
5816 } else {
5817 AtomicKind = C->getClauseKind();
5818 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005819 }
5820 }
5821 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005822
Alexey Bataev459dec02014-07-24 06:46:57 +00005823 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005824 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5825 Body = EWC->getSubExpr();
5826
Alexey Bataev62cec442014-11-18 10:14:22 +00005827 Expr *X = nullptr;
5828 Expr *V = nullptr;
5829 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005830 Expr *UE = nullptr;
5831 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005832 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005833 // OpenMP [2.12.6, atomic Construct]
5834 // In the next expressions:
5835 // * x and v (as applicable) are both l-value expressions with scalar type.
5836 // * During the execution of an atomic region, multiple syntactic
5837 // occurrences of x must designate the same storage location.
5838 // * Neither of v and expr (as applicable) may access the storage location
5839 // designated by x.
5840 // * Neither of x and expr (as applicable) may access the storage location
5841 // designated by v.
5842 // * expr is an expression with scalar type.
5843 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5844 // * binop, binop=, ++, and -- are not overloaded operators.
5845 // * The expression x binop expr must be numerically equivalent to x binop
5846 // (expr). This requirement is satisfied if the operators in expr have
5847 // precedence greater than binop, or by using parentheses around expr or
5848 // subexpressions of expr.
5849 // * The expression expr binop x must be numerically equivalent to (expr)
5850 // binop x. This requirement is satisfied if the operators in expr have
5851 // precedence equal to or greater than binop, or by using parentheses around
5852 // expr or subexpressions of expr.
5853 // * For forms that allow multiple occurrences of x, the number of times
5854 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005855 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005856 enum {
5857 NotAnExpression,
5858 NotAnAssignmentOp,
5859 NotAScalarType,
5860 NotAnLValue,
5861 NoError
5862 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005863 SourceLocation ErrorLoc, NoteLoc;
5864 SourceRange ErrorRange, NoteRange;
5865 // If clause is read:
5866 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005867 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5868 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005869 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5870 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5871 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5872 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5873 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5874 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5875 if (!X->isLValue() || !V->isLValue()) {
5876 auto NotLValueExpr = X->isLValue() ? V : X;
5877 ErrorFound = NotAnLValue;
5878 ErrorLoc = AtomicBinOp->getExprLoc();
5879 ErrorRange = AtomicBinOp->getSourceRange();
5880 NoteLoc = NotLValueExpr->getExprLoc();
5881 NoteRange = NotLValueExpr->getSourceRange();
5882 }
5883 } else if (!X->isInstantiationDependent() ||
5884 !V->isInstantiationDependent()) {
5885 auto NotScalarExpr =
5886 (X->isInstantiationDependent() || X->getType()->isScalarType())
5887 ? V
5888 : X;
5889 ErrorFound = NotAScalarType;
5890 ErrorLoc = AtomicBinOp->getExprLoc();
5891 ErrorRange = AtomicBinOp->getSourceRange();
5892 NoteLoc = NotScalarExpr->getExprLoc();
5893 NoteRange = NotScalarExpr->getSourceRange();
5894 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005895 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005896 ErrorFound = NotAnAssignmentOp;
5897 ErrorLoc = AtomicBody->getExprLoc();
5898 ErrorRange = AtomicBody->getSourceRange();
5899 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5900 : AtomicBody->getExprLoc();
5901 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5902 : AtomicBody->getSourceRange();
5903 }
5904 } else {
5905 ErrorFound = NotAnExpression;
5906 NoteLoc = ErrorLoc = Body->getLocStart();
5907 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005908 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005909 if (ErrorFound != NoError) {
5910 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5911 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005912 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5913 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005914 return StmtError();
5915 } else if (CurContext->isDependentContext())
5916 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005917 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005918 enum {
5919 NotAnExpression,
5920 NotAnAssignmentOp,
5921 NotAScalarType,
5922 NotAnLValue,
5923 NoError
5924 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005925 SourceLocation ErrorLoc, NoteLoc;
5926 SourceRange ErrorRange, NoteRange;
5927 // If clause is write:
5928 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005929 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5930 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005931 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5932 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005933 X = AtomicBinOp->getLHS();
5934 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005935 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5936 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5937 if (!X->isLValue()) {
5938 ErrorFound = NotAnLValue;
5939 ErrorLoc = AtomicBinOp->getExprLoc();
5940 ErrorRange = AtomicBinOp->getSourceRange();
5941 NoteLoc = X->getExprLoc();
5942 NoteRange = X->getSourceRange();
5943 }
5944 } else if (!X->isInstantiationDependent() ||
5945 !E->isInstantiationDependent()) {
5946 auto NotScalarExpr =
5947 (X->isInstantiationDependent() || X->getType()->isScalarType())
5948 ? E
5949 : X;
5950 ErrorFound = NotAScalarType;
5951 ErrorLoc = AtomicBinOp->getExprLoc();
5952 ErrorRange = AtomicBinOp->getSourceRange();
5953 NoteLoc = NotScalarExpr->getExprLoc();
5954 NoteRange = NotScalarExpr->getSourceRange();
5955 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005956 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005957 ErrorFound = NotAnAssignmentOp;
5958 ErrorLoc = AtomicBody->getExprLoc();
5959 ErrorRange = AtomicBody->getSourceRange();
5960 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5961 : AtomicBody->getExprLoc();
5962 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5963 : AtomicBody->getSourceRange();
5964 }
5965 } else {
5966 ErrorFound = NotAnExpression;
5967 NoteLoc = ErrorLoc = Body->getLocStart();
5968 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005969 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005970 if (ErrorFound != NoError) {
5971 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5972 << ErrorRange;
5973 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5974 << NoteRange;
5975 return StmtError();
5976 } else if (CurContext->isDependentContext())
5977 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005978 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005979 // If clause is update:
5980 // x++;
5981 // x--;
5982 // ++x;
5983 // --x;
5984 // x binop= expr;
5985 // x = x binop expr;
5986 // x = expr binop x;
5987 OpenMPAtomicUpdateChecker Checker(*this);
5988 if (Checker.checkStatement(
5989 Body, (AtomicKind == OMPC_update)
5990 ? diag::err_omp_atomic_update_not_expression_statement
5991 : diag::err_omp_atomic_not_expression_statement,
5992 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005993 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005994 if (!CurContext->isDependentContext()) {
5995 E = Checker.getExpr();
5996 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005997 UE = Checker.getUpdateExpr();
5998 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005999 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006000 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006001 enum {
6002 NotAnAssignmentOp,
6003 NotACompoundStatement,
6004 NotTwoSubstatements,
6005 NotASpecificExpression,
6006 NoError
6007 } ErrorFound = NoError;
6008 SourceLocation ErrorLoc, NoteLoc;
6009 SourceRange ErrorRange, NoteRange;
6010 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6011 // If clause is a capture:
6012 // v = x++;
6013 // v = x--;
6014 // v = ++x;
6015 // v = --x;
6016 // v = x binop= expr;
6017 // v = x = x binop expr;
6018 // v = x = expr binop x;
6019 auto *AtomicBinOp =
6020 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6021 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6022 V = AtomicBinOp->getLHS();
6023 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6024 OpenMPAtomicUpdateChecker Checker(*this);
6025 if (Checker.checkStatement(
6026 Body, diag::err_omp_atomic_capture_not_expression_statement,
6027 diag::note_omp_atomic_update))
6028 return StmtError();
6029 E = Checker.getExpr();
6030 X = Checker.getX();
6031 UE = Checker.getUpdateExpr();
6032 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6033 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006034 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006035 ErrorLoc = AtomicBody->getExprLoc();
6036 ErrorRange = AtomicBody->getSourceRange();
6037 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6038 : AtomicBody->getExprLoc();
6039 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6040 : AtomicBody->getSourceRange();
6041 ErrorFound = NotAnAssignmentOp;
6042 }
6043 if (ErrorFound != NoError) {
6044 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6045 << ErrorRange;
6046 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6047 return StmtError();
6048 } else if (CurContext->isDependentContext()) {
6049 UE = V = E = X = nullptr;
6050 }
6051 } else {
6052 // If clause is a capture:
6053 // { v = x; x = expr; }
6054 // { v = x; x++; }
6055 // { v = x; x--; }
6056 // { v = x; ++x; }
6057 // { v = x; --x; }
6058 // { v = x; x binop= expr; }
6059 // { v = x; x = x binop expr; }
6060 // { v = x; x = expr binop x; }
6061 // { x++; v = x; }
6062 // { x--; v = x; }
6063 // { ++x; v = x; }
6064 // { --x; v = x; }
6065 // { x binop= expr; v = x; }
6066 // { x = x binop expr; v = x; }
6067 // { x = expr binop x; v = x; }
6068 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6069 // Check that this is { expr1; expr2; }
6070 if (CS->size() == 2) {
6071 auto *First = CS->body_front();
6072 auto *Second = CS->body_back();
6073 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6074 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6075 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6076 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6077 // Need to find what subexpression is 'v' and what is 'x'.
6078 OpenMPAtomicUpdateChecker Checker(*this);
6079 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6080 BinaryOperator *BinOp = nullptr;
6081 if (IsUpdateExprFound) {
6082 BinOp = dyn_cast<BinaryOperator>(First);
6083 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6084 }
6085 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6086 // { v = x; x++; }
6087 // { v = x; x--; }
6088 // { v = x; ++x; }
6089 // { v = x; --x; }
6090 // { v = x; x binop= expr; }
6091 // { v = x; x = x binop expr; }
6092 // { v = x; x = expr binop x; }
6093 // Check that the first expression has form v = x.
6094 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6095 llvm::FoldingSetNodeID XId, PossibleXId;
6096 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6097 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6098 IsUpdateExprFound = XId == PossibleXId;
6099 if (IsUpdateExprFound) {
6100 V = BinOp->getLHS();
6101 X = Checker.getX();
6102 E = Checker.getExpr();
6103 UE = Checker.getUpdateExpr();
6104 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006105 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006106 }
6107 }
6108 if (!IsUpdateExprFound) {
6109 IsUpdateExprFound = !Checker.checkStatement(First);
6110 BinOp = nullptr;
6111 if (IsUpdateExprFound) {
6112 BinOp = dyn_cast<BinaryOperator>(Second);
6113 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6114 }
6115 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6116 // { x++; v = x; }
6117 // { x--; v = x; }
6118 // { ++x; v = x; }
6119 // { --x; v = x; }
6120 // { x binop= expr; v = x; }
6121 // { x = x binop expr; v = x; }
6122 // { x = expr binop x; v = x; }
6123 // Check that the second expression has form v = x.
6124 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6125 llvm::FoldingSetNodeID XId, PossibleXId;
6126 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6127 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6128 IsUpdateExprFound = XId == PossibleXId;
6129 if (IsUpdateExprFound) {
6130 V = BinOp->getLHS();
6131 X = Checker.getX();
6132 E = Checker.getExpr();
6133 UE = Checker.getUpdateExpr();
6134 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006135 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006136 }
6137 }
6138 }
6139 if (!IsUpdateExprFound) {
6140 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006141 auto *FirstExpr = dyn_cast<Expr>(First);
6142 auto *SecondExpr = dyn_cast<Expr>(Second);
6143 if (!FirstExpr || !SecondExpr ||
6144 !(FirstExpr->isInstantiationDependent() ||
6145 SecondExpr->isInstantiationDependent())) {
6146 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6147 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006148 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006149 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6150 : First->getLocStart();
6151 NoteRange = ErrorRange = FirstBinOp
6152 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006153 : SourceRange(ErrorLoc, ErrorLoc);
6154 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006155 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6156 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6157 ErrorFound = NotAnAssignmentOp;
6158 NoteLoc = ErrorLoc = SecondBinOp
6159 ? SecondBinOp->getOperatorLoc()
6160 : Second->getLocStart();
6161 NoteRange = ErrorRange =
6162 SecondBinOp ? SecondBinOp->getSourceRange()
6163 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006164 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006165 auto *PossibleXRHSInFirst =
6166 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6167 auto *PossibleXLHSInSecond =
6168 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6169 llvm::FoldingSetNodeID X1Id, X2Id;
6170 PossibleXRHSInFirst->Profile(X1Id, Context,
6171 /*Canonical=*/true);
6172 PossibleXLHSInSecond->Profile(X2Id, Context,
6173 /*Canonical=*/true);
6174 IsUpdateExprFound = X1Id == X2Id;
6175 if (IsUpdateExprFound) {
6176 V = FirstBinOp->getLHS();
6177 X = SecondBinOp->getLHS();
6178 E = SecondBinOp->getRHS();
6179 UE = nullptr;
6180 IsXLHSInRHSPart = false;
6181 IsPostfixUpdate = true;
6182 } else {
6183 ErrorFound = NotASpecificExpression;
6184 ErrorLoc = FirstBinOp->getExprLoc();
6185 ErrorRange = FirstBinOp->getSourceRange();
6186 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6187 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6188 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006189 }
6190 }
6191 }
6192 }
6193 } else {
6194 NoteLoc = ErrorLoc = Body->getLocStart();
6195 NoteRange = ErrorRange =
6196 SourceRange(Body->getLocStart(), Body->getLocStart());
6197 ErrorFound = NotTwoSubstatements;
6198 }
6199 } else {
6200 NoteLoc = ErrorLoc = Body->getLocStart();
6201 NoteRange = ErrorRange =
6202 SourceRange(Body->getLocStart(), Body->getLocStart());
6203 ErrorFound = NotACompoundStatement;
6204 }
6205 if (ErrorFound != NoError) {
6206 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6207 << ErrorRange;
6208 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6209 return StmtError();
6210 } else if (CurContext->isDependentContext()) {
6211 UE = V = E = X = nullptr;
6212 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006213 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006214 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006215
6216 getCurFunction()->setHasBranchProtectedScope();
6217
Alexey Bataev62cec442014-11-18 10:14:22 +00006218 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006219 X, V, E, UE, IsXLHSInRHSPart,
6220 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006221}
6222
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006223StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6224 Stmt *AStmt,
6225 SourceLocation StartLoc,
6226 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006227 if (!AStmt)
6228 return StmtError();
6229
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006230 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6231 // 1.2.2 OpenMP Language Terminology
6232 // Structured block - An executable statement with a single entry at the
6233 // top and a single exit at the bottom.
6234 // The point of exit cannot be a branch out of the structured block.
6235 // longjmp() and throw() must not violate the entry/exit criteria.
6236 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006237
Alexey Bataev13314bf2014-10-09 04:18:56 +00006238 // OpenMP [2.16, Nesting of Regions]
6239 // If specified, a teams construct must be contained within a target
6240 // construct. That target construct must contain no statements or directives
6241 // outside of the teams construct.
6242 if (DSAStack->hasInnerTeamsRegion()) {
6243 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6244 bool OMPTeamsFound = true;
6245 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6246 auto I = CS->body_begin();
6247 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006248 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006249 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6250 OMPTeamsFound = false;
6251 break;
6252 }
6253 ++I;
6254 }
6255 assert(I != CS->body_end() && "Not found statement");
6256 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006257 } else {
6258 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6259 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006260 }
6261 if (!OMPTeamsFound) {
6262 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6263 Diag(DSAStack->getInnerTeamsRegionLoc(),
6264 diag::note_omp_nested_teams_construct_here);
6265 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6266 << isa<OMPExecutableDirective>(S);
6267 return StmtError();
6268 }
6269 }
6270
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006271 getCurFunction()->setHasBranchProtectedScope();
6272
6273 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6274}
6275
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006276StmtResult
6277Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6278 Stmt *AStmt, SourceLocation StartLoc,
6279 SourceLocation EndLoc) {
6280 if (!AStmt)
6281 return StmtError();
6282
6283 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6284 // 1.2.2 OpenMP Language Terminology
6285 // Structured block - An executable statement with a single entry at the
6286 // top and a single exit at the bottom.
6287 // The point of exit cannot be a branch out of the structured block.
6288 // longjmp() and throw() must not violate the entry/exit criteria.
6289 CS->getCapturedDecl()->setNothrow();
6290
6291 getCurFunction()->setHasBranchProtectedScope();
6292
6293 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6294 AStmt);
6295}
6296
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006297StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6298 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6299 SourceLocation EndLoc,
6300 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6301 if (!AStmt)
6302 return StmtError();
6303
6304 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6305 // 1.2.2 OpenMP Language Terminology
6306 // Structured block - An executable statement with a single entry at the
6307 // top and a single exit at the bottom.
6308 // The point of exit cannot be a branch out of the structured block.
6309 // longjmp() and throw() must not violate the entry/exit criteria.
6310 CS->getCapturedDecl()->setNothrow();
6311
6312 OMPLoopDirective::HelperExprs B;
6313 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6314 // define the nested loops number.
6315 unsigned NestedLoopCount =
6316 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6317 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6318 VarsWithImplicitDSA, B);
6319 if (NestedLoopCount == 0)
6320 return StmtError();
6321
6322 assert((CurContext->isDependentContext() || B.builtAll()) &&
6323 "omp target parallel for loop exprs were not built");
6324
6325 if (!CurContext->isDependentContext()) {
6326 // Finalize the clauses that need pre-built expressions for CodeGen.
6327 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006328 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006329 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006330 B.NumIterations, *this, CurScope,
6331 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006332 return StmtError();
6333 }
6334 }
6335
6336 getCurFunction()->setHasBranchProtectedScope();
6337 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6338 NestedLoopCount, Clauses, AStmt,
6339 B, DSAStack->isCancelRegion());
6340}
6341
Alexey Bataev95b64a92017-05-30 16:00:04 +00006342/// Check for existence of a map clause in the list of clauses.
6343static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6344 const OpenMPClauseKind K) {
6345 return llvm::any_of(
6346 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6347}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006348
Alexey Bataev95b64a92017-05-30 16:00:04 +00006349template <typename... Params>
6350static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6351 const Params... ClauseTypes) {
6352 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006353}
6354
Michael Wong65f367f2015-07-21 13:44:28 +00006355StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6356 Stmt *AStmt,
6357 SourceLocation StartLoc,
6358 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006359 if (!AStmt)
6360 return StmtError();
6361
6362 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6363
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006364 // OpenMP [2.10.1, Restrictions, p. 97]
6365 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006366 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6367 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6368 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006369 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006370 return StmtError();
6371 }
6372
Michael Wong65f367f2015-07-21 13:44:28 +00006373 getCurFunction()->setHasBranchProtectedScope();
6374
6375 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6376 AStmt);
6377}
6378
Samuel Antaodf67fc42016-01-19 19:15:56 +00006379StmtResult
6380Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6381 SourceLocation StartLoc,
6382 SourceLocation EndLoc) {
6383 // OpenMP [2.10.2, Restrictions, p. 99]
6384 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006385 if (!hasClauses(Clauses, OMPC_map)) {
6386 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6387 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006388 return StmtError();
6389 }
6390
6391 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6392 Clauses);
6393}
6394
Samuel Antao72590762016-01-19 20:04:50 +00006395StmtResult
6396Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6397 SourceLocation StartLoc,
6398 SourceLocation EndLoc) {
6399 // OpenMP [2.10.3, Restrictions, p. 102]
6400 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006401 if (!hasClauses(Clauses, OMPC_map)) {
6402 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6403 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006404 return StmtError();
6405 }
6406
6407 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6408}
6409
Samuel Antao686c70c2016-05-26 17:30:50 +00006410StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6411 SourceLocation StartLoc,
6412 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006413 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006414 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6415 return StmtError();
6416 }
6417 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6418}
6419
Alexey Bataev13314bf2014-10-09 04:18:56 +00006420StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6421 Stmt *AStmt, SourceLocation StartLoc,
6422 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006423 if (!AStmt)
6424 return StmtError();
6425
Alexey Bataev13314bf2014-10-09 04:18:56 +00006426 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6427 // 1.2.2 OpenMP Language Terminology
6428 // Structured block - An executable statement with a single entry at the
6429 // top and a single exit at the bottom.
6430 // The point of exit cannot be a branch out of the structured block.
6431 // longjmp() and throw() must not violate the entry/exit criteria.
6432 CS->getCapturedDecl()->setNothrow();
6433
6434 getCurFunction()->setHasBranchProtectedScope();
6435
6436 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6437}
6438
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006439StmtResult
6440Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6441 SourceLocation EndLoc,
6442 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006443 if (DSAStack->isParentNowaitRegion()) {
6444 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6445 return StmtError();
6446 }
6447 if (DSAStack->isParentOrderedRegion()) {
6448 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6449 return StmtError();
6450 }
6451 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6452 CancelRegion);
6453}
6454
Alexey Bataev87933c72015-09-18 08:07:34 +00006455StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6456 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006457 SourceLocation EndLoc,
6458 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006459 if (DSAStack->isParentNowaitRegion()) {
6460 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6461 return StmtError();
6462 }
6463 if (DSAStack->isParentOrderedRegion()) {
6464 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6465 return StmtError();
6466 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006467 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006468 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6469 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006470}
6471
Alexey Bataev382967a2015-12-08 12:06:20 +00006472static bool checkGrainsizeNumTasksClauses(Sema &S,
6473 ArrayRef<OMPClause *> Clauses) {
6474 OMPClause *PrevClause = nullptr;
6475 bool ErrorFound = false;
6476 for (auto *C : Clauses) {
6477 if (C->getClauseKind() == OMPC_grainsize ||
6478 C->getClauseKind() == OMPC_num_tasks) {
6479 if (!PrevClause)
6480 PrevClause = C;
6481 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6482 S.Diag(C->getLocStart(),
6483 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6484 << getOpenMPClauseName(C->getClauseKind())
6485 << getOpenMPClauseName(PrevClause->getClauseKind());
6486 S.Diag(PrevClause->getLocStart(),
6487 diag::note_omp_previous_grainsize_num_tasks)
6488 << getOpenMPClauseName(PrevClause->getClauseKind());
6489 ErrorFound = true;
6490 }
6491 }
6492 }
6493 return ErrorFound;
6494}
6495
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006496static bool checkReductionClauseWithNogroup(Sema &S,
6497 ArrayRef<OMPClause *> Clauses) {
6498 OMPClause *ReductionClause = nullptr;
6499 OMPClause *NogroupClause = nullptr;
6500 for (auto *C : Clauses) {
6501 if (C->getClauseKind() == OMPC_reduction) {
6502 ReductionClause = C;
6503 if (NogroupClause)
6504 break;
6505 continue;
6506 }
6507 if (C->getClauseKind() == OMPC_nogroup) {
6508 NogroupClause = C;
6509 if (ReductionClause)
6510 break;
6511 continue;
6512 }
6513 }
6514 if (ReductionClause && NogroupClause) {
6515 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6516 << SourceRange(NogroupClause->getLocStart(),
6517 NogroupClause->getLocEnd());
6518 return true;
6519 }
6520 return false;
6521}
6522
Alexey Bataev49f6e782015-12-01 04:18:41 +00006523StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6524 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6525 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006526 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006527 if (!AStmt)
6528 return StmtError();
6529
6530 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6531 OMPLoopDirective::HelperExprs B;
6532 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6533 // define the nested loops number.
6534 unsigned NestedLoopCount =
6535 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006536 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006537 VarsWithImplicitDSA, B);
6538 if (NestedLoopCount == 0)
6539 return StmtError();
6540
6541 assert((CurContext->isDependentContext() || B.builtAll()) &&
6542 "omp for loop exprs were not built");
6543
Alexey Bataev382967a2015-12-08 12:06:20 +00006544 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6545 // The grainsize clause and num_tasks clause are mutually exclusive and may
6546 // not appear on the same taskloop directive.
6547 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6548 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006549 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6550 // If a reduction clause is present on the taskloop directive, the nogroup
6551 // clause must not be specified.
6552 if (checkReductionClauseWithNogroup(*this, Clauses))
6553 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006554
Alexey Bataev49f6e782015-12-01 04:18:41 +00006555 getCurFunction()->setHasBranchProtectedScope();
6556 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6557 NestedLoopCount, Clauses, AStmt, B);
6558}
6559
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006560StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6561 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6562 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006563 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006564 if (!AStmt)
6565 return StmtError();
6566
6567 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6568 OMPLoopDirective::HelperExprs B;
6569 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6570 // define the nested loops number.
6571 unsigned NestedLoopCount =
6572 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6573 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6574 VarsWithImplicitDSA, B);
6575 if (NestedLoopCount == 0)
6576 return StmtError();
6577
6578 assert((CurContext->isDependentContext() || B.builtAll()) &&
6579 "omp for loop exprs were not built");
6580
Alexey Bataev5a3af132016-03-29 08:58:54 +00006581 if (!CurContext->isDependentContext()) {
6582 // Finalize the clauses that need pre-built expressions for CodeGen.
6583 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006584 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006585 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006586 B.NumIterations, *this, CurScope,
6587 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006588 return StmtError();
6589 }
6590 }
6591
Alexey Bataev382967a2015-12-08 12:06:20 +00006592 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6593 // The grainsize clause and num_tasks clause are mutually exclusive and may
6594 // not appear on the same taskloop directive.
6595 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6596 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006597 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6598 // If a reduction clause is present on the taskloop directive, the nogroup
6599 // clause must not be specified.
6600 if (checkReductionClauseWithNogroup(*this, Clauses))
6601 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006602
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006603 getCurFunction()->setHasBranchProtectedScope();
6604 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6605 NestedLoopCount, Clauses, AStmt, B);
6606}
6607
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006608StmtResult Sema::ActOnOpenMPDistributeDirective(
6609 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6610 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006611 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006612 if (!AStmt)
6613 return StmtError();
6614
6615 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6616 OMPLoopDirective::HelperExprs B;
6617 // In presence of clause 'collapse' with number of loops, it will
6618 // define the nested loops number.
6619 unsigned NestedLoopCount =
6620 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6621 nullptr /*ordered not a clause on distribute*/, AStmt,
6622 *this, *DSAStack, VarsWithImplicitDSA, B);
6623 if (NestedLoopCount == 0)
6624 return StmtError();
6625
6626 assert((CurContext->isDependentContext() || B.builtAll()) &&
6627 "omp for loop exprs were not built");
6628
6629 getCurFunction()->setHasBranchProtectedScope();
6630 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6631 NestedLoopCount, Clauses, AStmt, B);
6632}
6633
Carlo Bertolli9925f152016-06-27 14:55:37 +00006634StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6635 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6636 SourceLocation EndLoc,
6637 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6638 if (!AStmt)
6639 return StmtError();
6640
6641 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6642 // 1.2.2 OpenMP Language Terminology
6643 // Structured block - An executable statement with a single entry at the
6644 // top and a single exit at the bottom.
6645 // The point of exit cannot be a branch out of the structured block.
6646 // longjmp() and throw() must not violate the entry/exit criteria.
6647 CS->getCapturedDecl()->setNothrow();
6648
6649 OMPLoopDirective::HelperExprs B;
6650 // In presence of clause 'collapse' with number of loops, it will
6651 // define the nested loops number.
6652 unsigned NestedLoopCount = CheckOpenMPLoop(
6653 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6654 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6655 VarsWithImplicitDSA, B);
6656 if (NestedLoopCount == 0)
6657 return StmtError();
6658
6659 assert((CurContext->isDependentContext() || B.builtAll()) &&
6660 "omp for loop exprs were not built");
6661
6662 getCurFunction()->setHasBranchProtectedScope();
6663 return OMPDistributeParallelForDirective::Create(
6664 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6665}
6666
Kelvin Li4a39add2016-07-05 05:00:15 +00006667StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6668 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6669 SourceLocation EndLoc,
6670 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6671 if (!AStmt)
6672 return StmtError();
6673
6674 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6675 // 1.2.2 OpenMP Language Terminology
6676 // Structured block - An executable statement with a single entry at the
6677 // top and a single exit at the bottom.
6678 // The point of exit cannot be a branch out of the structured block.
6679 // longjmp() and throw() must not violate the entry/exit criteria.
6680 CS->getCapturedDecl()->setNothrow();
6681
6682 OMPLoopDirective::HelperExprs B;
6683 // In presence of clause 'collapse' with number of loops, it will
6684 // define the nested loops number.
6685 unsigned NestedLoopCount = CheckOpenMPLoop(
6686 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6687 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6688 VarsWithImplicitDSA, B);
6689 if (NestedLoopCount == 0)
6690 return StmtError();
6691
6692 assert((CurContext->isDependentContext() || B.builtAll()) &&
6693 "omp for loop exprs were not built");
6694
Kelvin Lic5609492016-07-15 04:39:07 +00006695 if (checkSimdlenSafelenSpecified(*this, Clauses))
6696 return StmtError();
6697
Kelvin Li4a39add2016-07-05 05:00:15 +00006698 getCurFunction()->setHasBranchProtectedScope();
6699 return OMPDistributeParallelForSimdDirective::Create(
6700 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6701}
6702
Kelvin Li787f3fc2016-07-06 04:45:38 +00006703StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6704 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6705 SourceLocation EndLoc,
6706 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6707 if (!AStmt)
6708 return StmtError();
6709
6710 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6711 // 1.2.2 OpenMP Language Terminology
6712 // Structured block - An executable statement with a single entry at the
6713 // top and a single exit at the bottom.
6714 // The point of exit cannot be a branch out of the structured block.
6715 // longjmp() and throw() must not violate the entry/exit criteria.
6716 CS->getCapturedDecl()->setNothrow();
6717
6718 OMPLoopDirective::HelperExprs B;
6719 // In presence of clause 'collapse' with number of loops, it will
6720 // define the nested loops number.
6721 unsigned NestedLoopCount =
6722 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6723 nullptr /*ordered not a clause on distribute*/, AStmt,
6724 *this, *DSAStack, VarsWithImplicitDSA, B);
6725 if (NestedLoopCount == 0)
6726 return StmtError();
6727
6728 assert((CurContext->isDependentContext() || B.builtAll()) &&
6729 "omp for loop exprs were not built");
6730
Kelvin Lic5609492016-07-15 04:39:07 +00006731 if (checkSimdlenSafelenSpecified(*this, Clauses))
6732 return StmtError();
6733
Kelvin Li787f3fc2016-07-06 04:45:38 +00006734 getCurFunction()->setHasBranchProtectedScope();
6735 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6736 NestedLoopCount, Clauses, AStmt, B);
6737}
6738
Kelvin Lia579b912016-07-14 02:54:56 +00006739StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6740 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6741 SourceLocation EndLoc,
6742 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6743 if (!AStmt)
6744 return StmtError();
6745
6746 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6747 // 1.2.2 OpenMP Language Terminology
6748 // Structured block - An executable statement with a single entry at the
6749 // top and a single exit at the bottom.
6750 // The point of exit cannot be a branch out of the structured block.
6751 // longjmp() and throw() must not violate the entry/exit criteria.
6752 CS->getCapturedDecl()->setNothrow();
6753
6754 OMPLoopDirective::HelperExprs B;
6755 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6756 // define the nested loops number.
6757 unsigned NestedLoopCount = CheckOpenMPLoop(
6758 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6759 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6760 VarsWithImplicitDSA, B);
6761 if (NestedLoopCount == 0)
6762 return StmtError();
6763
6764 assert((CurContext->isDependentContext() || B.builtAll()) &&
6765 "omp target parallel for simd loop exprs were not built");
6766
6767 if (!CurContext->isDependentContext()) {
6768 // Finalize the clauses that need pre-built expressions for CodeGen.
6769 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006770 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006771 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6772 B.NumIterations, *this, CurScope,
6773 DSAStack))
6774 return StmtError();
6775 }
6776 }
Kelvin Lic5609492016-07-15 04:39:07 +00006777 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006778 return StmtError();
6779
6780 getCurFunction()->setHasBranchProtectedScope();
6781 return OMPTargetParallelForSimdDirective::Create(
6782 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6783}
6784
Kelvin Li986330c2016-07-20 22:57:10 +00006785StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6786 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6787 SourceLocation EndLoc,
6788 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6789 if (!AStmt)
6790 return StmtError();
6791
6792 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6793 // 1.2.2 OpenMP Language Terminology
6794 // Structured block - An executable statement with a single entry at the
6795 // top and a single exit at the bottom.
6796 // The point of exit cannot be a branch out of the structured block.
6797 // longjmp() and throw() must not violate the entry/exit criteria.
6798 CS->getCapturedDecl()->setNothrow();
6799
6800 OMPLoopDirective::HelperExprs B;
6801 // In presence of clause 'collapse' with number of loops, it will define the
6802 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006803 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006804 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6805 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6806 VarsWithImplicitDSA, B);
6807 if (NestedLoopCount == 0)
6808 return StmtError();
6809
6810 assert((CurContext->isDependentContext() || B.builtAll()) &&
6811 "omp target simd loop exprs were not built");
6812
6813 if (!CurContext->isDependentContext()) {
6814 // Finalize the clauses that need pre-built expressions for CodeGen.
6815 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006816 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006817 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6818 B.NumIterations, *this, CurScope,
6819 DSAStack))
6820 return StmtError();
6821 }
6822 }
6823
6824 if (checkSimdlenSafelenSpecified(*this, Clauses))
6825 return StmtError();
6826
6827 getCurFunction()->setHasBranchProtectedScope();
6828 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6829 NestedLoopCount, Clauses, AStmt, B);
6830}
6831
Kelvin Li02532872016-08-05 14:37:37 +00006832StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6833 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6834 SourceLocation EndLoc,
6835 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6836 if (!AStmt)
6837 return StmtError();
6838
6839 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6840 // 1.2.2 OpenMP Language Terminology
6841 // Structured block - An executable statement with a single entry at the
6842 // top and a single exit at the bottom.
6843 // The point of exit cannot be a branch out of the structured block.
6844 // longjmp() and throw() must not violate the entry/exit criteria.
6845 CS->getCapturedDecl()->setNothrow();
6846
6847 OMPLoopDirective::HelperExprs B;
6848 // In presence of clause 'collapse' with number of loops, it will
6849 // define the nested loops number.
6850 unsigned NestedLoopCount =
6851 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6852 nullptr /*ordered not a clause on distribute*/, AStmt,
6853 *this, *DSAStack, VarsWithImplicitDSA, B);
6854 if (NestedLoopCount == 0)
6855 return StmtError();
6856
6857 assert((CurContext->isDependentContext() || B.builtAll()) &&
6858 "omp teams distribute loop exprs were not built");
6859
6860 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006861 return OMPTeamsDistributeDirective::Create(
6862 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006863}
6864
Kelvin Li4e325f72016-10-25 12:50:55 +00006865StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6866 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6867 SourceLocation EndLoc,
6868 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6869 if (!AStmt)
6870 return StmtError();
6871
6872 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6873 // 1.2.2 OpenMP Language Terminology
6874 // Structured block - An executable statement with a single entry at the
6875 // top and a single exit at the bottom.
6876 // The point of exit cannot be a branch out of the structured block.
6877 // longjmp() and throw() must not violate the entry/exit criteria.
6878 CS->getCapturedDecl()->setNothrow();
6879
6880 OMPLoopDirective::HelperExprs B;
6881 // In presence of clause 'collapse' with number of loops, it will
6882 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006883 unsigned NestedLoopCount = CheckOpenMPLoop(
6884 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6885 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6886 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006887
6888 if (NestedLoopCount == 0)
6889 return StmtError();
6890
6891 assert((CurContext->isDependentContext() || B.builtAll()) &&
6892 "omp teams distribute simd loop exprs were not built");
6893
6894 if (!CurContext->isDependentContext()) {
6895 // Finalize the clauses that need pre-built expressions for CodeGen.
6896 for (auto C : Clauses) {
6897 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6898 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6899 B.NumIterations, *this, CurScope,
6900 DSAStack))
6901 return StmtError();
6902 }
6903 }
6904
6905 if (checkSimdlenSafelenSpecified(*this, Clauses))
6906 return StmtError();
6907
6908 getCurFunction()->setHasBranchProtectedScope();
6909 return OMPTeamsDistributeSimdDirective::Create(
6910 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6911}
6912
Kelvin Li579e41c2016-11-30 23:51:03 +00006913StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6914 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6915 SourceLocation EndLoc,
6916 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6917 if (!AStmt)
6918 return StmtError();
6919
6920 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6921 // 1.2.2 OpenMP Language Terminology
6922 // Structured block - An executable statement with a single entry at the
6923 // top and a single exit at the bottom.
6924 // The point of exit cannot be a branch out of the structured block.
6925 // longjmp() and throw() must not violate the entry/exit criteria.
6926 CS->getCapturedDecl()->setNothrow();
6927
6928 OMPLoopDirective::HelperExprs B;
6929 // In presence of clause 'collapse' with number of loops, it will
6930 // define the nested loops number.
6931 auto NestedLoopCount = CheckOpenMPLoop(
6932 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6933 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6934 VarsWithImplicitDSA, B);
6935
6936 if (NestedLoopCount == 0)
6937 return StmtError();
6938
6939 assert((CurContext->isDependentContext() || B.builtAll()) &&
6940 "omp for loop exprs were not built");
6941
6942 if (!CurContext->isDependentContext()) {
6943 // Finalize the clauses that need pre-built expressions for CodeGen.
6944 for (auto C : Clauses) {
6945 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6946 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6947 B.NumIterations, *this, CurScope,
6948 DSAStack))
6949 return StmtError();
6950 }
6951 }
6952
6953 if (checkSimdlenSafelenSpecified(*this, Clauses))
6954 return StmtError();
6955
6956 getCurFunction()->setHasBranchProtectedScope();
6957 return OMPTeamsDistributeParallelForSimdDirective::Create(
6958 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6959}
6960
Kelvin Li7ade93f2016-12-09 03:24:30 +00006961StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6962 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6963 SourceLocation EndLoc,
6964 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6965 if (!AStmt)
6966 return StmtError();
6967
6968 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6969 // 1.2.2 OpenMP Language Terminology
6970 // Structured block - An executable statement with a single entry at the
6971 // top and a single exit at the bottom.
6972 // The point of exit cannot be a branch out of the structured block.
6973 // longjmp() and throw() must not violate the entry/exit criteria.
6974 CS->getCapturedDecl()->setNothrow();
6975
6976 OMPLoopDirective::HelperExprs B;
6977 // In presence of clause 'collapse' with number of loops, it will
6978 // define the nested loops number.
6979 unsigned NestedLoopCount = CheckOpenMPLoop(
6980 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6981 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6982 VarsWithImplicitDSA, B);
6983
6984 if (NestedLoopCount == 0)
6985 return StmtError();
6986
6987 assert((CurContext->isDependentContext() || B.builtAll()) &&
6988 "omp for loop exprs were not built");
6989
6990 if (!CurContext->isDependentContext()) {
6991 // Finalize the clauses that need pre-built expressions for CodeGen.
6992 for (auto C : Clauses) {
6993 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6994 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6995 B.NumIterations, *this, CurScope,
6996 DSAStack))
6997 return StmtError();
6998 }
6999 }
7000
7001 getCurFunction()->setHasBranchProtectedScope();
7002 return OMPTeamsDistributeParallelForDirective::Create(
7003 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7004}
7005
Kelvin Libf594a52016-12-17 05:48:59 +00007006StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7007 Stmt *AStmt,
7008 SourceLocation StartLoc,
7009 SourceLocation EndLoc) {
7010 if (!AStmt)
7011 return StmtError();
7012
7013 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7014 // 1.2.2 OpenMP Language Terminology
7015 // Structured block - An executable statement with a single entry at the
7016 // top and a single exit at the bottom.
7017 // The point of exit cannot be a branch out of the structured block.
7018 // longjmp() and throw() must not violate the entry/exit criteria.
7019 CS->getCapturedDecl()->setNothrow();
7020
7021 getCurFunction()->setHasBranchProtectedScope();
7022
7023 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7024 AStmt);
7025}
7026
Kelvin Li83c451e2016-12-25 04:52:54 +00007027StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7028 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7029 SourceLocation EndLoc,
7030 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7031 if (!AStmt)
7032 return StmtError();
7033
7034 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7035 // 1.2.2 OpenMP Language Terminology
7036 // Structured block - An executable statement with a single entry at the
7037 // top and a single exit at the bottom.
7038 // The point of exit cannot be a branch out of the structured block.
7039 // longjmp() and throw() must not violate the entry/exit criteria.
7040 CS->getCapturedDecl()->setNothrow();
7041
7042 OMPLoopDirective::HelperExprs B;
7043 // In presence of clause 'collapse' with number of loops, it will
7044 // define the nested loops number.
7045 auto NestedLoopCount = CheckOpenMPLoop(
7046 OMPD_target_teams_distribute,
7047 getCollapseNumberExpr(Clauses),
7048 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7049 VarsWithImplicitDSA, B);
7050 if (NestedLoopCount == 0)
7051 return StmtError();
7052
7053 assert((CurContext->isDependentContext() || B.builtAll()) &&
7054 "omp target teams distribute loop exprs were not built");
7055
7056 getCurFunction()->setHasBranchProtectedScope();
7057 return OMPTargetTeamsDistributeDirective::Create(
7058 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7059}
7060
Kelvin Li80e8f562016-12-29 22:16:30 +00007061StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7062 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7063 SourceLocation EndLoc,
7064 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7065 if (!AStmt)
7066 return StmtError();
7067
7068 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7069 // 1.2.2 OpenMP Language Terminology
7070 // Structured block - An executable statement with a single entry at the
7071 // top and a single exit at the bottom.
7072 // The point of exit cannot be a branch out of the structured block.
7073 // longjmp() and throw() must not violate the entry/exit criteria.
7074 CS->getCapturedDecl()->setNothrow();
7075
7076 OMPLoopDirective::HelperExprs B;
7077 // In presence of clause 'collapse' with number of loops, it will
7078 // define the nested loops number.
7079 auto NestedLoopCount = CheckOpenMPLoop(
7080 OMPD_target_teams_distribute_parallel_for,
7081 getCollapseNumberExpr(Clauses),
7082 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7083 VarsWithImplicitDSA, B);
7084 if (NestedLoopCount == 0)
7085 return StmtError();
7086
7087 assert((CurContext->isDependentContext() || B.builtAll()) &&
7088 "omp target teams distribute parallel for loop exprs were not built");
7089
7090 if (!CurContext->isDependentContext()) {
7091 // Finalize the clauses that need pre-built expressions for CodeGen.
7092 for (auto C : Clauses) {
7093 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7094 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7095 B.NumIterations, *this, CurScope,
7096 DSAStack))
7097 return StmtError();
7098 }
7099 }
7100
7101 getCurFunction()->setHasBranchProtectedScope();
7102 return OMPTargetTeamsDistributeParallelForDirective::Create(
7103 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7104}
7105
Kelvin Li1851df52017-01-03 05:23:48 +00007106StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7107 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7108 SourceLocation EndLoc,
7109 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7110 if (!AStmt)
7111 return StmtError();
7112
7113 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7114 // 1.2.2 OpenMP Language Terminology
7115 // Structured block - An executable statement with a single entry at the
7116 // top and a single exit at the bottom.
7117 // The point of exit cannot be a branch out of the structured block.
7118 // longjmp() and throw() must not violate the entry/exit criteria.
7119 CS->getCapturedDecl()->setNothrow();
7120
7121 OMPLoopDirective::HelperExprs B;
7122 // In presence of clause 'collapse' with number of loops, it will
7123 // define the nested loops number.
7124 auto NestedLoopCount = CheckOpenMPLoop(
7125 OMPD_target_teams_distribute_parallel_for_simd,
7126 getCollapseNumberExpr(Clauses),
7127 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7128 VarsWithImplicitDSA, B);
7129 if (NestedLoopCount == 0)
7130 return StmtError();
7131
7132 assert((CurContext->isDependentContext() || B.builtAll()) &&
7133 "omp target teams distribute parallel for simd loop exprs were not "
7134 "built");
7135
7136 if (!CurContext->isDependentContext()) {
7137 // Finalize the clauses that need pre-built expressions for CodeGen.
7138 for (auto C : Clauses) {
7139 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7140 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7141 B.NumIterations, *this, CurScope,
7142 DSAStack))
7143 return StmtError();
7144 }
7145 }
7146
7147 getCurFunction()->setHasBranchProtectedScope();
7148 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7149 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7150}
7151
Kelvin Lida681182017-01-10 18:08:18 +00007152StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7153 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7154 SourceLocation EndLoc,
7155 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7156 if (!AStmt)
7157 return StmtError();
7158
7159 auto *CS = cast<CapturedStmt>(AStmt);
7160 // 1.2.2 OpenMP Language Terminology
7161 // Structured block - An executable statement with a single entry at the
7162 // top and a single exit at the bottom.
7163 // The point of exit cannot be a branch out of the structured block.
7164 // longjmp() and throw() must not violate the entry/exit criteria.
7165 CS->getCapturedDecl()->setNothrow();
7166
7167 OMPLoopDirective::HelperExprs B;
7168 // In presence of clause 'collapse' with number of loops, it will
7169 // define the nested loops number.
7170 auto NestedLoopCount = CheckOpenMPLoop(
7171 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7172 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7173 VarsWithImplicitDSA, B);
7174 if (NestedLoopCount == 0)
7175 return StmtError();
7176
7177 assert((CurContext->isDependentContext() || B.builtAll()) &&
7178 "omp target teams distribute simd loop exprs were not built");
7179
7180 getCurFunction()->setHasBranchProtectedScope();
7181 return OMPTargetTeamsDistributeSimdDirective::Create(
7182 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7183}
7184
Alexey Bataeved09d242014-05-28 05:53:51 +00007185OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007186 SourceLocation StartLoc,
7187 SourceLocation LParenLoc,
7188 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007189 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007190 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007191 case OMPC_final:
7192 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7193 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007194 case OMPC_num_threads:
7195 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7196 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007197 case OMPC_safelen:
7198 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7199 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007200 case OMPC_simdlen:
7201 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7202 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007203 case OMPC_collapse:
7204 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7205 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007206 case OMPC_ordered:
7207 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7208 break;
Michael Wonge710d542015-08-07 16:16:36 +00007209 case OMPC_device:
7210 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7211 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007212 case OMPC_num_teams:
7213 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7214 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007215 case OMPC_thread_limit:
7216 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7217 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007218 case OMPC_priority:
7219 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7220 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007221 case OMPC_grainsize:
7222 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7223 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007224 case OMPC_num_tasks:
7225 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7226 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007227 case OMPC_hint:
7228 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7229 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007230 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007231 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007232 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007233 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007234 case OMPC_private:
7235 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007236 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007237 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007238 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007239 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007240 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007241 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007242 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007243 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007244 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007245 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007246 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007247 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007248 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007249 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007250 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007251 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007252 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007253 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007254 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007255 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007256 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007257 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007258 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007259 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007260 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007261 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007262 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007263 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007264 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007265 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007266 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007267 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007268 llvm_unreachable("Clause is not allowed.");
7269 }
7270 return Res;
7271}
7272
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007273// An OpenMP directive such as 'target parallel' has two captured regions:
7274// for the 'target' and 'parallel' respectively. This function returns
7275// the region in which to capture expressions associated with a clause.
7276// A return value of OMPD_unknown signifies that the expression should not
7277// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007278static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7279 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7280 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007281 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7282
7283 switch (CKind) {
7284 case OMPC_if:
7285 switch (DKind) {
7286 case OMPD_target_parallel:
7287 // If this clause applies to the nested 'parallel' region, capture within
7288 // the 'target' region, otherwise do not capture.
7289 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7290 CaptureRegion = OMPD_target;
7291 break;
7292 case OMPD_cancel:
7293 case OMPD_parallel:
7294 case OMPD_parallel_sections:
7295 case OMPD_parallel_for:
7296 case OMPD_parallel_for_simd:
7297 case OMPD_target:
7298 case OMPD_target_simd:
7299 case OMPD_target_parallel_for:
7300 case OMPD_target_parallel_for_simd:
7301 case OMPD_target_teams:
7302 case OMPD_target_teams_distribute:
7303 case OMPD_target_teams_distribute_simd:
7304 case OMPD_target_teams_distribute_parallel_for:
7305 case OMPD_target_teams_distribute_parallel_for_simd:
7306 case OMPD_teams_distribute_parallel_for:
7307 case OMPD_teams_distribute_parallel_for_simd:
7308 case OMPD_distribute_parallel_for:
7309 case OMPD_distribute_parallel_for_simd:
7310 case OMPD_task:
7311 case OMPD_taskloop:
7312 case OMPD_taskloop_simd:
7313 case OMPD_target_data:
7314 case OMPD_target_enter_data:
7315 case OMPD_target_exit_data:
7316 case OMPD_target_update:
7317 // Do not capture if-clause expressions.
7318 break;
7319 case OMPD_threadprivate:
7320 case OMPD_taskyield:
7321 case OMPD_barrier:
7322 case OMPD_taskwait:
7323 case OMPD_cancellation_point:
7324 case OMPD_flush:
7325 case OMPD_declare_reduction:
7326 case OMPD_declare_simd:
7327 case OMPD_declare_target:
7328 case OMPD_end_declare_target:
7329 case OMPD_teams:
7330 case OMPD_simd:
7331 case OMPD_for:
7332 case OMPD_for_simd:
7333 case OMPD_sections:
7334 case OMPD_section:
7335 case OMPD_single:
7336 case OMPD_master:
7337 case OMPD_critical:
7338 case OMPD_taskgroup:
7339 case OMPD_distribute:
7340 case OMPD_ordered:
7341 case OMPD_atomic:
7342 case OMPD_distribute_simd:
7343 case OMPD_teams_distribute:
7344 case OMPD_teams_distribute_simd:
7345 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7346 case OMPD_unknown:
7347 llvm_unreachable("Unknown OpenMP directive");
7348 }
7349 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007350 case OMPC_num_threads:
7351 switch (DKind) {
7352 case OMPD_target_parallel:
7353 CaptureRegion = OMPD_target;
7354 break;
7355 case OMPD_cancel:
7356 case OMPD_parallel:
7357 case OMPD_parallel_sections:
7358 case OMPD_parallel_for:
7359 case OMPD_parallel_for_simd:
7360 case OMPD_target:
7361 case OMPD_target_simd:
7362 case OMPD_target_parallel_for:
7363 case OMPD_target_parallel_for_simd:
7364 case OMPD_target_teams:
7365 case OMPD_target_teams_distribute:
7366 case OMPD_target_teams_distribute_simd:
7367 case OMPD_target_teams_distribute_parallel_for:
7368 case OMPD_target_teams_distribute_parallel_for_simd:
7369 case OMPD_teams_distribute_parallel_for:
7370 case OMPD_teams_distribute_parallel_for_simd:
7371 case OMPD_distribute_parallel_for:
7372 case OMPD_distribute_parallel_for_simd:
7373 case OMPD_task:
7374 case OMPD_taskloop:
7375 case OMPD_taskloop_simd:
7376 case OMPD_target_data:
7377 case OMPD_target_enter_data:
7378 case OMPD_target_exit_data:
7379 case OMPD_target_update:
7380 // Do not capture num_threads-clause expressions.
7381 break;
7382 case OMPD_threadprivate:
7383 case OMPD_taskyield:
7384 case OMPD_barrier:
7385 case OMPD_taskwait:
7386 case OMPD_cancellation_point:
7387 case OMPD_flush:
7388 case OMPD_declare_reduction:
7389 case OMPD_declare_simd:
7390 case OMPD_declare_target:
7391 case OMPD_end_declare_target:
7392 case OMPD_teams:
7393 case OMPD_simd:
7394 case OMPD_for:
7395 case OMPD_for_simd:
7396 case OMPD_sections:
7397 case OMPD_section:
7398 case OMPD_single:
7399 case OMPD_master:
7400 case OMPD_critical:
7401 case OMPD_taskgroup:
7402 case OMPD_distribute:
7403 case OMPD_ordered:
7404 case OMPD_atomic:
7405 case OMPD_distribute_simd:
7406 case OMPD_teams_distribute:
7407 case OMPD_teams_distribute_simd:
7408 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7409 case OMPD_unknown:
7410 llvm_unreachable("Unknown OpenMP directive");
7411 }
7412 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007413 case OMPC_num_teams:
7414 switch (DKind) {
7415 case OMPD_target_teams:
7416 CaptureRegion = OMPD_target;
7417 break;
7418 case OMPD_cancel:
7419 case OMPD_parallel:
7420 case OMPD_parallel_sections:
7421 case OMPD_parallel_for:
7422 case OMPD_parallel_for_simd:
7423 case OMPD_target:
7424 case OMPD_target_simd:
7425 case OMPD_target_parallel:
7426 case OMPD_target_parallel_for:
7427 case OMPD_target_parallel_for_simd:
7428 case OMPD_target_teams_distribute:
7429 case OMPD_target_teams_distribute_simd:
7430 case OMPD_target_teams_distribute_parallel_for:
7431 case OMPD_target_teams_distribute_parallel_for_simd:
7432 case OMPD_teams_distribute_parallel_for:
7433 case OMPD_teams_distribute_parallel_for_simd:
7434 case OMPD_distribute_parallel_for:
7435 case OMPD_distribute_parallel_for_simd:
7436 case OMPD_task:
7437 case OMPD_taskloop:
7438 case OMPD_taskloop_simd:
7439 case OMPD_target_data:
7440 case OMPD_target_enter_data:
7441 case OMPD_target_exit_data:
7442 case OMPD_target_update:
7443 case OMPD_teams:
7444 case OMPD_teams_distribute:
7445 case OMPD_teams_distribute_simd:
7446 // Do not capture num_teams-clause expressions.
7447 break;
7448 case OMPD_threadprivate:
7449 case OMPD_taskyield:
7450 case OMPD_barrier:
7451 case OMPD_taskwait:
7452 case OMPD_cancellation_point:
7453 case OMPD_flush:
7454 case OMPD_declare_reduction:
7455 case OMPD_declare_simd:
7456 case OMPD_declare_target:
7457 case OMPD_end_declare_target:
7458 case OMPD_simd:
7459 case OMPD_for:
7460 case OMPD_for_simd:
7461 case OMPD_sections:
7462 case OMPD_section:
7463 case OMPD_single:
7464 case OMPD_master:
7465 case OMPD_critical:
7466 case OMPD_taskgroup:
7467 case OMPD_distribute:
7468 case OMPD_ordered:
7469 case OMPD_atomic:
7470 case OMPD_distribute_simd:
7471 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7472 case OMPD_unknown:
7473 llvm_unreachable("Unknown OpenMP directive");
7474 }
7475 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007476 case OMPC_thread_limit:
7477 switch (DKind) {
7478 case OMPD_target_teams:
7479 CaptureRegion = OMPD_target;
7480 break;
7481 case OMPD_cancel:
7482 case OMPD_parallel:
7483 case OMPD_parallel_sections:
7484 case OMPD_parallel_for:
7485 case OMPD_parallel_for_simd:
7486 case OMPD_target:
7487 case OMPD_target_simd:
7488 case OMPD_target_parallel:
7489 case OMPD_target_parallel_for:
7490 case OMPD_target_parallel_for_simd:
7491 case OMPD_target_teams_distribute:
7492 case OMPD_target_teams_distribute_simd:
7493 case OMPD_target_teams_distribute_parallel_for:
7494 case OMPD_target_teams_distribute_parallel_for_simd:
7495 case OMPD_teams_distribute_parallel_for:
7496 case OMPD_teams_distribute_parallel_for_simd:
7497 case OMPD_distribute_parallel_for:
7498 case OMPD_distribute_parallel_for_simd:
7499 case OMPD_task:
7500 case OMPD_taskloop:
7501 case OMPD_taskloop_simd:
7502 case OMPD_target_data:
7503 case OMPD_target_enter_data:
7504 case OMPD_target_exit_data:
7505 case OMPD_target_update:
7506 case OMPD_teams:
7507 case OMPD_teams_distribute:
7508 case OMPD_teams_distribute_simd:
7509 // Do not capture thread_limit-clause expressions.
7510 break;
7511 case OMPD_threadprivate:
7512 case OMPD_taskyield:
7513 case OMPD_barrier:
7514 case OMPD_taskwait:
7515 case OMPD_cancellation_point:
7516 case OMPD_flush:
7517 case OMPD_declare_reduction:
7518 case OMPD_declare_simd:
7519 case OMPD_declare_target:
7520 case OMPD_end_declare_target:
7521 case OMPD_simd:
7522 case OMPD_for:
7523 case OMPD_for_simd:
7524 case OMPD_sections:
7525 case OMPD_section:
7526 case OMPD_single:
7527 case OMPD_master:
7528 case OMPD_critical:
7529 case OMPD_taskgroup:
7530 case OMPD_distribute:
7531 case OMPD_ordered:
7532 case OMPD_atomic:
7533 case OMPD_distribute_simd:
7534 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7535 case OMPD_unknown:
7536 llvm_unreachable("Unknown OpenMP directive");
7537 }
7538 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007539 case OMPC_schedule:
7540 case OMPC_dist_schedule:
7541 case OMPC_firstprivate:
7542 case OMPC_lastprivate:
7543 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007544 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007545 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007546 case OMPC_linear:
7547 case OMPC_default:
7548 case OMPC_proc_bind:
7549 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007550 case OMPC_safelen:
7551 case OMPC_simdlen:
7552 case OMPC_collapse:
7553 case OMPC_private:
7554 case OMPC_shared:
7555 case OMPC_aligned:
7556 case OMPC_copyin:
7557 case OMPC_copyprivate:
7558 case OMPC_ordered:
7559 case OMPC_nowait:
7560 case OMPC_untied:
7561 case OMPC_mergeable:
7562 case OMPC_threadprivate:
7563 case OMPC_flush:
7564 case OMPC_read:
7565 case OMPC_write:
7566 case OMPC_update:
7567 case OMPC_capture:
7568 case OMPC_seq_cst:
7569 case OMPC_depend:
7570 case OMPC_device:
7571 case OMPC_threads:
7572 case OMPC_simd:
7573 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007574 case OMPC_priority:
7575 case OMPC_grainsize:
7576 case OMPC_nogroup:
7577 case OMPC_num_tasks:
7578 case OMPC_hint:
7579 case OMPC_defaultmap:
7580 case OMPC_unknown:
7581 case OMPC_uniform:
7582 case OMPC_to:
7583 case OMPC_from:
7584 case OMPC_use_device_ptr:
7585 case OMPC_is_device_ptr:
7586 llvm_unreachable("Unexpected OpenMP clause.");
7587 }
7588 return CaptureRegion;
7589}
7590
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007591OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7592 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007593 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007594 SourceLocation NameModifierLoc,
7595 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007596 SourceLocation EndLoc) {
7597 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007598 Stmt *HelperValStmt = nullptr;
7599 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007600 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7601 !Condition->isInstantiationDependent() &&
7602 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007603 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007604 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007605 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007606
Richard Smith03a4aa32016-06-23 19:02:52 +00007607 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007608
7609 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7610 CaptureRegion =
7611 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7612 if (CaptureRegion != OMPD_unknown) {
7613 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7614 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7615 HelperValStmt = buildPreInits(Context, Captures);
7616 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007617 }
7618
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007619 return new (Context)
7620 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7621 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007622}
7623
Alexey Bataev3778b602014-07-17 07:32:53 +00007624OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7625 SourceLocation StartLoc,
7626 SourceLocation LParenLoc,
7627 SourceLocation EndLoc) {
7628 Expr *ValExpr = Condition;
7629 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7630 !Condition->isInstantiationDependent() &&
7631 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007632 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007633 if (Val.isInvalid())
7634 return nullptr;
7635
Richard Smith03a4aa32016-06-23 19:02:52 +00007636 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007637 }
7638
7639 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7640}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007641ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7642 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007643 if (!Op)
7644 return ExprError();
7645
7646 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7647 public:
7648 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007649 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007650 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7651 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007652 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7653 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007654 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7655 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007656 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7657 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007658 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7659 QualType T,
7660 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007661 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7662 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007663 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7664 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007665 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007666 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007667 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007668 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7669 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007670 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7671 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007672 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7673 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007674 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007675 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007676 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007677 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7678 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007679 llvm_unreachable("conversion functions are permitted");
7680 }
7681 } ConvertDiagnoser;
7682 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7683}
7684
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007685static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007686 OpenMPClauseKind CKind,
7687 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007688 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7689 !ValExpr->isInstantiationDependent()) {
7690 SourceLocation Loc = ValExpr->getExprLoc();
7691 ExprResult Value =
7692 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7693 if (Value.isInvalid())
7694 return false;
7695
7696 ValExpr = Value.get();
7697 // The expression must evaluate to a non-negative integer value.
7698 llvm::APSInt Result;
7699 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007700 Result.isSigned() &&
7701 !((!StrictlyPositive && Result.isNonNegative()) ||
7702 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007703 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007704 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7705 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007706 return false;
7707 }
7708 }
7709 return true;
7710}
7711
Alexey Bataev568a8332014-03-06 06:15:19 +00007712OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7713 SourceLocation StartLoc,
7714 SourceLocation LParenLoc,
7715 SourceLocation EndLoc) {
7716 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007717 Stmt *HelperValStmt = nullptr;
7718 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007719
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007720 // OpenMP [2.5, Restrictions]
7721 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007722 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7723 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007724 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007725
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007726 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7727 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7728 if (CaptureRegion != OMPD_unknown) {
7729 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7730 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7731 HelperValStmt = buildPreInits(Context, Captures);
7732 }
7733
7734 return new (Context) OMPNumThreadsClause(
7735 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007736}
7737
Alexey Bataev62c87d22014-03-21 04:51:18 +00007738ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007739 OpenMPClauseKind CKind,
7740 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007741 if (!E)
7742 return ExprError();
7743 if (E->isValueDependent() || E->isTypeDependent() ||
7744 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007745 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007746 llvm::APSInt Result;
7747 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7748 if (ICE.isInvalid())
7749 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007750 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7751 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007752 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007753 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7754 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007755 return ExprError();
7756 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007757 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7758 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7759 << E->getSourceRange();
7760 return ExprError();
7761 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007762 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7763 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007764 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007765 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007766 return ICE;
7767}
7768
7769OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7770 SourceLocation LParenLoc,
7771 SourceLocation EndLoc) {
7772 // OpenMP [2.8.1, simd construct, Description]
7773 // The parameter of the safelen clause must be a constant
7774 // positive integer expression.
7775 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7776 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007777 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007778 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007779 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007780}
7781
Alexey Bataev66b15b52015-08-21 11:14:16 +00007782OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7783 SourceLocation LParenLoc,
7784 SourceLocation EndLoc) {
7785 // OpenMP [2.8.1, simd construct, Description]
7786 // The parameter of the simdlen clause must be a constant
7787 // positive integer expression.
7788 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7789 if (Simdlen.isInvalid())
7790 return nullptr;
7791 return new (Context)
7792 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7793}
7794
Alexander Musman64d33f12014-06-04 07:53:32 +00007795OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7796 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007797 SourceLocation LParenLoc,
7798 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007799 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007800 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007801 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007802 // The parameter of the collapse clause must be a constant
7803 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007804 ExprResult NumForLoopsResult =
7805 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7806 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007807 return nullptr;
7808 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007809 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007810}
7811
Alexey Bataev10e775f2015-07-30 11:36:16 +00007812OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7813 SourceLocation EndLoc,
7814 SourceLocation LParenLoc,
7815 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007816 // OpenMP [2.7.1, loop construct, Description]
7817 // OpenMP [2.8.1, simd construct, Description]
7818 // OpenMP [2.9.6, distribute construct, Description]
7819 // The parameter of the ordered clause must be a constant
7820 // positive integer expression if any.
7821 if (NumForLoops && LParenLoc.isValid()) {
7822 ExprResult NumForLoopsResult =
7823 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7824 if (NumForLoopsResult.isInvalid())
7825 return nullptr;
7826 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007827 } else
7828 NumForLoops = nullptr;
7829 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007830 return new (Context)
7831 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7832}
7833
Alexey Bataeved09d242014-05-28 05:53:51 +00007834OMPClause *Sema::ActOnOpenMPSimpleClause(
7835 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7836 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007837 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007838 switch (Kind) {
7839 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007840 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007841 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7842 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007843 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007844 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007845 Res = ActOnOpenMPProcBindClause(
7846 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7847 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007848 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007849 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007850 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007851 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007852 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007853 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007854 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007855 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007856 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007857 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007858 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007859 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007860 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007861 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007862 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007863 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007864 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007865 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007866 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007867 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007868 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007869 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007870 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007871 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007872 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007873 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007874 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007875 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007876 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007877 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007878 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007879 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007880 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007881 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007882 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007883 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007884 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007885 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007886 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007887 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007888 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007889 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007890 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007891 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007892 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007893 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007894 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007895 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007896 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007897 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007898 llvm_unreachable("Clause is not allowed.");
7899 }
7900 return Res;
7901}
7902
Alexey Bataev6402bca2015-12-28 07:25:51 +00007903static std::string
7904getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7905 ArrayRef<unsigned> Exclude = llvm::None) {
7906 std::string Values;
7907 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7908 unsigned Skipped = Exclude.size();
7909 auto S = Exclude.begin(), E = Exclude.end();
7910 for (unsigned i = First; i < Last; ++i) {
7911 if (std::find(S, E, i) != E) {
7912 --Skipped;
7913 continue;
7914 }
7915 Values += "'";
7916 Values += getOpenMPSimpleClauseTypeName(K, i);
7917 Values += "'";
7918 if (i == Bound - Skipped)
7919 Values += " or ";
7920 else if (i != Bound + 1 - Skipped)
7921 Values += ", ";
7922 }
7923 return Values;
7924}
7925
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007926OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7927 SourceLocation KindKwLoc,
7928 SourceLocation StartLoc,
7929 SourceLocation LParenLoc,
7930 SourceLocation EndLoc) {
7931 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007932 static_assert(OMPC_DEFAULT_unknown > 0,
7933 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007934 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007935 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7936 /*Last=*/OMPC_DEFAULT_unknown)
7937 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007938 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007939 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007940 switch (Kind) {
7941 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007942 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007943 break;
7944 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007945 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007946 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007947 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007948 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007949 break;
7950 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007951 return new (Context)
7952 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007953}
7954
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007955OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7956 SourceLocation KindKwLoc,
7957 SourceLocation StartLoc,
7958 SourceLocation LParenLoc,
7959 SourceLocation EndLoc) {
7960 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007961 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007962 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7963 /*Last=*/OMPC_PROC_BIND_unknown)
7964 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007965 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007966 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007967 return new (Context)
7968 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007969}
7970
Alexey Bataev56dafe82014-06-20 07:16:17 +00007971OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007972 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007973 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007974 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007975 SourceLocation EndLoc) {
7976 OMPClause *Res = nullptr;
7977 switch (Kind) {
7978 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007979 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7980 assert(Argument.size() == NumberOfElements &&
7981 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007982 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007983 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7984 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7985 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7986 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7987 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007988 break;
7989 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007990 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7991 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7992 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7993 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007994 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007995 case OMPC_dist_schedule:
7996 Res = ActOnOpenMPDistScheduleClause(
7997 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7998 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7999 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008000 case OMPC_defaultmap:
8001 enum { Modifier, DefaultmapKind };
8002 Res = ActOnOpenMPDefaultmapClause(
8003 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8004 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008005 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8006 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008007 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008008 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008009 case OMPC_num_threads:
8010 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008011 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008012 case OMPC_collapse:
8013 case OMPC_default:
8014 case OMPC_proc_bind:
8015 case OMPC_private:
8016 case OMPC_firstprivate:
8017 case OMPC_lastprivate:
8018 case OMPC_shared:
8019 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008020 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008021 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008022 case OMPC_linear:
8023 case OMPC_aligned:
8024 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008025 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008026 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008027 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008028 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008029 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008030 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008031 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008032 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008033 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008034 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008035 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008036 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008037 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008038 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008039 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008040 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008041 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008042 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008043 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008044 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008045 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008046 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008047 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008048 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008049 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008050 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008051 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008052 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008053 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008054 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008055 llvm_unreachable("Clause is not allowed.");
8056 }
8057 return Res;
8058}
8059
Alexey Bataev6402bca2015-12-28 07:25:51 +00008060static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8061 OpenMPScheduleClauseModifier M2,
8062 SourceLocation M1Loc, SourceLocation M2Loc) {
8063 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8064 SmallVector<unsigned, 2> Excluded;
8065 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8066 Excluded.push_back(M2);
8067 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8068 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8069 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8070 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8071 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8072 << getListOfPossibleValues(OMPC_schedule,
8073 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8074 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8075 Excluded)
8076 << getOpenMPClauseName(OMPC_schedule);
8077 return true;
8078 }
8079 return false;
8080}
8081
Alexey Bataev56dafe82014-06-20 07:16:17 +00008082OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008083 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008084 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008085 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8086 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8087 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8088 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8089 return nullptr;
8090 // OpenMP, 2.7.1, Loop Construct, Restrictions
8091 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8092 // but not both.
8093 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8094 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8095 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8096 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8097 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8098 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8099 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8100 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8101 return nullptr;
8102 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008103 if (Kind == OMPC_SCHEDULE_unknown) {
8104 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008105 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8106 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8107 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8108 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8109 Exclude);
8110 } else {
8111 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8112 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008113 }
8114 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8115 << Values << getOpenMPClauseName(OMPC_schedule);
8116 return nullptr;
8117 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008118 // OpenMP, 2.7.1, Loop Construct, Restrictions
8119 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8120 // schedule(guided).
8121 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8122 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8123 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8124 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8125 diag::err_omp_schedule_nonmonotonic_static);
8126 return nullptr;
8127 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008128 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008129 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008130 if (ChunkSize) {
8131 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8132 !ChunkSize->isInstantiationDependent() &&
8133 !ChunkSize->containsUnexpandedParameterPack()) {
8134 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8135 ExprResult Val =
8136 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8137 if (Val.isInvalid())
8138 return nullptr;
8139
8140 ValExpr = Val.get();
8141
8142 // OpenMP [2.7.1, Restrictions]
8143 // chunk_size must be a loop invariant integer expression with a positive
8144 // value.
8145 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008146 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8147 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8148 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008149 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008150 return nullptr;
8151 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008152 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
8153 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008154 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8155 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8156 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008157 }
8158 }
8159 }
8160
Alexey Bataev6402bca2015-12-28 07:25:51 +00008161 return new (Context)
8162 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008163 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008164}
8165
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008166OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8167 SourceLocation StartLoc,
8168 SourceLocation EndLoc) {
8169 OMPClause *Res = nullptr;
8170 switch (Kind) {
8171 case OMPC_ordered:
8172 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8173 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008174 case OMPC_nowait:
8175 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8176 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008177 case OMPC_untied:
8178 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8179 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008180 case OMPC_mergeable:
8181 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8182 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008183 case OMPC_read:
8184 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8185 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008186 case OMPC_write:
8187 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8188 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008189 case OMPC_update:
8190 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8191 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008192 case OMPC_capture:
8193 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8194 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008195 case OMPC_seq_cst:
8196 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8197 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008198 case OMPC_threads:
8199 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8200 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008201 case OMPC_simd:
8202 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8203 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008204 case OMPC_nogroup:
8205 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8206 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008207 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008208 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008209 case OMPC_num_threads:
8210 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008211 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008212 case OMPC_collapse:
8213 case OMPC_schedule:
8214 case OMPC_private:
8215 case OMPC_firstprivate:
8216 case OMPC_lastprivate:
8217 case OMPC_shared:
8218 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008219 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008220 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008221 case OMPC_linear:
8222 case OMPC_aligned:
8223 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008224 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008225 case OMPC_default:
8226 case OMPC_proc_bind:
8227 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008228 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008229 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008230 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008231 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008232 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008233 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008234 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008235 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008236 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008237 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008238 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008239 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008240 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008241 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008242 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008243 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008244 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008245 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008246 llvm_unreachable("Clause is not allowed.");
8247 }
8248 return Res;
8249}
8250
Alexey Bataev236070f2014-06-20 11:19:47 +00008251OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8252 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008253 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008254 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8255}
8256
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008257OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8258 SourceLocation EndLoc) {
8259 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8260}
8261
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008262OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8263 SourceLocation EndLoc) {
8264 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8265}
8266
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008267OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8268 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008269 return new (Context) OMPReadClause(StartLoc, EndLoc);
8270}
8271
Alexey Bataevdea47612014-07-23 07:46:59 +00008272OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8273 SourceLocation EndLoc) {
8274 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8275}
8276
Alexey Bataev67a4f222014-07-23 10:25:33 +00008277OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8278 SourceLocation EndLoc) {
8279 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8280}
8281
Alexey Bataev459dec02014-07-24 06:46:57 +00008282OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8283 SourceLocation EndLoc) {
8284 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8285}
8286
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008287OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8288 SourceLocation EndLoc) {
8289 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8290}
8291
Alexey Bataev346265e2015-09-25 10:37:12 +00008292OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8293 SourceLocation EndLoc) {
8294 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8295}
8296
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008297OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8298 SourceLocation EndLoc) {
8299 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8300}
8301
Alexey Bataevb825de12015-12-07 10:51:44 +00008302OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8303 SourceLocation EndLoc) {
8304 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8305}
8306
Alexey Bataevc5e02582014-06-16 07:08:35 +00008307OMPClause *Sema::ActOnOpenMPVarListClause(
8308 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8309 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8310 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008311 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008312 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8313 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8314 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008315 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008316 switch (Kind) {
8317 case OMPC_private:
8318 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8319 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008320 case OMPC_firstprivate:
8321 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8322 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008323 case OMPC_lastprivate:
8324 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8325 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008326 case OMPC_shared:
8327 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8328 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008329 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008330 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8331 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008332 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008333 case OMPC_task_reduction:
8334 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8335 EndLoc, ReductionIdScopeSpec,
8336 ReductionId);
8337 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008338 case OMPC_in_reduction:
8339 Res =
8340 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8341 EndLoc, ReductionIdScopeSpec, ReductionId);
8342 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008343 case OMPC_linear:
8344 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008345 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008346 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008347 case OMPC_aligned:
8348 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8349 ColonLoc, EndLoc);
8350 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008351 case OMPC_copyin:
8352 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8353 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008354 case OMPC_copyprivate:
8355 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8356 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008357 case OMPC_flush:
8358 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8359 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008360 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008361 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008362 StartLoc, LParenLoc, EndLoc);
8363 break;
8364 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008365 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8366 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8367 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008368 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008369 case OMPC_to:
8370 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8371 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008372 case OMPC_from:
8373 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8374 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008375 case OMPC_use_device_ptr:
8376 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8377 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008378 case OMPC_is_device_ptr:
8379 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8380 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008381 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008382 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008383 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008384 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008385 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008386 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008387 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008388 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008389 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008390 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008391 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008392 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008393 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008394 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008395 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008396 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008397 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008398 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008399 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008400 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008401 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008402 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008403 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008404 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008405 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008406 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008407 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008408 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008409 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008410 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008411 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008412 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008413 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008414 llvm_unreachable("Clause is not allowed.");
8415 }
8416 return Res;
8417}
8418
Alexey Bataev90c228f2016-02-08 09:29:13 +00008419ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008420 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008421 ExprResult Res = BuildDeclRefExpr(
8422 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8423 if (!Res.isUsable())
8424 return ExprError();
8425 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8426 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8427 if (!Res.isUsable())
8428 return ExprError();
8429 }
8430 if (VK != VK_LValue && Res.get()->isGLValue()) {
8431 Res = DefaultLvalueConversion(Res.get());
8432 if (!Res.isUsable())
8433 return ExprError();
8434 }
8435 return Res;
8436}
8437
Alexey Bataev60da77e2016-02-29 05:54:20 +00008438static std::pair<ValueDecl *, bool>
8439getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8440 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008441 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8442 RefExpr->containsUnexpandedParameterPack())
8443 return std::make_pair(nullptr, true);
8444
Alexey Bataevd985eda2016-02-10 11:29:16 +00008445 // OpenMP [3.1, C/C++]
8446 // A list item is a variable name.
8447 // OpenMP [2.9.3.3, Restrictions, p.1]
8448 // A variable that is part of another variable (as an array or
8449 // structure element) cannot appear in a private clause.
8450 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008451 enum {
8452 NoArrayExpr = -1,
8453 ArraySubscript = 0,
8454 OMPArraySection = 1
8455 } IsArrayExpr = NoArrayExpr;
8456 if (AllowArraySection) {
8457 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8458 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8459 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8460 Base = TempASE->getBase()->IgnoreParenImpCasts();
8461 RefExpr = Base;
8462 IsArrayExpr = ArraySubscript;
8463 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8464 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8465 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8466 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8467 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8468 Base = TempASE->getBase()->IgnoreParenImpCasts();
8469 RefExpr = Base;
8470 IsArrayExpr = OMPArraySection;
8471 }
8472 }
8473 ELoc = RefExpr->getExprLoc();
8474 ERange = RefExpr->getSourceRange();
8475 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008476 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8477 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8478 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8479 (S.getCurrentThisType().isNull() || !ME ||
8480 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8481 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008482 if (IsArrayExpr != NoArrayExpr)
8483 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8484 << ERange;
8485 else {
8486 S.Diag(ELoc,
8487 AllowArraySection
8488 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8489 : diag::err_omp_expected_var_name_member_expr)
8490 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8491 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008492 return std::make_pair(nullptr, false);
8493 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008494 return std::make_pair(
8495 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008496}
8497
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008498OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8499 SourceLocation StartLoc,
8500 SourceLocation LParenLoc,
8501 SourceLocation EndLoc) {
8502 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008503 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008504 for (auto &RefExpr : VarList) {
8505 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008506 SourceLocation ELoc;
8507 SourceRange ERange;
8508 Expr *SimpleRefExpr = RefExpr;
8509 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008510 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008511 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008512 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008513 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008514 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008515 ValueDecl *D = Res.first;
8516 if (!D)
8517 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008518
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008519 QualType Type = D->getType();
8520 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008521
8522 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8523 // A variable that appears in a private clause must not have an incomplete
8524 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008525 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008526 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008527 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008528
Alexey Bataev758e55e2013-09-06 18:03:48 +00008529 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8530 // in a Construct]
8531 // Variables with the predetermined data-sharing attributes may not be
8532 // listed in data-sharing attributes clauses, except for the cases
8533 // listed below. For these exceptions only, listing a predetermined
8534 // variable in a data-sharing attribute clause is allowed and overrides
8535 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008536 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008537 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008538 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8539 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008540 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008541 continue;
8542 }
8543
Kelvin Libf594a52016-12-17 05:48:59 +00008544 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008545 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008546 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008547 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008548 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8549 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008550 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008551 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008552 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008554 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008556 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008557 continue;
8558 }
8559
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008560 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8561 // A list item cannot appear in both a map clause and a data-sharing
8562 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008563 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008564 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008565 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008566 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008567 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008568 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008569 CurrDir == OMPD_target_parallel_for_simd ||
8570 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008571 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008572 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008573 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008574 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8575 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8576 ConflictKind = WhereFoundClauseKind;
8577 return true;
8578 })) {
8579 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008580 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008581 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008582 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008583 ReportOriginalDSA(*this, DSAStack, D, DVar);
8584 continue;
8585 }
8586 }
8587
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008588 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8589 // A variable of class type (or array thereof) that appears in a private
8590 // clause requires an accessible, unambiguous default constructor for the
8591 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008592 // Generate helper private variable and initialize it with the default
8593 // value. The address of the original variable is replaced by the address of
8594 // the new private variable in CodeGen. This new variable is not added to
8595 // IdResolver, so the code in the OpenMP region uses original variable for
8596 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008597 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008598 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8599 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008600 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008601 if (VDPrivate->isInvalidDecl())
8602 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008603 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008604 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008605
Alexey Bataev90c228f2016-02-08 09:29:13 +00008606 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008607 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008608 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008609 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008610 Vars.push_back((VD || CurContext->isDependentContext())
8611 ? RefExpr->IgnoreParens()
8612 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008613 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008614 }
8615
Alexey Bataeved09d242014-05-28 05:53:51 +00008616 if (Vars.empty())
8617 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008618
Alexey Bataev03b340a2014-10-21 03:16:40 +00008619 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8620 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008621}
8622
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008623namespace {
8624class DiagsUninitializedSeveretyRAII {
8625private:
8626 DiagnosticsEngine &Diags;
8627 SourceLocation SavedLoc;
8628 bool IsIgnored;
8629
8630public:
8631 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8632 bool IsIgnored)
8633 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8634 if (!IsIgnored) {
8635 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8636 /*Map*/ diag::Severity::Ignored, Loc);
8637 }
8638 }
8639 ~DiagsUninitializedSeveretyRAII() {
8640 if (!IsIgnored)
8641 Diags.popMappings(SavedLoc);
8642 }
8643};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008644}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008645
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008646OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8647 SourceLocation StartLoc,
8648 SourceLocation LParenLoc,
8649 SourceLocation EndLoc) {
8650 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008651 SmallVector<Expr *, 8> PrivateCopies;
8652 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008653 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008654 bool IsImplicitClause =
8655 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8656 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8657
Alexey Bataeved09d242014-05-28 05:53:51 +00008658 for (auto &RefExpr : VarList) {
8659 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008660 SourceLocation ELoc;
8661 SourceRange ERange;
8662 Expr *SimpleRefExpr = RefExpr;
8663 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008664 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008665 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008666 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008667 PrivateCopies.push_back(nullptr);
8668 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008669 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008670 ValueDecl *D = Res.first;
8671 if (!D)
8672 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008673
Alexey Bataev60da77e2016-02-29 05:54:20 +00008674 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008675 QualType Type = D->getType();
8676 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008677
8678 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8679 // A variable that appears in a private clause must not have an incomplete
8680 // type or a reference type.
8681 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008682 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008683 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008684 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008685
8686 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8687 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008688 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008689 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008690 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008691
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008692 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008693 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008694 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008695 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008696 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008697 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008698 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008699 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8700 // A list item that specifies a given variable may not appear in more
8701 // than one clause on the same directive, except that a variable may be
8702 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008703 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8704 // A list item may appear in a firstprivate or lastprivate clause but not
8705 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008706 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008707 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8708 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008709 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008710 << getOpenMPClauseName(DVar.CKind)
8711 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008712 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008713 continue;
8714 }
8715
8716 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8717 // in a Construct]
8718 // Variables with the predetermined data-sharing attributes may not be
8719 // listed in data-sharing attributes clauses, except for the cases
8720 // listed below. For these exceptions only, listing a predetermined
8721 // variable in a data-sharing attribute clause is allowed and overrides
8722 // the variable's predetermined data-sharing attributes.
8723 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8724 // in a Construct, C/C++, p.2]
8725 // Variables with const-qualified type having no mutable member may be
8726 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008727 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008728 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8729 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008730 << getOpenMPClauseName(DVar.CKind)
8731 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008732 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008733 continue;
8734 }
8735
8736 // OpenMP [2.9.3.4, Restrictions, p.2]
8737 // A list item that is private within a parallel region must not appear
8738 // in a firstprivate clause on a worksharing construct if any of the
8739 // worksharing regions arising from the worksharing construct ever bind
8740 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008741 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8742 // A list item that is private within a teams region must not appear in a
8743 // firstprivate clause on a distribute construct if any of the distribute
8744 // regions arising from the distribute construct ever bind to any of the
8745 // teams regions arising from the teams construct.
8746 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8747 // A list item that appears in a reduction clause of a teams construct
8748 // must not appear in a firstprivate clause on a distribute construct if
8749 // any of the distribute regions arising from the distribute construct
8750 // ever bind to any of the teams regions arising from the teams construct.
8751 if ((isOpenMPWorksharingDirective(CurrDir) ||
8752 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008753 !isOpenMPParallelDirective(CurrDir) &&
8754 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008755 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008756 if (DVar.CKind != OMPC_shared &&
8757 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008758 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008759 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008760 Diag(ELoc, diag::err_omp_required_access)
8761 << getOpenMPClauseName(OMPC_firstprivate)
8762 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008763 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008764 continue;
8765 }
8766 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008767 // OpenMP [2.9.3.4, Restrictions, p.3]
8768 // A list item that appears in a reduction clause of a parallel construct
8769 // must not appear in a firstprivate clause on a worksharing or task
8770 // construct if any of the worksharing or task regions arising from the
8771 // worksharing or task construct ever bind to any of the parallel regions
8772 // arising from the parallel construct.
8773 // OpenMP [2.9.3.4, Restrictions, p.4]
8774 // A list item that appears in a reduction clause in worksharing
8775 // construct must not appear in a firstprivate clause in a task construct
8776 // encountered during execution of any of the worksharing regions arising
8777 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008778 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008779 DVar = DSAStack->hasInnermostDSA(
8780 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8781 [](OpenMPDirectiveKind K) -> bool {
8782 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008783 isOpenMPWorksharingDirective(K) ||
8784 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008785 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008786 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008787 if (DVar.CKind == OMPC_reduction &&
8788 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008789 isOpenMPWorksharingDirective(DVar.DKind) ||
8790 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008791 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8792 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008793 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008794 continue;
8795 }
8796 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008797
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008798 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8799 // A list item cannot appear in both a map clause and a data-sharing
8800 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008801 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008802 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008803 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008804 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008805 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008806 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008807 CurrDir == OMPD_target_parallel_for_simd ||
8808 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008809 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008810 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008811 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008812 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8813 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8814 ConflictKind = WhereFoundClauseKind;
8815 return true;
8816 })) {
8817 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008818 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008819 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008820 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8821 ReportOriginalDSA(*this, DSAStack, D, DVar);
8822 continue;
8823 }
8824 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008825 }
8826
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008827 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008828 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008829 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008830 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8831 << getOpenMPClauseName(OMPC_firstprivate) << Type
8832 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8833 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008834 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008835 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008836 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008837 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008838 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008839 continue;
8840 }
8841
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008842 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008843 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8844 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008845 // Generate helper private variable and initialize it with the value of the
8846 // original variable. The address of the original variable is replaced by
8847 // the address of the new private variable in the CodeGen. This new variable
8848 // is not added to IdResolver, so the code in the OpenMP region uses
8849 // original variable for proper diagnostics and variable capturing.
8850 Expr *VDInitRefExpr = nullptr;
8851 // For arrays generate initializer for single element and replace it by the
8852 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008853 if (Type->isArrayType()) {
8854 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008855 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008856 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008857 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008858 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008859 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008860 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008861 InitializedEntity Entity =
8862 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008863 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8864
8865 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8866 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8867 if (Result.isInvalid())
8868 VDPrivate->setInvalidDecl();
8869 else
8870 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008871 // Remove temp variable declaration.
8872 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008873 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008874 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8875 ".firstprivate.temp");
8876 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8877 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008878 AddInitializerToDecl(VDPrivate,
8879 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008880 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008881 }
8882 if (VDPrivate->isInvalidDecl()) {
8883 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008884 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008885 diag::note_omp_task_predetermined_firstprivate_here);
8886 }
8887 continue;
8888 }
8889 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008890 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008891 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8892 RefExpr->getExprLoc());
8893 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008894 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008895 if (TopDVar.CKind == OMPC_lastprivate)
8896 Ref = TopDVar.PrivateCopy;
8897 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008898 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008899 if (!IsOpenMPCapturedDecl(D))
8900 ExprCaptures.push_back(Ref->getDecl());
8901 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008902 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008903 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008904 Vars.push_back((VD || CurContext->isDependentContext())
8905 ? RefExpr->IgnoreParens()
8906 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008907 PrivateCopies.push_back(VDPrivateRefExpr);
8908 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008909 }
8910
Alexey Bataeved09d242014-05-28 05:53:51 +00008911 if (Vars.empty())
8912 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008913
8914 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008915 Vars, PrivateCopies, Inits,
8916 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008917}
8918
Alexander Musman1bb328c2014-06-04 13:06:39 +00008919OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8920 SourceLocation StartLoc,
8921 SourceLocation LParenLoc,
8922 SourceLocation EndLoc) {
8923 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008924 SmallVector<Expr *, 8> SrcExprs;
8925 SmallVector<Expr *, 8> DstExprs;
8926 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008927 SmallVector<Decl *, 4> ExprCaptures;
8928 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008929 for (auto &RefExpr : VarList) {
8930 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008931 SourceLocation ELoc;
8932 SourceRange ERange;
8933 Expr *SimpleRefExpr = RefExpr;
8934 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008935 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008936 // It will be analyzed later.
8937 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008938 SrcExprs.push_back(nullptr);
8939 DstExprs.push_back(nullptr);
8940 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008941 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008942 ValueDecl *D = Res.first;
8943 if (!D)
8944 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008945
Alexey Bataev74caaf22016-02-20 04:09:36 +00008946 QualType Type = D->getType();
8947 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008948
8949 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8950 // A variable that appears in a lastprivate clause must not have an
8951 // incomplete type or a reference type.
8952 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008953 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008954 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008955 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008956
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008957 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008958 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8959 // in a Construct]
8960 // Variables with the predetermined data-sharing attributes may not be
8961 // listed in data-sharing attributes clauses, except for the cases
8962 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008963 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8964 // A list item may appear in a firstprivate or lastprivate clause but not
8965 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008966 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008967 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008968 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00008969 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8970 Diag(ELoc, diag::err_omp_wrong_dsa)
8971 << getOpenMPClauseName(DVar.CKind)
8972 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008973 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008974 continue;
8975 }
8976
Alexey Bataevf29276e2014-06-18 04:14:57 +00008977 // OpenMP [2.14.3.5, Restrictions, p.2]
8978 // A list item that is private within a parallel region, or that appears in
8979 // the reduction clause of a parallel construct, must not appear in a
8980 // lastprivate clause on a worksharing construct if any of the corresponding
8981 // worksharing regions ever binds to any of the corresponding parallel
8982 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008983 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008984 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008985 !isOpenMPParallelDirective(CurrDir) &&
8986 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008987 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008988 if (DVar.CKind != OMPC_shared) {
8989 Diag(ELoc, diag::err_omp_required_access)
8990 << getOpenMPClauseName(OMPC_lastprivate)
8991 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008992 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008993 continue;
8994 }
8995 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008996
Alexander Musman1bb328c2014-06-04 13:06:39 +00008997 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008998 // A variable of class type (or array thereof) that appears in a
8999 // lastprivate clause requires an accessible, unambiguous default
9000 // constructor for the class type, unless the list item is also specified
9001 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009002 // A variable of class type (or array thereof) that appears in a
9003 // lastprivate clause requires an accessible, unambiguous copy assignment
9004 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009005 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009006 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009007 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009008 D->hasAttrs() ? &D->getAttrs() : nullptr);
9009 auto *PseudoSrcExpr =
9010 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009011 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009012 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009013 D->hasAttrs() ? &D->getAttrs() : nullptr);
9014 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009015 // For arrays generate assignment operation for single element and replace
9016 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009017 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009018 PseudoDstExpr, PseudoSrcExpr);
9019 if (AssignmentOp.isInvalid())
9020 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009021 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009022 /*DiscardedValue=*/true);
9023 if (AssignmentOp.isInvalid())
9024 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009025
Alexey Bataev74caaf22016-02-20 04:09:36 +00009026 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009027 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009028 if (TopDVar.CKind == OMPC_firstprivate)
9029 Ref = TopDVar.PrivateCopy;
9030 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009031 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009032 if (!IsOpenMPCapturedDecl(D))
9033 ExprCaptures.push_back(Ref->getDecl());
9034 }
9035 if (TopDVar.CKind == OMPC_firstprivate ||
9036 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009037 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009038 ExprResult RefRes = DefaultLvalueConversion(Ref);
9039 if (!RefRes.isUsable())
9040 continue;
9041 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009042 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9043 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009044 if (!PostUpdateRes.isUsable())
9045 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009046 ExprPostUpdates.push_back(
9047 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009048 }
9049 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009050 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009051 Vars.push_back((VD || CurContext->isDependentContext())
9052 ? RefExpr->IgnoreParens()
9053 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009054 SrcExprs.push_back(PseudoSrcExpr);
9055 DstExprs.push_back(PseudoDstExpr);
9056 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009057 }
9058
9059 if (Vars.empty())
9060 return nullptr;
9061
9062 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009063 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009064 buildPreInits(Context, ExprCaptures),
9065 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009066}
9067
Alexey Bataev758e55e2013-09-06 18:03:48 +00009068OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9069 SourceLocation StartLoc,
9070 SourceLocation LParenLoc,
9071 SourceLocation EndLoc) {
9072 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009073 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009074 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009075 SourceLocation ELoc;
9076 SourceRange ERange;
9077 Expr *SimpleRefExpr = RefExpr;
9078 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009079 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009080 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009081 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009082 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009083 ValueDecl *D = Res.first;
9084 if (!D)
9085 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009086
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009087 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009088 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9089 // in a Construct]
9090 // Variables with the predetermined data-sharing attributes may not be
9091 // listed in data-sharing attributes clauses, except for the cases
9092 // listed below. For these exceptions only, listing a predetermined
9093 // variable in a data-sharing attribute clause is allowed and overrides
9094 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009095 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009096 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9097 DVar.RefExpr) {
9098 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9099 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009100 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009101 continue;
9102 }
9103
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009104 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009105 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009106 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009107 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009108 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9109 ? RefExpr->IgnoreParens()
9110 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009111 }
9112
Alexey Bataeved09d242014-05-28 05:53:51 +00009113 if (Vars.empty())
9114 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009115
9116 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9117}
9118
Alexey Bataevc5e02582014-06-16 07:08:35 +00009119namespace {
9120class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9121 DSAStackTy *Stack;
9122
9123public:
9124 bool VisitDeclRefExpr(DeclRefExpr *E) {
9125 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009126 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009127 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9128 return false;
9129 if (DVar.CKind != OMPC_unknown)
9130 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009131 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9132 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009133 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009134 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009135 return true;
9136 return false;
9137 }
9138 return false;
9139 }
9140 bool VisitStmt(Stmt *S) {
9141 for (auto Child : S->children()) {
9142 if (Child && Visit(Child))
9143 return true;
9144 }
9145 return false;
9146 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009147 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009148};
Alexey Bataev23b69422014-06-18 07:08:49 +00009149} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009150
Alexey Bataev60da77e2016-02-29 05:54:20 +00009151namespace {
9152// Transform MemberExpression for specified FieldDecl of current class to
9153// DeclRefExpr to specified OMPCapturedExprDecl.
9154class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9155 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9156 ValueDecl *Field;
9157 DeclRefExpr *CapturedExpr;
9158
9159public:
9160 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9161 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9162
9163 ExprResult TransformMemberExpr(MemberExpr *E) {
9164 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9165 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009166 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009167 return CapturedExpr;
9168 }
9169 return BaseTransform::TransformMemberExpr(E);
9170 }
9171 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9172};
9173} // namespace
9174
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009175template <typename T>
9176static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9177 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9178 for (auto &Set : Lookups) {
9179 for (auto *D : Set) {
9180 if (auto Res = Gen(cast<ValueDecl>(D)))
9181 return Res;
9182 }
9183 }
9184 return T();
9185}
9186
9187static ExprResult
9188buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9189 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9190 const DeclarationNameInfo &ReductionId, QualType Ty,
9191 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9192 if (ReductionIdScopeSpec.isInvalid())
9193 return ExprError();
9194 SmallVector<UnresolvedSet<8>, 4> Lookups;
9195 if (S) {
9196 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9197 Lookup.suppressDiagnostics();
9198 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9199 auto *D = Lookup.getRepresentativeDecl();
9200 do {
9201 S = S->getParent();
9202 } while (S && !S->isDeclScope(D));
9203 if (S)
9204 S = S->getParent();
9205 Lookups.push_back(UnresolvedSet<8>());
9206 Lookups.back().append(Lookup.begin(), Lookup.end());
9207 Lookup.clear();
9208 }
9209 } else if (auto *ULE =
9210 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9211 Lookups.push_back(UnresolvedSet<8>());
9212 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009213 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009214 if (D == PrevD)
9215 Lookups.push_back(UnresolvedSet<8>());
9216 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9217 Lookups.back().addDecl(DRD);
9218 PrevD = D;
9219 }
9220 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009221 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9222 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009223 Ty->containsUnexpandedParameterPack() ||
9224 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9225 return !D->isInvalidDecl() &&
9226 (D->getType()->isDependentType() ||
9227 D->getType()->isInstantiationDependentType() ||
9228 D->getType()->containsUnexpandedParameterPack());
9229 })) {
9230 UnresolvedSet<8> ResSet;
9231 for (auto &Set : Lookups) {
9232 ResSet.append(Set.begin(), Set.end());
9233 // The last item marks the end of all declarations at the specified scope.
9234 ResSet.addDecl(Set[Set.size() - 1]);
9235 }
9236 return UnresolvedLookupExpr::Create(
9237 SemaRef.Context, /*NamingClass=*/nullptr,
9238 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9239 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9240 }
9241 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9242 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9243 if (!D->isInvalidDecl() &&
9244 SemaRef.Context.hasSameType(D->getType(), Ty))
9245 return D;
9246 return nullptr;
9247 }))
9248 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9249 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9250 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9251 if (!D->isInvalidDecl() &&
9252 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9253 !Ty.isMoreQualifiedThan(D->getType()))
9254 return D;
9255 return nullptr;
9256 })) {
9257 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9258 /*DetectVirtual=*/false);
9259 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9260 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9261 VD->getType().getUnqualifiedType()))) {
9262 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9263 /*DiagID=*/0) !=
9264 Sema::AR_inaccessible) {
9265 SemaRef.BuildBasePathArray(Paths, BasePath);
9266 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9267 }
9268 }
9269 }
9270 }
9271 if (ReductionIdScopeSpec.isSet()) {
9272 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9273 return ExprError();
9274 }
9275 return ExprEmpty();
9276}
9277
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009278namespace {
9279/// Data for the reduction-based clauses.
9280struct ReductionData {
9281 /// List of original reduction items.
9282 SmallVector<Expr *, 8> Vars;
9283 /// List of private copies of the reduction items.
9284 SmallVector<Expr *, 8> Privates;
9285 /// LHS expressions for the reduction_op expressions.
9286 SmallVector<Expr *, 8> LHSs;
9287 /// RHS expressions for the reduction_op expressions.
9288 SmallVector<Expr *, 8> RHSs;
9289 /// Reduction operation expression.
9290 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009291 /// Taskgroup descriptors for the corresponding reduction items in
9292 /// in_reduction clauses.
9293 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009294 /// List of captures for clause.
9295 SmallVector<Decl *, 4> ExprCaptures;
9296 /// List of postupdate expressions.
9297 SmallVector<Expr *, 4> ExprPostUpdates;
9298 ReductionData() = delete;
9299 /// Reserves required memory for the reduction data.
9300 ReductionData(unsigned Size) {
9301 Vars.reserve(Size);
9302 Privates.reserve(Size);
9303 LHSs.reserve(Size);
9304 RHSs.reserve(Size);
9305 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009306 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009307 ExprCaptures.reserve(Size);
9308 ExprPostUpdates.reserve(Size);
9309 }
9310 /// Stores reduction item and reduction operation only (required for dependent
9311 /// reduction item).
9312 void push(Expr *Item, Expr *ReductionOp) {
9313 Vars.emplace_back(Item);
9314 Privates.emplace_back(nullptr);
9315 LHSs.emplace_back(nullptr);
9316 RHSs.emplace_back(nullptr);
9317 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009318 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009319 }
9320 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009321 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9322 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009323 Vars.emplace_back(Item);
9324 Privates.emplace_back(Private);
9325 LHSs.emplace_back(LHS);
9326 RHSs.emplace_back(RHS);
9327 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009328 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009329 }
9330};
9331} // namespace
9332
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009333static bool CheckOMPArraySectionConstantForReduction(
9334 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9335 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9336 const Expr *Length = OASE->getLength();
9337 if (Length == nullptr) {
9338 // For array sections of the form [1:] or [:], we would need to analyze
9339 // the lower bound...
9340 if (OASE->getColonLoc().isValid())
9341 return false;
9342
9343 // This is an array subscript which has implicit length 1!
9344 SingleElement = true;
9345 ArraySizes.push_back(llvm::APSInt::get(1));
9346 } else {
9347 llvm::APSInt ConstantLengthValue;
9348 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9349 return false;
9350
9351 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9352 ArraySizes.push_back(ConstantLengthValue);
9353 }
9354
9355 // Get the base of this array section and walk up from there.
9356 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9357
9358 // We require length = 1 for all array sections except the right-most to
9359 // guarantee that the memory region is contiguous and has no holes in it.
9360 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9361 Length = TempOASE->getLength();
9362 if (Length == nullptr) {
9363 // For array sections of the form [1:] or [:], we would need to analyze
9364 // the lower bound...
9365 if (OASE->getColonLoc().isValid())
9366 return false;
9367
9368 // This is an array subscript which has implicit length 1!
9369 ArraySizes.push_back(llvm::APSInt::get(1));
9370 } else {
9371 llvm::APSInt ConstantLengthValue;
9372 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9373 ConstantLengthValue.getSExtValue() != 1)
9374 return false;
9375
9376 ArraySizes.push_back(ConstantLengthValue);
9377 }
9378 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9379 }
9380
9381 // If we have a single element, we don't need to add the implicit lengths.
9382 if (!SingleElement) {
9383 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9384 // Has implicit length 1!
9385 ArraySizes.push_back(llvm::APSInt::get(1));
9386 Base = TempASE->getBase()->IgnoreParenImpCasts();
9387 }
9388 }
9389
9390 // This array section can be privatized as a single value or as a constant
9391 // sized array.
9392 return true;
9393}
9394
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009395static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009396 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9397 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9398 SourceLocation ColonLoc, SourceLocation EndLoc,
9399 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009400 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009401 auto DN = ReductionId.getName();
9402 auto OOK = DN.getCXXOverloadedOperator();
9403 BinaryOperatorKind BOK = BO_Comma;
9404
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009405 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009406 // OpenMP [2.14.3.6, reduction clause]
9407 // C
9408 // reduction-identifier is either an identifier or one of the following
9409 // operators: +, -, *, &, |, ^, && and ||
9410 // C++
9411 // reduction-identifier is either an id-expression or one of the following
9412 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009413 switch (OOK) {
9414 case OO_Plus:
9415 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009416 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009417 break;
9418 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009419 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009420 break;
9421 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009422 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009423 break;
9424 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009425 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009426 break;
9427 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009428 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009429 break;
9430 case OO_AmpAmp:
9431 BOK = BO_LAnd;
9432 break;
9433 case OO_PipePipe:
9434 BOK = BO_LOr;
9435 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009436 case OO_New:
9437 case OO_Delete:
9438 case OO_Array_New:
9439 case OO_Array_Delete:
9440 case OO_Slash:
9441 case OO_Percent:
9442 case OO_Tilde:
9443 case OO_Exclaim:
9444 case OO_Equal:
9445 case OO_Less:
9446 case OO_Greater:
9447 case OO_LessEqual:
9448 case OO_GreaterEqual:
9449 case OO_PlusEqual:
9450 case OO_MinusEqual:
9451 case OO_StarEqual:
9452 case OO_SlashEqual:
9453 case OO_PercentEqual:
9454 case OO_CaretEqual:
9455 case OO_AmpEqual:
9456 case OO_PipeEqual:
9457 case OO_LessLess:
9458 case OO_GreaterGreater:
9459 case OO_LessLessEqual:
9460 case OO_GreaterGreaterEqual:
9461 case OO_EqualEqual:
9462 case OO_ExclaimEqual:
9463 case OO_PlusPlus:
9464 case OO_MinusMinus:
9465 case OO_Comma:
9466 case OO_ArrowStar:
9467 case OO_Arrow:
9468 case OO_Call:
9469 case OO_Subscript:
9470 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009471 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009472 case NUM_OVERLOADED_OPERATORS:
9473 llvm_unreachable("Unexpected reduction identifier");
9474 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009475 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009476 if (II->isStr("max"))
9477 BOK = BO_GT;
9478 else if (II->isStr("min"))
9479 BOK = BO_LT;
9480 }
9481 break;
9482 }
9483 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009484 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009485 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009486 else
9487 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009488 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009489
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009490 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9491 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009492 for (auto RefExpr : VarList) {
9493 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009494 // OpenMP [2.1, C/C++]
9495 // A list item is a variable or array section, subject to the restrictions
9496 // specified in Section 2.4 on page 42 and in each of the sections
9497 // describing clauses and directives for which a list appears.
9498 // OpenMP [2.14.3.3, Restrictions, p.1]
9499 // A variable that is part of another variable (as an array or
9500 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009501 if (!FirstIter && IR != ER)
9502 ++IR;
9503 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009504 SourceLocation ELoc;
9505 SourceRange ERange;
9506 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009507 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009508 /*AllowArraySection=*/true);
9509 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009510 // Try to find 'declare reduction' corresponding construct before using
9511 // builtin/overloaded operators.
9512 QualType Type = Context.DependentTy;
9513 CXXCastPath BasePath;
9514 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009515 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009516 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009517 Expr *ReductionOp = nullptr;
9518 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009519 (DeclareReductionRef.isUnset() ||
9520 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009521 ReductionOp = DeclareReductionRef.get();
9522 // It will be analyzed later.
9523 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009524 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009525 ValueDecl *D = Res.first;
9526 if (!D)
9527 continue;
9528
Alexey Bataev88202be2017-07-27 13:20:36 +00009529 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009530 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009531 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9532 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9533 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009534 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009535 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009536 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9537 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9538 Type = ATy->getElementType();
9539 else
9540 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009541 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009542 } else
9543 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9544 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009545
Alexey Bataevc5e02582014-06-16 07:08:35 +00009546 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9547 // A variable that appears in a private clause must not have an incomplete
9548 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009549 if (S.RequireCompleteType(ELoc, Type,
9550 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009551 continue;
9552 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009553 // A list item that appears in a reduction clause must not be
9554 // const-qualified.
9555 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009556 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009557 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009558 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9559 VarDecl::DeclarationOnly;
9560 S.Diag(D->getLocation(),
9561 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009562 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009563 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009564 continue;
9565 }
9566 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9567 // If a list-item is a reference type then it must bind to the same object
9568 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009569 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009570 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009571 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009572 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009573 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009574 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9575 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009576 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009577 continue;
9578 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009579 }
9580 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009581
Alexey Bataevc5e02582014-06-16 07:08:35 +00009582 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9583 // in a Construct]
9584 // Variables with the predetermined data-sharing attributes may not be
9585 // listed in data-sharing attributes clauses, except for the cases
9586 // listed below. For these exceptions only, listing a predetermined
9587 // variable in a data-sharing attribute clause is allowed and overrides
9588 // the variable's predetermined data-sharing attributes.
9589 // OpenMP [2.14.3.6, Restrictions, p.3]
9590 // Any number of reduction clauses can be specified on the directive,
9591 // but a list item can appear only once in the reduction clauses for that
9592 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009593 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009594 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009595 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009596 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009597 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009598 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009599 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009600 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009601 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009602 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009603 << getOpenMPClauseName(DVar.CKind)
9604 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009605 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009606 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009607 }
9608
9609 // OpenMP [2.14.3.6, Restrictions, p.1]
9610 // A list item that appears in a reduction clause of a worksharing
9611 // construct must be shared in the parallel regions to which any of the
9612 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009613 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009614 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009615 !isOpenMPParallelDirective(CurrDir) &&
9616 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009617 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009618 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009619 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009620 << getOpenMPClauseName(OMPC_reduction)
9621 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009622 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009623 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009624 }
9625 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009626
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009627 // Try to find 'declare reduction' corresponding construct before using
9628 // builtin/overloaded operators.
9629 CXXCastPath BasePath;
9630 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009631 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009632 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9633 if (DeclareReductionRef.isInvalid())
9634 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009635 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009636 (DeclareReductionRef.isUnset() ||
9637 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009638 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009639 continue;
9640 }
9641 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9642 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009643 S.Diag(ReductionId.getLocStart(),
9644 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009645 << Type << ReductionIdRange;
9646 continue;
9647 }
9648
9649 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9650 // The type of a list item that appears in a reduction clause must be valid
9651 // for the reduction-identifier. For a max or min reduction in C, the type
9652 // of the list item must be an allowed arithmetic data type: char, int,
9653 // float, double, or _Bool, possibly modified with long, short, signed, or
9654 // unsigned. For a max or min reduction in C++, the type of the list item
9655 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9656 // double, or bool, possibly modified with long, short, signed, or unsigned.
9657 if (DeclareReductionRef.isUnset()) {
9658 if ((BOK == BO_GT || BOK == BO_LT) &&
9659 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009660 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9661 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009662 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009663 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009664 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9665 VarDecl::DeclarationOnly;
9666 S.Diag(D->getLocation(),
9667 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009668 << D;
9669 }
9670 continue;
9671 }
9672 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009673 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009674 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9675 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009676 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009677 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9678 VarDecl::DeclarationOnly;
9679 S.Diag(D->getLocation(),
9680 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009681 << D;
9682 }
9683 continue;
9684 }
9685 }
9686
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009687 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009688 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009689 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009690 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009691 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009692 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009693
9694 // Try if we can determine constant lengths for all array sections and avoid
9695 // the VLA.
9696 bool ConstantLengthOASE = false;
9697 if (OASE) {
9698 bool SingleElement;
9699 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
9700 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
9701 Context, OASE, SingleElement, ArraySizes);
9702
9703 // If we don't have a single element, we must emit a constant array type.
9704 if (ConstantLengthOASE && !SingleElement) {
9705 for (auto &Size : ArraySizes) {
9706 PrivateTy = Context.getConstantArrayType(
9707 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
9708 }
9709 }
9710 }
9711
9712 if ((OASE && !ConstantLengthOASE) ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009713 (!ASE &&
9714 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009715 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009716 // Create pseudo array type for private copy. The size for this array will
9717 // be generated during codegen.
9718 // For array subscripts or single variables Private Ty is the same as Type
9719 // (type of the variable or single array element).
9720 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009721 Type,
9722 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9723 VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009724 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009725 } else if (!ASE && !OASE &&
9726 Context.getAsArrayType(D->getType().getNonReferenceType()))
9727 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009728 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009729 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009730 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009731 // Add initializer for private variable.
9732 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009733 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9734 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009735 if (DeclareReductionRef.isUsable()) {
9736 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9737 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9738 if (DRD->getInitializer()) {
9739 Init = DRDRef;
9740 RHSVD->setInit(DRDRef);
9741 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009742 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009743 } else {
9744 switch (BOK) {
9745 case BO_Add:
9746 case BO_Xor:
9747 case BO_Or:
9748 case BO_LOr:
9749 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9750 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009751 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009752 break;
9753 case BO_Mul:
9754 case BO_LAnd:
9755 if (Type->isScalarType() || Type->isAnyComplexType()) {
9756 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009757 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009758 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009759 break;
9760 case BO_And: {
9761 // '&' reduction op - initializer is '~0'.
9762 QualType OrigType = Type;
9763 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9764 Type = ComplexTy->getElementType();
9765 if (Type->isRealFloatingType()) {
9766 llvm::APFloat InitValue =
9767 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9768 /*isIEEE=*/true);
9769 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9770 Type, ELoc);
9771 } else if (Type->isScalarType()) {
9772 auto Size = Context.getTypeSize(Type);
9773 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9774 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9775 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9776 }
9777 if (Init && OrigType->isAnyComplexType()) {
9778 // Init = 0xFFFF + 0xFFFFi;
9779 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009780 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009781 }
9782 Type = OrigType;
9783 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009784 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009785 case BO_LT:
9786 case BO_GT: {
9787 // 'min' reduction op - initializer is 'Largest representable number in
9788 // the reduction list item type'.
9789 // 'max' reduction op - initializer is 'Least representable number in
9790 // the reduction list item type'.
9791 if (Type->isIntegerType() || Type->isPointerType()) {
9792 bool IsSigned = Type->hasSignedIntegerRepresentation();
9793 auto Size = Context.getTypeSize(Type);
9794 QualType IntTy =
9795 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9796 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009797 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9798 : llvm::APInt::getMinValue(Size)
9799 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9800 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009801 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9802 if (Type->isPointerType()) {
9803 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009804 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009805 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9806 SourceLocation(), Init);
9807 if (CastExpr.isInvalid())
9808 continue;
9809 Init = CastExpr.get();
9810 }
9811 } else if (Type->isRealFloatingType()) {
9812 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9813 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9814 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9815 Type, ELoc);
9816 }
9817 break;
9818 }
9819 case BO_PtrMemD:
9820 case BO_PtrMemI:
9821 case BO_MulAssign:
9822 case BO_Div:
9823 case BO_Rem:
9824 case BO_Sub:
9825 case BO_Shl:
9826 case BO_Shr:
9827 case BO_LE:
9828 case BO_GE:
9829 case BO_EQ:
9830 case BO_NE:
9831 case BO_AndAssign:
9832 case BO_XorAssign:
9833 case BO_OrAssign:
9834 case BO_Assign:
9835 case BO_AddAssign:
9836 case BO_SubAssign:
9837 case BO_DivAssign:
9838 case BO_RemAssign:
9839 case BO_ShlAssign:
9840 case BO_ShrAssign:
9841 case BO_Comma:
9842 llvm_unreachable("Unexpected reduction operation");
9843 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009844 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009845 if (Init && DeclareReductionRef.isUnset())
9846 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9847 else if (!Init)
9848 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009849 if (RHSVD->isInvalidDecl())
9850 continue;
9851 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009852 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9853 << Type << ReductionIdRange;
9854 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9855 VarDecl::DeclarationOnly;
9856 S.Diag(D->getLocation(),
9857 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009858 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009859 continue;
9860 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009861 // Store initializer for single element in private copy. Will be used during
9862 // codegen.
9863 PrivateVD->setInit(RHSVD->getInit());
9864 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009865 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009866 ExprResult ReductionOp;
9867 if (DeclareReductionRef.isUsable()) {
9868 QualType RedTy = DeclareReductionRef.get()->getType();
9869 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009870 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9871 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009872 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009873 LHS = S.DefaultLvalueConversion(LHS.get());
9874 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009875 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9876 CK_UncheckedDerivedToBase, LHS.get(),
9877 &BasePath, LHS.get()->getValueKind());
9878 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9879 CK_UncheckedDerivedToBase, RHS.get(),
9880 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009881 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009882 FunctionProtoType::ExtProtoInfo EPI;
9883 QualType Params[] = {PtrRedTy, PtrRedTy};
9884 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9885 auto *OVE = new (Context) OpaqueValueExpr(
9886 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009887 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009888 Expr *Args[] = {LHS.get(), RHS.get()};
9889 ReductionOp = new (Context)
9890 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9891 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009892 ReductionOp = S.BuildBinOp(
9893 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009894 if (ReductionOp.isUsable()) {
9895 if (BOK != BO_LT && BOK != BO_GT) {
9896 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009897 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9898 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009899 } else {
9900 auto *ConditionalOp = new (Context) ConditionalOperator(
9901 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9902 RHSDRE, Type, VK_LValue, OK_Ordinary);
9903 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009904 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9905 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009906 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009907 if (ReductionOp.isUsable())
9908 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009909 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009910 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009911 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009912 }
9913
Alexey Bataevfa312f32017-07-21 18:48:21 +00009914 // OpenMP [2.15.4.6, Restrictions, p.2]
9915 // A list item that appears in an in_reduction clause of a task construct
9916 // must appear in a task_reduction clause of a construct associated with a
9917 // taskgroup region that includes the participating task in its taskgroup
9918 // set. The construct associated with the innermost region that meets this
9919 // condition must specify the same reduction-identifier as the in_reduction
9920 // clause.
9921 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00009922 SourceRange ParentSR;
9923 BinaryOperatorKind ParentBOK;
9924 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +00009925 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +00009926 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009927 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
9928 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009929 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009930 Stack->getTopMostTaskgroupReductionData(
9931 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009932 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
9933 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
9934 if (!IsParentBOK && !IsParentReductionOp) {
9935 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
9936 continue;
9937 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00009938 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
9939 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
9940 IsParentReductionOp) {
9941 bool EmitError = true;
9942 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
9943 llvm::FoldingSetNodeID RedId, ParentRedId;
9944 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
9945 DeclareReductionRef.get()->Profile(RedId, Context,
9946 /*Canonical=*/true);
9947 EmitError = RedId != ParentRedId;
9948 }
9949 if (EmitError) {
9950 S.Diag(ReductionId.getLocStart(),
9951 diag::err_omp_reduction_identifier_mismatch)
9952 << ReductionIdRange << RefExpr->getSourceRange();
9953 S.Diag(ParentSR.getBegin(),
9954 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +00009955 << ParentSR
9956 << (IsParentBOK ? ParentBOKDSA.RefExpr
9957 : ParentReductionOpDSA.RefExpr)
9958 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +00009959 continue;
9960 }
9961 }
Alexey Bataev88202be2017-07-27 13:20:36 +00009962 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
9963 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +00009964 }
9965
Alexey Bataev60da77e2016-02-29 05:54:20 +00009966 DeclRefExpr *Ref = nullptr;
9967 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009968 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009969 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009970 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009971 VarsExpr =
9972 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9973 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009974 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009975 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009976 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009977 if (!S.IsOpenMPCapturedDecl(D)) {
9978 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009979 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009980 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009981 if (!RefRes.isUsable())
9982 continue;
9983 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009984 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9985 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009986 if (!PostUpdateRes.isUsable())
9987 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009988 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9989 Stack->getCurrentDirective() == OMPD_taskgroup) {
9990 S.Diag(RefExpr->getExprLoc(),
9991 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009992 << RefExpr->getSourceRange();
9993 continue;
9994 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009995 RD.ExprPostUpdates.emplace_back(
9996 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009997 }
9998 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009999 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010000 // All reduction items are still marked as reduction (to do not increase
10001 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010002 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010003 if (CurrDir == OMPD_taskgroup) {
10004 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010005 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10006 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010007 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010008 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010009 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010010 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10011 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010012 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010013 return RD.Vars.empty();
10014}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010015
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010016OMPClause *Sema::ActOnOpenMPReductionClause(
10017 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10018 SourceLocation ColonLoc, SourceLocation EndLoc,
10019 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10020 ArrayRef<Expr *> UnresolvedReductions) {
10021 ReductionData RD(VarList.size());
10022
Alexey Bataev169d96a2017-07-18 20:17:46 +000010023 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10024 StartLoc, LParenLoc, ColonLoc, EndLoc,
10025 ReductionIdScopeSpec, ReductionId,
10026 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010027 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010028
Alexey Bataevc5e02582014-06-16 07:08:35 +000010029 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010030 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10031 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10032 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10033 buildPreInits(Context, RD.ExprCaptures),
10034 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010035}
10036
Alexey Bataev169d96a2017-07-18 20:17:46 +000010037OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10038 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10039 SourceLocation ColonLoc, SourceLocation EndLoc,
10040 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10041 ArrayRef<Expr *> UnresolvedReductions) {
10042 ReductionData RD(VarList.size());
10043
10044 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10045 VarList, StartLoc, LParenLoc, ColonLoc,
10046 EndLoc, ReductionIdScopeSpec, ReductionId,
10047 UnresolvedReductions, RD))
10048 return nullptr;
10049
10050 return OMPTaskReductionClause::Create(
10051 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10052 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10053 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10054 buildPreInits(Context, RD.ExprCaptures),
10055 buildPostUpdate(*this, RD.ExprPostUpdates));
10056}
10057
Alexey Bataevfa312f32017-07-21 18:48:21 +000010058OMPClause *Sema::ActOnOpenMPInReductionClause(
10059 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10060 SourceLocation ColonLoc, SourceLocation EndLoc,
10061 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10062 ArrayRef<Expr *> UnresolvedReductions) {
10063 ReductionData RD(VarList.size());
10064
10065 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10066 StartLoc, LParenLoc, ColonLoc, EndLoc,
10067 ReductionIdScopeSpec, ReductionId,
10068 UnresolvedReductions, RD))
10069 return nullptr;
10070
10071 return OMPInReductionClause::Create(
10072 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10073 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010074 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010075 buildPreInits(Context, RD.ExprCaptures),
10076 buildPostUpdate(*this, RD.ExprPostUpdates));
10077}
10078
Alexey Bataevecba70f2016-04-12 11:02:11 +000010079bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10080 SourceLocation LinLoc) {
10081 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10082 LinKind == OMPC_LINEAR_unknown) {
10083 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10084 return true;
10085 }
10086 return false;
10087}
10088
10089bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10090 OpenMPLinearClauseKind LinKind,
10091 QualType Type) {
10092 auto *VD = dyn_cast_or_null<VarDecl>(D);
10093 // A variable must not have an incomplete type or a reference type.
10094 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10095 return true;
10096 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10097 !Type->isReferenceType()) {
10098 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10099 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10100 return true;
10101 }
10102 Type = Type.getNonReferenceType();
10103
10104 // A list item must not be const-qualified.
10105 if (Type.isConstant(Context)) {
10106 Diag(ELoc, diag::err_omp_const_variable)
10107 << getOpenMPClauseName(OMPC_linear);
10108 if (D) {
10109 bool IsDecl =
10110 !VD ||
10111 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10112 Diag(D->getLocation(),
10113 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10114 << D;
10115 }
10116 return true;
10117 }
10118
10119 // A list item must be of integral or pointer type.
10120 Type = Type.getUnqualifiedType().getCanonicalType();
10121 const auto *Ty = Type.getTypePtrOrNull();
10122 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10123 !Ty->isPointerType())) {
10124 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10125 if (D) {
10126 bool IsDecl =
10127 !VD ||
10128 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10129 Diag(D->getLocation(),
10130 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10131 << D;
10132 }
10133 return true;
10134 }
10135 return false;
10136}
10137
Alexey Bataev182227b2015-08-20 10:54:39 +000010138OMPClause *Sema::ActOnOpenMPLinearClause(
10139 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10140 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10141 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010142 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010143 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010144 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010145 SmallVector<Decl *, 4> ExprCaptures;
10146 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010147 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010148 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010149 for (auto &RefExpr : VarList) {
10150 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010151 SourceLocation ELoc;
10152 SourceRange ERange;
10153 Expr *SimpleRefExpr = RefExpr;
10154 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10155 /*AllowArraySection=*/false);
10156 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010157 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010158 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010159 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010160 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010161 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010162 ValueDecl *D = Res.first;
10163 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010164 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010165
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010166 QualType Type = D->getType();
10167 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010168
10169 // OpenMP [2.14.3.7, linear clause]
10170 // A list-item cannot appear in more than one linear clause.
10171 // A list-item that appears in a linear clause cannot appear in any
10172 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010173 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010174 if (DVar.RefExpr) {
10175 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10176 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010177 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010178 continue;
10179 }
10180
Alexey Bataevecba70f2016-04-12 11:02:11 +000010181 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010182 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010183 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010184
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010185 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010186 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10187 D->hasAttrs() ? &D->getAttrs() : nullptr);
10188 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010189 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010190 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010191 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010192 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010193 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010194 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10195 if (!IsOpenMPCapturedDecl(D)) {
10196 ExprCaptures.push_back(Ref->getDecl());
10197 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10198 ExprResult RefRes = DefaultLvalueConversion(Ref);
10199 if (!RefRes.isUsable())
10200 continue;
10201 ExprResult PostUpdateRes =
10202 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10203 SimpleRefExpr, RefRes.get());
10204 if (!PostUpdateRes.isUsable())
10205 continue;
10206 ExprPostUpdates.push_back(
10207 IgnoredValueConversions(PostUpdateRes.get()).get());
10208 }
10209 }
10210 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010211 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010212 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010213 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010214 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010215 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010216 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010217 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10218
10219 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010220 Vars.push_back((VD || CurContext->isDependentContext())
10221 ? RefExpr->IgnoreParens()
10222 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010223 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010224 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010225 }
10226
10227 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010228 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010229
10230 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010231 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010232 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10233 !Step->isInstantiationDependent() &&
10234 !Step->containsUnexpandedParameterPack()) {
10235 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010236 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010237 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010238 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010239 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010240
Alexander Musman3276a272015-03-21 10:12:56 +000010241 // Build var to save the step value.
10242 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010243 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010244 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010245 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010246 ExprResult CalcStep =
10247 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010248 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010249
Alexander Musman8dba6642014-04-22 13:09:42 +000010250 // Warn about zero linear step (it would be probably better specified as
10251 // making corresponding variables 'const').
10252 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010253 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10254 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010255 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10256 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010257 if (!IsConstant && CalcStep.isUsable()) {
10258 // Calculate the step beforehand instead of doing this on each iteration.
10259 // (This is not used if the number of iterations may be kfold-ed).
10260 CalcStepExpr = CalcStep.get();
10261 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010262 }
10263
Alexey Bataev182227b2015-08-20 10:54:39 +000010264 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10265 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010266 StepExpr, CalcStepExpr,
10267 buildPreInits(Context, ExprCaptures),
10268 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010269}
10270
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010271static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10272 Expr *NumIterations, Sema &SemaRef,
10273 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010274 // Walk the vars and build update/final expressions for the CodeGen.
10275 SmallVector<Expr *, 8> Updates;
10276 SmallVector<Expr *, 8> Finals;
10277 Expr *Step = Clause.getStep();
10278 Expr *CalcStep = Clause.getCalcStep();
10279 // OpenMP [2.14.3.7, linear clause]
10280 // If linear-step is not specified it is assumed to be 1.
10281 if (Step == nullptr)
10282 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010283 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010284 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010285 }
Alexander Musman3276a272015-03-21 10:12:56 +000010286 bool HasErrors = false;
10287 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010288 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010289 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010290 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010291 SourceLocation ELoc;
10292 SourceRange ERange;
10293 Expr *SimpleRefExpr = RefExpr;
10294 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10295 /*AllowArraySection=*/false);
10296 ValueDecl *D = Res.first;
10297 if (Res.second || !D) {
10298 Updates.push_back(nullptr);
10299 Finals.push_back(nullptr);
10300 HasErrors = true;
10301 continue;
10302 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010303 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010304 Expr *InitExpr = *CurInit;
10305
10306 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010307 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010308 Expr *CapturedRef;
10309 if (LinKind == OMPC_LINEAR_uval)
10310 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10311 else
10312 CapturedRef =
10313 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10314 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10315 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010316
10317 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010318 ExprResult Update;
10319 if (!Info.first) {
10320 Update =
10321 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10322 InitExpr, IV, Step, /* Subtract */ false);
10323 } else
10324 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010325 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10326 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010327
10328 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010329 ExprResult Final;
10330 if (!Info.first) {
10331 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10332 InitExpr, NumIterations, Step,
10333 /* Subtract */ false);
10334 } else
10335 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010336 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10337 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010338
Alexander Musman3276a272015-03-21 10:12:56 +000010339 if (!Update.isUsable() || !Final.isUsable()) {
10340 Updates.push_back(nullptr);
10341 Finals.push_back(nullptr);
10342 HasErrors = true;
10343 } else {
10344 Updates.push_back(Update.get());
10345 Finals.push_back(Final.get());
10346 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010347 ++CurInit;
10348 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010349 }
10350 Clause.setUpdates(Updates);
10351 Clause.setFinals(Finals);
10352 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010353}
10354
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010355OMPClause *Sema::ActOnOpenMPAlignedClause(
10356 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10357 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10358
10359 SmallVector<Expr *, 8> Vars;
10360 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010361 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10362 SourceLocation ELoc;
10363 SourceRange ERange;
10364 Expr *SimpleRefExpr = RefExpr;
10365 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10366 /*AllowArraySection=*/false);
10367 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010368 // It will be analyzed later.
10369 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010370 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010371 ValueDecl *D = Res.first;
10372 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010373 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010374
Alexey Bataev1efd1662016-03-29 10:59:56 +000010375 QualType QType = D->getType();
10376 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010377
10378 // OpenMP [2.8.1, simd construct, Restrictions]
10379 // The type of list items appearing in the aligned clause must be
10380 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010381 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010382 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010383 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010384 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010385 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010386 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010387 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010388 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010389 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010390 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010391 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010392 continue;
10393 }
10394
10395 // OpenMP [2.8.1, simd construct, Restrictions]
10396 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010397 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010398 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010399 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10400 << getOpenMPClauseName(OMPC_aligned);
10401 continue;
10402 }
10403
Alexey Bataev1efd1662016-03-29 10:59:56 +000010404 DeclRefExpr *Ref = nullptr;
10405 if (!VD && IsOpenMPCapturedDecl(D))
10406 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10407 Vars.push_back(DefaultFunctionArrayConversion(
10408 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10409 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010410 }
10411
10412 // OpenMP [2.8.1, simd construct, Description]
10413 // The parameter of the aligned clause, alignment, must be a constant
10414 // positive integer expression.
10415 // If no optional parameter is specified, implementation-defined default
10416 // alignments for SIMD instructions on the target platforms are assumed.
10417 if (Alignment != nullptr) {
10418 ExprResult AlignResult =
10419 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10420 if (AlignResult.isInvalid())
10421 return nullptr;
10422 Alignment = AlignResult.get();
10423 }
10424 if (Vars.empty())
10425 return nullptr;
10426
10427 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10428 EndLoc, Vars, Alignment);
10429}
10430
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010431OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10432 SourceLocation StartLoc,
10433 SourceLocation LParenLoc,
10434 SourceLocation EndLoc) {
10435 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010436 SmallVector<Expr *, 8> SrcExprs;
10437 SmallVector<Expr *, 8> DstExprs;
10438 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010439 for (auto &RefExpr : VarList) {
10440 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10441 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010442 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010443 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010444 SrcExprs.push_back(nullptr);
10445 DstExprs.push_back(nullptr);
10446 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010447 continue;
10448 }
10449
Alexey Bataeved09d242014-05-28 05:53:51 +000010450 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010451 // OpenMP [2.1, C/C++]
10452 // A list item is a variable name.
10453 // OpenMP [2.14.4.1, Restrictions, p.1]
10454 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010455 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010456 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010457 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10458 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010459 continue;
10460 }
10461
10462 Decl *D = DE->getDecl();
10463 VarDecl *VD = cast<VarDecl>(D);
10464
10465 QualType Type = VD->getType();
10466 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10467 // It will be analyzed later.
10468 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010469 SrcExprs.push_back(nullptr);
10470 DstExprs.push_back(nullptr);
10471 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010472 continue;
10473 }
10474
10475 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10476 // A list item that appears in a copyin clause must be threadprivate.
10477 if (!DSAStack->isThreadPrivate(VD)) {
10478 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010479 << getOpenMPClauseName(OMPC_copyin)
10480 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010481 continue;
10482 }
10483
10484 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10485 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010486 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010487 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010488 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010489 auto *SrcVD =
10490 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10491 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010492 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010493 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10494 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010495 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10496 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010497 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010498 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010499 // For arrays generate assignment operation for single element and replace
10500 // it by the original array element in CodeGen.
10501 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10502 PseudoDstExpr, PseudoSrcExpr);
10503 if (AssignmentOp.isInvalid())
10504 continue;
10505 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10506 /*DiscardedValue=*/true);
10507 if (AssignmentOp.isInvalid())
10508 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010509
10510 DSAStack->addDSA(VD, DE, OMPC_copyin);
10511 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010512 SrcExprs.push_back(PseudoSrcExpr);
10513 DstExprs.push_back(PseudoDstExpr);
10514 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010515 }
10516
Alexey Bataeved09d242014-05-28 05:53:51 +000010517 if (Vars.empty())
10518 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010519
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010520 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10521 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010522}
10523
Alexey Bataevbae9a792014-06-27 10:37:06 +000010524OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10525 SourceLocation StartLoc,
10526 SourceLocation LParenLoc,
10527 SourceLocation EndLoc) {
10528 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010529 SmallVector<Expr *, 8> SrcExprs;
10530 SmallVector<Expr *, 8> DstExprs;
10531 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010532 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010533 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10534 SourceLocation ELoc;
10535 SourceRange ERange;
10536 Expr *SimpleRefExpr = RefExpr;
10537 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10538 /*AllowArraySection=*/false);
10539 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010540 // It will be analyzed later.
10541 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010542 SrcExprs.push_back(nullptr);
10543 DstExprs.push_back(nullptr);
10544 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010545 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010546 ValueDecl *D = Res.first;
10547 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010548 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010549
Alexey Bataeve122da12016-03-17 10:50:17 +000010550 QualType Type = D->getType();
10551 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010552
10553 // OpenMP [2.14.4.2, Restrictions, p.2]
10554 // A list item that appears in a copyprivate clause may not appear in a
10555 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010556 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10557 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010558 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10559 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010560 Diag(ELoc, diag::err_omp_wrong_dsa)
10561 << getOpenMPClauseName(DVar.CKind)
10562 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010563 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010564 continue;
10565 }
10566
10567 // OpenMP [2.11.4.2, Restrictions, p.1]
10568 // All list items that appear in a copyprivate clause must be either
10569 // threadprivate or private in the enclosing context.
10570 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010571 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010572 if (DVar.CKind == OMPC_shared) {
10573 Diag(ELoc, diag::err_omp_required_access)
10574 << getOpenMPClauseName(OMPC_copyprivate)
10575 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010576 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010577 continue;
10578 }
10579 }
10580 }
10581
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010582 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010583 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010584 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010585 << getOpenMPClauseName(OMPC_copyprivate) << Type
10586 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010587 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010588 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010589 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010590 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010591 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010592 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010593 continue;
10594 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010595
Alexey Bataevbae9a792014-06-27 10:37:06 +000010596 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10597 // A variable of class type (or array thereof) that appears in a
10598 // copyin clause requires an accessible, unambiguous copy assignment
10599 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010600 Type = Context.getBaseElementType(Type.getNonReferenceType())
10601 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010602 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010603 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10604 D->hasAttrs() ? &D->getAttrs() : nullptr);
10605 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010606 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010607 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10608 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010609 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010610 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010611 PseudoDstExpr, PseudoSrcExpr);
10612 if (AssignmentOp.isInvalid())
10613 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010614 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010615 /*DiscardedValue=*/true);
10616 if (AssignmentOp.isInvalid())
10617 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010618
10619 // No need to mark vars as copyprivate, they are already threadprivate or
10620 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010621 assert(VD || IsOpenMPCapturedDecl(D));
10622 Vars.push_back(
10623 VD ? RefExpr->IgnoreParens()
10624 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010625 SrcExprs.push_back(PseudoSrcExpr);
10626 DstExprs.push_back(PseudoDstExpr);
10627 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010628 }
10629
10630 if (Vars.empty())
10631 return nullptr;
10632
Alexey Bataeva63048e2015-03-23 06:18:07 +000010633 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10634 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010635}
10636
Alexey Bataev6125da92014-07-21 11:26:11 +000010637OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10638 SourceLocation StartLoc,
10639 SourceLocation LParenLoc,
10640 SourceLocation EndLoc) {
10641 if (VarList.empty())
10642 return nullptr;
10643
10644 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10645}
Alexey Bataevdea47612014-07-23 07:46:59 +000010646
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010647OMPClause *
10648Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10649 SourceLocation DepLoc, SourceLocation ColonLoc,
10650 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10651 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010652 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010653 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010654 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010655 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010656 return nullptr;
10657 }
10658 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010659 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10660 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010661 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010662 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010663 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10664 /*Last=*/OMPC_DEPEND_unknown, Except)
10665 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010666 return nullptr;
10667 }
10668 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010669 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010670 llvm::APSInt DepCounter(/*BitWidth=*/32);
10671 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10672 if (DepKind == OMPC_DEPEND_sink) {
10673 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10674 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10675 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010676 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010677 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010678 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10679 DSAStack->getParentOrderedRegionParam()) {
10680 for (auto &RefExpr : VarList) {
10681 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010682 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010683 // It will be analyzed later.
10684 Vars.push_back(RefExpr);
10685 continue;
10686 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010687
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010688 SourceLocation ELoc = RefExpr->getExprLoc();
10689 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10690 if (DepKind == OMPC_DEPEND_sink) {
10691 if (DepCounter >= TotalDepCount) {
10692 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10693 continue;
10694 }
10695 ++DepCounter;
10696 // OpenMP [2.13.9, Summary]
10697 // depend(dependence-type : vec), where dependence-type is:
10698 // 'sink' and where vec is the iteration vector, which has the form:
10699 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10700 // where n is the value specified by the ordered clause in the loop
10701 // directive, xi denotes the loop iteration variable of the i-th nested
10702 // loop associated with the loop directive, and di is a constant
10703 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010704 if (CurContext->isDependentContext()) {
10705 // It will be analyzed later.
10706 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010707 continue;
10708 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010709 SimpleExpr = SimpleExpr->IgnoreImplicit();
10710 OverloadedOperatorKind OOK = OO_None;
10711 SourceLocation OOLoc;
10712 Expr *LHS = SimpleExpr;
10713 Expr *RHS = nullptr;
10714 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10715 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10716 OOLoc = BO->getOperatorLoc();
10717 LHS = BO->getLHS()->IgnoreParenImpCasts();
10718 RHS = BO->getRHS()->IgnoreParenImpCasts();
10719 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10720 OOK = OCE->getOperator();
10721 OOLoc = OCE->getOperatorLoc();
10722 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10723 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10724 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10725 OOK = MCE->getMethodDecl()
10726 ->getNameInfo()
10727 .getName()
10728 .getCXXOverloadedOperator();
10729 OOLoc = MCE->getCallee()->getExprLoc();
10730 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10731 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10732 }
10733 SourceLocation ELoc;
10734 SourceRange ERange;
10735 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10736 /*AllowArraySection=*/false);
10737 if (Res.second) {
10738 // It will be analyzed later.
10739 Vars.push_back(RefExpr);
10740 }
10741 ValueDecl *D = Res.first;
10742 if (!D)
10743 continue;
10744
10745 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10746 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10747 continue;
10748 }
10749 if (RHS) {
10750 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10751 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10752 if (RHSRes.isInvalid())
10753 continue;
10754 }
10755 if (!CurContext->isDependentContext() &&
10756 DSAStack->getParentOrderedRegionParam() &&
10757 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000010758 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
10759 DepCounter.getZExtValue());
10760 if (VD) {
10761 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10762 << 1 << VD;
10763 } else {
10764 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
10765 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010766 continue;
10767 }
10768 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010769 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010770 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010771 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010772 (ASE &&
10773 !ASE->getBase()
10774 ->getType()
10775 .getNonReferenceType()
10776 ->isPointerType() &&
10777 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010778 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10779 << RefExpr->getSourceRange();
10780 continue;
10781 }
10782 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
10783 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
10784 ExprResult Res = CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf,
10785 RefExpr->IgnoreParenImpCasts());
10786 getDiagnostics().setSuppressAllDiagnostics(Suppress);
10787 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
10788 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10789 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010790 continue;
10791 }
10792 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010793 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10794 }
10795
10796 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10797 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000010798 DSAStack->getParentOrderedRegionParam() &&
10799 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
10800 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010801 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10802 }
10803 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10804 Vars.empty())
10805 return nullptr;
10806 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010807 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10808 DepKind, DepLoc, ColonLoc, Vars);
10809 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10810 DSAStack->addDoacrossDependClause(C, OpsOffs);
10811 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010812}
Michael Wonge710d542015-08-07 16:16:36 +000010813
10814OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10815 SourceLocation LParenLoc,
10816 SourceLocation EndLoc) {
10817 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000010818 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000010819
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010820 // OpenMP [2.9.1, Restrictions]
10821 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010822 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10823 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010824 return nullptr;
10825
Alexey Bataev931e19b2017-10-02 16:32:39 +000010826 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10827 if (isOpenMPTargetExecutionDirective(DKind) &&
10828 !CurContext->isDependentContext()) {
10829 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10830 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10831 HelperValStmt = buildPreInits(Context, Captures);
10832 }
10833
10834 return new (Context)
10835 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000010836}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010837
Kelvin Li0bff7af2015-11-23 05:32:03 +000010838static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10839 DSAStackTy *Stack, QualType QTy) {
10840 NamedDecl *ND;
10841 if (QTy->isIncompleteType(&ND)) {
10842 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10843 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010844 }
10845 return true;
10846}
10847
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010848/// \brief Return true if it can be proven that the provided array expression
10849/// (array section or array subscript) does NOT specify the whole size of the
10850/// array whose base type is \a BaseQTy.
10851static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10852 const Expr *E,
10853 QualType BaseQTy) {
10854 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10855
10856 // If this is an array subscript, it refers to the whole size if the size of
10857 // the dimension is constant and equals 1. Also, an array section assumes the
10858 // format of an array subscript if no colon is used.
10859 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10860 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10861 return ATy->getSize().getSExtValue() != 1;
10862 // Size can't be evaluated statically.
10863 return false;
10864 }
10865
10866 assert(OASE && "Expecting array section if not an array subscript.");
10867 auto *LowerBound = OASE->getLowerBound();
10868 auto *Length = OASE->getLength();
10869
10870 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010871 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010872 if (LowerBound) {
10873 llvm::APSInt ConstLowerBound;
10874 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10875 return false; // Can't get the integer value as a constant.
10876 if (ConstLowerBound.getSExtValue())
10877 return true;
10878 }
10879
10880 // If we don't have a length we covering the whole dimension.
10881 if (!Length)
10882 return false;
10883
10884 // If the base is a pointer, we don't have a way to get the size of the
10885 // pointee.
10886 if (BaseQTy->isPointerType())
10887 return false;
10888
10889 // We can only check if the length is the same as the size of the dimension
10890 // if we have a constant array.
10891 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10892 if (!CATy)
10893 return false;
10894
10895 llvm::APSInt ConstLength;
10896 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10897 return false; // Can't get the integer value as a constant.
10898
10899 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10900}
10901
10902// Return true if it can be proven that the provided array expression (array
10903// section or array subscript) does NOT specify a single element of the array
10904// whose base type is \a BaseQTy.
10905static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010906 const Expr *E,
10907 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010908 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10909
10910 // An array subscript always refer to a single element. Also, an array section
10911 // assumes the format of an array subscript if no colon is used.
10912 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10913 return false;
10914
10915 assert(OASE && "Expecting array section if not an array subscript.");
10916 auto *Length = OASE->getLength();
10917
10918 // If we don't have a length we have to check if the array has unitary size
10919 // for this dimension. Also, we should always expect a length if the base type
10920 // is pointer.
10921 if (!Length) {
10922 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10923 return ATy->getSize().getSExtValue() != 1;
10924 // We cannot assume anything.
10925 return false;
10926 }
10927
10928 // Check if the length evaluates to 1.
10929 llvm::APSInt ConstLength;
10930 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10931 return false; // Can't get the integer value as a constant.
10932
10933 return ConstLength.getSExtValue() != 1;
10934}
10935
Samuel Antao661c0902016-05-26 17:39:58 +000010936// Return the expression of the base of the mappable expression or null if it
10937// cannot be determined and do all the necessary checks to see if the expression
10938// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010939// components of the expression.
10940static Expr *CheckMapClauseExpressionBase(
10941 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010942 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10943 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010944 SourceLocation ELoc = E->getExprLoc();
10945 SourceRange ERange = E->getSourceRange();
10946
10947 // The base of elements of list in a map clause have to be either:
10948 // - a reference to variable or field.
10949 // - a member expression.
10950 // - an array expression.
10951 //
10952 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10953 // reference to 'r'.
10954 //
10955 // If we have:
10956 //
10957 // struct SS {
10958 // Bla S;
10959 // foo() {
10960 // #pragma omp target map (S.Arr[:12]);
10961 // }
10962 // }
10963 //
10964 // We want to retrieve the member expression 'this->S';
10965
10966 Expr *RelevantExpr = nullptr;
10967
Samuel Antao5de996e2016-01-22 20:21:36 +000010968 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10969 // If a list item is an array section, it must specify contiguous storage.
10970 //
10971 // For this restriction it is sufficient that we make sure only references
10972 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010973 // exist except in the rightmost expression (unless they cover the whole
10974 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010975 //
10976 // r.ArrS[3:5].Arr[6:7]
10977 //
10978 // r.ArrS[3:5].x
10979 //
10980 // but these would be valid:
10981 // r.ArrS[3].Arr[6:7]
10982 //
10983 // r.ArrS[3].x
10984
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010985 bool AllowUnitySizeArraySection = true;
10986 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010987
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010988 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010989 E = E->IgnoreParenImpCasts();
10990
10991 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10992 if (!isa<VarDecl>(CurE->getDecl()))
10993 break;
10994
10995 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010996
10997 // If we got a reference to a declaration, we should not expect any array
10998 // section before that.
10999 AllowUnitySizeArraySection = false;
11000 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011001
11002 // Record the component.
11003 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
11004 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000011005 continue;
11006 }
11007
11008 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11009 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11010
11011 if (isa<CXXThisExpr>(BaseE))
11012 // We found a base expression: this->Val.
11013 RelevantExpr = CurE;
11014 else
11015 E = BaseE;
11016
11017 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11018 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11019 << CurE->getSourceRange();
11020 break;
11021 }
11022
11023 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11024
11025 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11026 // A bit-field cannot appear in a map clause.
11027 //
11028 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011029 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11030 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011031 break;
11032 }
11033
11034 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11035 // If the type of a list item is a reference to a type T then the type
11036 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011037 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011038
11039 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11040 // A list item cannot be a variable that is a member of a structure with
11041 // a union type.
11042 //
11043 if (auto *RT = CurType->getAs<RecordType>())
11044 if (RT->isUnionType()) {
11045 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11046 << CurE->getSourceRange();
11047 break;
11048 }
11049
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011050 // If we got a member expression, we should not expect any array section
11051 // before that:
11052 //
11053 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11054 // If a list item is an element of a structure, only the rightmost symbol
11055 // of the variable reference can be an array section.
11056 //
11057 AllowUnitySizeArraySection = false;
11058 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011059
11060 // Record the component.
11061 CurComponents.push_back(
11062 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000011063 continue;
11064 }
11065
11066 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11067 E = CurE->getBase()->IgnoreParenImpCasts();
11068
11069 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11070 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11071 << 0 << CurE->getSourceRange();
11072 break;
11073 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011074
11075 // If we got an array subscript that express the whole dimension we
11076 // can have any array expressions before. If it only expressing part of
11077 // the dimension, we can only have unitary-size array expressions.
11078 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11079 E->getType()))
11080 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011081
11082 // Record the component - we don't have any declaration associated.
11083 CurComponents.push_back(
11084 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011085 continue;
11086 }
11087
11088 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011089 E = CurE->getBase()->IgnoreParenImpCasts();
11090
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011091 auto CurType =
11092 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11093
Samuel Antao5de996e2016-01-22 20:21:36 +000011094 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11095 // If the type of a list item is a reference to a type T then the type
11096 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011097 if (CurType->isReferenceType())
11098 CurType = CurType->getPointeeType();
11099
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011100 bool IsPointer = CurType->isAnyPointerType();
11101
11102 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011103 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11104 << 0 << CurE->getSourceRange();
11105 break;
11106 }
11107
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011108 bool NotWhole =
11109 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11110 bool NotUnity =
11111 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11112
Samuel Antaodab51bb2016-07-18 23:22:11 +000011113 if (AllowWholeSizeArraySection) {
11114 // Any array section is currently allowed. Allowing a whole size array
11115 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011116 //
11117 // If this array section refers to the whole dimension we can still
11118 // accept other array sections before this one, except if the base is a
11119 // pointer. Otherwise, only unitary sections are accepted.
11120 if (NotWhole || IsPointer)
11121 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011122 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011123 // A unity or whole array section is not allowed and that is not
11124 // compatible with the properties of the current array section.
11125 SemaRef.Diag(
11126 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11127 << CurE->getSourceRange();
11128 break;
11129 }
Samuel Antao90927002016-04-26 14:54:23 +000011130
11131 // Record the component - we don't have any declaration associated.
11132 CurComponents.push_back(
11133 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011134 continue;
11135 }
11136
11137 // If nothing else worked, this is not a valid map clause expression.
11138 SemaRef.Diag(ELoc,
11139 diag::err_omp_expected_named_var_member_or_array_expression)
11140 << ERange;
11141 break;
11142 }
11143
11144 return RelevantExpr;
11145}
11146
11147// Return true if expression E associated with value VD has conflicts with other
11148// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011149static bool CheckMapConflicts(
11150 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11151 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011152 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11153 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011154 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011155 SourceLocation ELoc = E->getExprLoc();
11156 SourceRange ERange = E->getSourceRange();
11157
11158 // In order to easily check the conflicts we need to match each component of
11159 // the expression under test with the components of the expressions that are
11160 // already in the stack.
11161
Samuel Antao5de996e2016-01-22 20:21:36 +000011162 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011163 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011164 "Map clause expression with unexpected base!");
11165
11166 // Variables to help detecting enclosing problems in data environment nests.
11167 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011168 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011169
Samuel Antao90927002016-04-26 14:54:23 +000011170 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11171 VD, CurrentRegionOnly,
11172 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011173 StackComponents,
11174 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011175
Samuel Antao5de996e2016-01-22 20:21:36 +000011176 assert(!StackComponents.empty() &&
11177 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011178 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011179 "Map clause expression with unexpected base!");
11180
Samuel Antao90927002016-04-26 14:54:23 +000011181 // The whole expression in the stack.
11182 auto *RE = StackComponents.front().getAssociatedExpression();
11183
Samuel Antao5de996e2016-01-22 20:21:36 +000011184 // Expressions must start from the same base. Here we detect at which
11185 // point both expressions diverge from each other and see if we can
11186 // detect if the memory referred to both expressions is contiguous and
11187 // do not overlap.
11188 auto CI = CurComponents.rbegin();
11189 auto CE = CurComponents.rend();
11190 auto SI = StackComponents.rbegin();
11191 auto SE = StackComponents.rend();
11192 for (; CI != CE && SI != SE; ++CI, ++SI) {
11193
11194 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11195 // At most one list item can be an array item derived from a given
11196 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011197 if (CurrentRegionOnly &&
11198 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11199 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11200 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11201 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11202 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011203 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011204 << CI->getAssociatedExpression()->getSourceRange();
11205 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11206 diag::note_used_here)
11207 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011208 return true;
11209 }
11210
11211 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011212 if (CI->getAssociatedExpression()->getStmtClass() !=
11213 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011214 break;
11215
11216 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011217 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011218 break;
11219 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011220 // Check if the extra components of the expressions in the enclosing
11221 // data environment are redundant for the current base declaration.
11222 // If they are, the maps completely overlap, which is legal.
11223 for (; SI != SE; ++SI) {
11224 QualType Type;
11225 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011226 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011227 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011228 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11229 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011230 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11231 Type =
11232 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11233 }
11234 if (Type.isNull() || Type->isAnyPointerType() ||
11235 CheckArrayExpressionDoesNotReferToWholeSize(
11236 SemaRef, SI->getAssociatedExpression(), Type))
11237 break;
11238 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011239
11240 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11241 // List items of map clauses in the same construct must not share
11242 // original storage.
11243 //
11244 // If the expressions are exactly the same or one is a subset of the
11245 // other, it means they are sharing storage.
11246 if (CI == CE && SI == SE) {
11247 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011248 if (CKind == OMPC_map)
11249 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11250 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011251 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011252 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11253 << ERange;
11254 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011255 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11256 << RE->getSourceRange();
11257 return true;
11258 } else {
11259 // If we find the same expression in the enclosing data environment,
11260 // that is legal.
11261 IsEnclosedByDataEnvironmentExpr = true;
11262 return false;
11263 }
11264 }
11265
Samuel Antao90927002016-04-26 14:54:23 +000011266 QualType DerivedType =
11267 std::prev(CI)->getAssociatedDeclaration()->getType();
11268 SourceLocation DerivedLoc =
11269 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011270
11271 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11272 // If the type of a list item is a reference to a type T then the type
11273 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011274 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011275
11276 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11277 // A variable for which the type is pointer and an array section
11278 // derived from that variable must not appear as list items of map
11279 // clauses of the same construct.
11280 //
11281 // Also, cover one of the cases in:
11282 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11283 // If any part of the original storage of a list item has corresponding
11284 // storage in the device data environment, all of the original storage
11285 // must have corresponding storage in the device data environment.
11286 //
11287 if (DerivedType->isAnyPointerType()) {
11288 if (CI == CE || SI == SE) {
11289 SemaRef.Diag(
11290 DerivedLoc,
11291 diag::err_omp_pointer_mapped_along_with_derived_section)
11292 << DerivedLoc;
11293 } else {
11294 assert(CI != CE && SI != SE);
11295 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11296 << DerivedLoc;
11297 }
11298 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11299 << RE->getSourceRange();
11300 return true;
11301 }
11302
11303 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11304 // List items of map clauses in the same construct must not share
11305 // original storage.
11306 //
11307 // An expression is a subset of the other.
11308 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011309 if (CKind == OMPC_map)
11310 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11311 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011312 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011313 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11314 << ERange;
11315 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011316 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11317 << RE->getSourceRange();
11318 return true;
11319 }
11320
11321 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011322 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011323 if (!CurrentRegionOnly && SI != SE)
11324 EnclosingExpr = RE;
11325
11326 // The current expression is a subset of the expression in the data
11327 // environment.
11328 IsEnclosedByDataEnvironmentExpr |=
11329 (!CurrentRegionOnly && CI != CE && SI == SE);
11330
11331 return false;
11332 });
11333
11334 if (CurrentRegionOnly)
11335 return FoundError;
11336
11337 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11338 // If any part of the original storage of a list item has corresponding
11339 // storage in the device data environment, all of the original storage must
11340 // have corresponding storage in the device data environment.
11341 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11342 // If a list item is an element of a structure, and a different element of
11343 // the structure has a corresponding list item in the device data environment
11344 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011345 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011346 // data environment prior to the task encountering the construct.
11347 //
11348 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11349 SemaRef.Diag(ELoc,
11350 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11351 << ERange;
11352 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11353 << EnclosingExpr->getSourceRange();
11354 return true;
11355 }
11356
11357 return FoundError;
11358}
11359
Samuel Antao661c0902016-05-26 17:39:58 +000011360namespace {
11361// Utility struct that gathers all the related lists associated with a mappable
11362// expression.
11363struct MappableVarListInfo final {
11364 // The list of expressions.
11365 ArrayRef<Expr *> VarList;
11366 // The list of processed expressions.
11367 SmallVector<Expr *, 16> ProcessedVarList;
11368 // The mappble components for each expression.
11369 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11370 // The base declaration of the variable.
11371 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11372
11373 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11374 // We have a list of components and base declarations for each entry in the
11375 // variable list.
11376 VarComponents.reserve(VarList.size());
11377 VarBaseDeclarations.reserve(VarList.size());
11378 }
11379};
11380}
11381
11382// Check the validity of the provided variable list for the provided clause kind
11383// \a CKind. In the check process the valid expressions, and mappable expression
11384// components and variables are extracted and used to fill \a Vars,
11385// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11386// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11387static void
11388checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11389 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11390 SourceLocation StartLoc,
11391 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11392 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011393 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11394 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011395 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011396
Samuel Antao90927002016-04-26 14:54:23 +000011397 // Keep track of the mappable components and base declarations in this clause.
11398 // Each entry in the list is going to have a list of components associated. We
11399 // record each set of the components so that we can build the clause later on.
11400 // In the end we should have the same amount of declarations and component
11401 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011402
Samuel Antao661c0902016-05-26 17:39:58 +000011403 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011404 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011405 SourceLocation ELoc = RE->getExprLoc();
11406
Kelvin Li0bff7af2015-11-23 05:32:03 +000011407 auto *VE = RE->IgnoreParenLValueCasts();
11408
11409 if (VE->isValueDependent() || VE->isTypeDependent() ||
11410 VE->isInstantiationDependent() ||
11411 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011412 // We can only analyze this information once the missing information is
11413 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011414 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011415 continue;
11416 }
11417
11418 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011419
Samuel Antao5de996e2016-01-22 20:21:36 +000011420 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011421 SemaRef.Diag(ELoc,
11422 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011423 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011424 continue;
11425 }
11426
Samuel Antao90927002016-04-26 14:54:23 +000011427 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11428 ValueDecl *CurDeclaration = nullptr;
11429
11430 // Obtain the array or member expression bases if required. Also, fill the
11431 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011432 auto *BE =
11433 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011434 if (!BE)
11435 continue;
11436
Samuel Antao90927002016-04-26 14:54:23 +000011437 assert(!CurComponents.empty() &&
11438 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011439
Samuel Antao90927002016-04-26 14:54:23 +000011440 // For the following checks, we rely on the base declaration which is
11441 // expected to be associated with the last component. The declaration is
11442 // expected to be a variable or a field (if 'this' is being mapped).
11443 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11444 assert(CurDeclaration && "Null decl on map clause.");
11445 assert(
11446 CurDeclaration->isCanonicalDecl() &&
11447 "Expecting components to have associated only canonical declarations.");
11448
11449 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11450 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011451
11452 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011453 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011454
11455 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011456 // threadprivate variables cannot appear in a map clause.
11457 // OpenMP 4.5 [2.10.5, target update Construct]
11458 // threadprivate variables cannot appear in a from clause.
11459 if (VD && DSAS->isThreadPrivate(VD)) {
11460 auto DVar = DSAS->getTopDSA(VD, false);
11461 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11462 << getOpenMPClauseName(CKind);
11463 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011464 continue;
11465 }
11466
Samuel Antao5de996e2016-01-22 20:21:36 +000011467 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11468 // A list item cannot appear in both a map clause and a data-sharing
11469 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011470
Samuel Antao5de996e2016-01-22 20:21:36 +000011471 // Check conflicts with other map clause expressions. We check the conflicts
11472 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011473 // environment, because the restrictions are different. We only have to
11474 // check conflicts across regions for the map clauses.
11475 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11476 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011477 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011478 if (CKind == OMPC_map &&
11479 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11480 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011481 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011482
Samuel Antao661c0902016-05-26 17:39:58 +000011483 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011484 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11485 // If the type of a list item is a reference to a type T then the type will
11486 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011487 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011488
Samuel Antao661c0902016-05-26 17:39:58 +000011489 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11490 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011491 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011492 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011493 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11494 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011495 continue;
11496
Samuel Antao661c0902016-05-26 17:39:58 +000011497 if (CKind == OMPC_map) {
11498 // target enter data
11499 // OpenMP [2.10.2, Restrictions, p. 99]
11500 // A map-type must be specified in all map clauses and must be either
11501 // to or alloc.
11502 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11503 if (DKind == OMPD_target_enter_data &&
11504 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11505 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11506 << (IsMapTypeImplicit ? 1 : 0)
11507 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11508 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011509 continue;
11510 }
Samuel Antao661c0902016-05-26 17:39:58 +000011511
11512 // target exit_data
11513 // OpenMP [2.10.3, Restrictions, p. 102]
11514 // A map-type must be specified in all map clauses and must be either
11515 // from, release, or delete.
11516 if (DKind == OMPD_target_exit_data &&
11517 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11518 MapType == OMPC_MAP_delete)) {
11519 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11520 << (IsMapTypeImplicit ? 1 : 0)
11521 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11522 << getOpenMPDirectiveName(DKind);
11523 continue;
11524 }
11525
11526 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11527 // A list item cannot appear in both a map clause and a data-sharing
11528 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011529 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011530 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011531 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011532 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11533 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011534 auto DVar = DSAS->getTopDSA(VD, false);
11535 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011536 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011537 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011538 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011539 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11540 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11541 continue;
11542 }
11543 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011544 }
11545
Samuel Antao90927002016-04-26 14:54:23 +000011546 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011547 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011548
11549 // Store the components in the stack so that they can be used to check
11550 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011551 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11552 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011553
11554 // Save the components and declaration to create the clause. For purposes of
11555 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011556 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011557 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11558 MVLI.VarComponents.back().append(CurComponents.begin(),
11559 CurComponents.end());
11560 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11561 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011562 }
Samuel Antao661c0902016-05-26 17:39:58 +000011563}
11564
11565OMPClause *
11566Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11567 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11568 SourceLocation MapLoc, SourceLocation ColonLoc,
11569 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11570 SourceLocation LParenLoc, SourceLocation EndLoc) {
11571 MappableVarListInfo MVLI(VarList);
11572 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11573 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011574
Samuel Antao5de996e2016-01-22 20:21:36 +000011575 // We need to produce a map clause even if we don't have variables so that
11576 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011577 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11578 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11579 MVLI.VarComponents, MapTypeModifier, MapType,
11580 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011581}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011582
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011583QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11584 TypeResult ParsedType) {
11585 assert(ParsedType.isUsable());
11586
11587 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11588 if (ReductionType.isNull())
11589 return QualType();
11590
11591 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11592 // A type name in a declare reduction directive cannot be a function type, an
11593 // array type, a reference type, or a type qualified with const, volatile or
11594 // restrict.
11595 if (ReductionType.hasQualifiers()) {
11596 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11597 return QualType();
11598 }
11599
11600 if (ReductionType->isFunctionType()) {
11601 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11602 return QualType();
11603 }
11604 if (ReductionType->isReferenceType()) {
11605 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11606 return QualType();
11607 }
11608 if (ReductionType->isArrayType()) {
11609 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11610 return QualType();
11611 }
11612 return ReductionType;
11613}
11614
11615Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11616 Scope *S, DeclContext *DC, DeclarationName Name,
11617 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11618 AccessSpecifier AS, Decl *PrevDeclInScope) {
11619 SmallVector<Decl *, 8> Decls;
11620 Decls.reserve(ReductionTypes.size());
11621
11622 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000011623 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011624 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11625 // A reduction-identifier may not be re-declared in the current scope for the
11626 // same type or for a type that is compatible according to the base language
11627 // rules.
11628 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11629 OMPDeclareReductionDecl *PrevDRD = nullptr;
11630 bool InCompoundScope = true;
11631 if (S != nullptr) {
11632 // Find previous declaration with the same name not referenced in other
11633 // declarations.
11634 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11635 InCompoundScope =
11636 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11637 LookupName(Lookup, S);
11638 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11639 /*AllowInlineNamespace=*/false);
11640 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11641 auto Filter = Lookup.makeFilter();
11642 while (Filter.hasNext()) {
11643 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11644 if (InCompoundScope) {
11645 auto I = UsedAsPrevious.find(PrevDecl);
11646 if (I == UsedAsPrevious.end())
11647 UsedAsPrevious[PrevDecl] = false;
11648 if (auto *D = PrevDecl->getPrevDeclInScope())
11649 UsedAsPrevious[D] = true;
11650 }
11651 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11652 PrevDecl->getLocation();
11653 }
11654 Filter.done();
11655 if (InCompoundScope) {
11656 for (auto &PrevData : UsedAsPrevious) {
11657 if (!PrevData.second) {
11658 PrevDRD = PrevData.first;
11659 break;
11660 }
11661 }
11662 }
11663 } else if (PrevDeclInScope != nullptr) {
11664 auto *PrevDRDInScope = PrevDRD =
11665 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11666 do {
11667 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11668 PrevDRDInScope->getLocation();
11669 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11670 } while (PrevDRDInScope != nullptr);
11671 }
11672 for (auto &TyData : ReductionTypes) {
11673 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11674 bool Invalid = false;
11675 if (I != PreviousRedeclTypes.end()) {
11676 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11677 << TyData.first;
11678 Diag(I->second, diag::note_previous_definition);
11679 Invalid = true;
11680 }
11681 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11682 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11683 Name, TyData.first, PrevDRD);
11684 DC->addDecl(DRD);
11685 DRD->setAccess(AS);
11686 Decls.push_back(DRD);
11687 if (Invalid)
11688 DRD->setInvalidDecl();
11689 else
11690 PrevDRD = DRD;
11691 }
11692
11693 return DeclGroupPtrTy::make(
11694 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11695}
11696
11697void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11698 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11699
11700 // Enter new function scope.
11701 PushFunctionScope();
11702 getCurFunction()->setHasBranchProtectedScope();
11703 getCurFunction()->setHasOMPDeclareReductionCombiner();
11704
11705 if (S != nullptr)
11706 PushDeclContext(S, DRD);
11707 else
11708 CurContext = DRD;
11709
Faisal Valid143a0c2017-04-01 21:30:49 +000011710 PushExpressionEvaluationContext(
11711 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011712
11713 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011714 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11715 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11716 // uses semantics of argument handles by value, but it should be passed by
11717 // reference. C lang does not support references, so pass all parameters as
11718 // pointers.
11719 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011720 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011721 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011722 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11723 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11724 // uses semantics of argument handles by value, but it should be passed by
11725 // reference. C lang does not support references, so pass all parameters as
11726 // pointers.
11727 // Create 'T omp_out;' variable.
11728 auto *OmpOutParm =
11729 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11730 if (S != nullptr) {
11731 PushOnScopeChains(OmpInParm, S);
11732 PushOnScopeChains(OmpOutParm, S);
11733 } else {
11734 DRD->addDecl(OmpInParm);
11735 DRD->addDecl(OmpOutParm);
11736 }
11737}
11738
11739void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11740 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11741 DiscardCleanupsInEvaluationContext();
11742 PopExpressionEvaluationContext();
11743
11744 PopDeclContext();
11745 PopFunctionScopeInfo();
11746
11747 if (Combiner != nullptr)
11748 DRD->setCombiner(Combiner);
11749 else
11750 DRD->setInvalidDecl();
11751}
11752
Alexey Bataev070f43a2017-09-06 14:49:58 +000011753VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011754 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11755
11756 // Enter new function scope.
11757 PushFunctionScope();
11758 getCurFunction()->setHasBranchProtectedScope();
11759
11760 if (S != nullptr)
11761 PushDeclContext(S, DRD);
11762 else
11763 CurContext = DRD;
11764
Faisal Valid143a0c2017-04-01 21:30:49 +000011765 PushExpressionEvaluationContext(
11766 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011767
11768 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011769 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11770 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11771 // uses semantics of argument handles by value, but it should be passed by
11772 // reference. C lang does not support references, so pass all parameters as
11773 // pointers.
11774 // Create 'T omp_priv;' variable.
11775 auto *OmpPrivParm =
11776 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011777 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11778 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11779 // uses semantics of argument handles by value, but it should be passed by
11780 // reference. C lang does not support references, so pass all parameters as
11781 // pointers.
11782 // Create 'T omp_orig;' variable.
11783 auto *OmpOrigParm =
11784 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011785 if (S != nullptr) {
11786 PushOnScopeChains(OmpPrivParm, S);
11787 PushOnScopeChains(OmpOrigParm, S);
11788 } else {
11789 DRD->addDecl(OmpPrivParm);
11790 DRD->addDecl(OmpOrigParm);
11791 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000011792 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011793}
11794
Alexey Bataev070f43a2017-09-06 14:49:58 +000011795void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
11796 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011797 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11798 DiscardCleanupsInEvaluationContext();
11799 PopExpressionEvaluationContext();
11800
11801 PopDeclContext();
11802 PopFunctionScopeInfo();
11803
Alexey Bataev070f43a2017-09-06 14:49:58 +000011804 if (Initializer != nullptr) {
11805 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
11806 } else if (OmpPrivParm->hasInit()) {
11807 DRD->setInitializer(OmpPrivParm->getInit(),
11808 OmpPrivParm->isDirectInit()
11809 ? OMPDeclareReductionDecl::DirectInit
11810 : OMPDeclareReductionDecl::CopyInit);
11811 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011812 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000011813 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011814}
11815
11816Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11817 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11818 for (auto *D : DeclReductions.get()) {
11819 if (IsValid) {
11820 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11821 if (S != nullptr)
11822 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11823 } else
11824 D->setInvalidDecl();
11825 }
11826 return DeclReductions;
11827}
11828
David Majnemer9d168222016-08-05 17:44:54 +000011829OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011830 SourceLocation StartLoc,
11831 SourceLocation LParenLoc,
11832 SourceLocation EndLoc) {
11833 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011834 Stmt *HelperValStmt = nullptr;
11835 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011836
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011837 // OpenMP [teams Constrcut, Restrictions]
11838 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011839 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11840 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011841 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011842
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011843 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11844 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11845 if (CaptureRegion != OMPD_unknown) {
11846 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11847 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11848 HelperValStmt = buildPreInits(Context, Captures);
11849 }
11850
11851 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11852 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011853}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011854
11855OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11856 SourceLocation StartLoc,
11857 SourceLocation LParenLoc,
11858 SourceLocation EndLoc) {
11859 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011860 Stmt *HelperValStmt = nullptr;
11861 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011862
11863 // OpenMP [teams Constrcut, Restrictions]
11864 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011865 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11866 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011867 return nullptr;
11868
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011869 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11870 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11871 if (CaptureRegion != OMPD_unknown) {
11872 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11873 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11874 HelperValStmt = buildPreInits(Context, Captures);
11875 }
11876
11877 return new (Context) OMPThreadLimitClause(
11878 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011879}
Alexey Bataeva0569352015-12-01 10:17:31 +000011880
11881OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11882 SourceLocation StartLoc,
11883 SourceLocation LParenLoc,
11884 SourceLocation EndLoc) {
11885 Expr *ValExpr = Priority;
11886
11887 // OpenMP [2.9.1, task Constrcut]
11888 // The priority-value is a non-negative numerical scalar expression.
11889 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11890 /*StrictlyPositive=*/false))
11891 return nullptr;
11892
11893 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11894}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011895
11896OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11897 SourceLocation StartLoc,
11898 SourceLocation LParenLoc,
11899 SourceLocation EndLoc) {
11900 Expr *ValExpr = Grainsize;
11901
11902 // OpenMP [2.9.2, taskloop Constrcut]
11903 // The parameter of the grainsize clause must be a positive integer
11904 // expression.
11905 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11906 /*StrictlyPositive=*/true))
11907 return nullptr;
11908
11909 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11910}
Alexey Bataev382967a2015-12-08 12:06:20 +000011911
11912OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11913 SourceLocation StartLoc,
11914 SourceLocation LParenLoc,
11915 SourceLocation EndLoc) {
11916 Expr *ValExpr = NumTasks;
11917
11918 // OpenMP [2.9.2, taskloop Constrcut]
11919 // The parameter of the num_tasks clause must be a positive integer
11920 // expression.
11921 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11922 /*StrictlyPositive=*/true))
11923 return nullptr;
11924
11925 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11926}
11927
Alexey Bataev28c75412015-12-15 08:19:24 +000011928OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11929 SourceLocation LParenLoc,
11930 SourceLocation EndLoc) {
11931 // OpenMP [2.13.2, critical construct, Description]
11932 // ... where hint-expression is an integer constant expression that evaluates
11933 // to a valid lock hint.
11934 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11935 if (HintExpr.isInvalid())
11936 return nullptr;
11937 return new (Context)
11938 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11939}
11940
Carlo Bertollib4adf552016-01-15 18:50:31 +000011941OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11942 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11943 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11944 SourceLocation EndLoc) {
11945 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11946 std::string Values;
11947 Values += "'";
11948 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11949 Values += "'";
11950 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11951 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11952 return nullptr;
11953 }
11954 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011955 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011956 if (ChunkSize) {
11957 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11958 !ChunkSize->isInstantiationDependent() &&
11959 !ChunkSize->containsUnexpandedParameterPack()) {
11960 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11961 ExprResult Val =
11962 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11963 if (Val.isInvalid())
11964 return nullptr;
11965
11966 ValExpr = Val.get();
11967
11968 // OpenMP [2.7.1, Restrictions]
11969 // chunk_size must be a loop invariant integer expression with a positive
11970 // value.
11971 llvm::APSInt Result;
11972 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11973 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11974 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11975 << "dist_schedule" << ChunkSize->getSourceRange();
11976 return nullptr;
11977 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011978 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11979 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011980 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11981 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11982 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011983 }
11984 }
11985 }
11986
11987 return new (Context)
11988 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011989 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011990}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011991
11992OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11993 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11994 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11995 SourceLocation KindLoc, SourceLocation EndLoc) {
11996 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011997 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011998 std::string Value;
11999 SourceLocation Loc;
12000 Value += "'";
12001 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12002 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012003 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012004 Loc = MLoc;
12005 } else {
12006 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012007 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012008 Loc = KindLoc;
12009 }
12010 Value += "'";
12011 Diag(Loc, diag::err_omp_unexpected_clause_value)
12012 << Value << getOpenMPClauseName(OMPC_defaultmap);
12013 return nullptr;
12014 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012015 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012016
12017 return new (Context)
12018 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12019}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012020
12021bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12022 DeclContext *CurLexicalContext = getCurLexicalContext();
12023 if (!CurLexicalContext->isFileContext() &&
12024 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012025 !CurLexicalContext->isExternCXXContext() &&
12026 !isa<CXXRecordDecl>(CurLexicalContext) &&
12027 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12028 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12029 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012030 Diag(Loc, diag::err_omp_region_not_file_context);
12031 return false;
12032 }
12033 if (IsInOpenMPDeclareTargetContext) {
12034 Diag(Loc, diag::err_omp_enclosed_declare_target);
12035 return false;
12036 }
12037
12038 IsInOpenMPDeclareTargetContext = true;
12039 return true;
12040}
12041
12042void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12043 assert(IsInOpenMPDeclareTargetContext &&
12044 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12045
12046 IsInOpenMPDeclareTargetContext = false;
12047}
12048
David Majnemer9d168222016-08-05 17:44:54 +000012049void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12050 CXXScopeSpec &ScopeSpec,
12051 const DeclarationNameInfo &Id,
12052 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12053 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012054 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12055 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12056
12057 if (Lookup.isAmbiguous())
12058 return;
12059 Lookup.suppressDiagnostics();
12060
12061 if (!Lookup.isSingleResult()) {
12062 if (TypoCorrection Corrected =
12063 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12064 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12065 CTK_ErrorRecovery)) {
12066 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12067 << Id.getName());
12068 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12069 return;
12070 }
12071
12072 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12073 return;
12074 }
12075
12076 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12077 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12078 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12079 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12080
12081 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12082 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12083 ND->addAttr(A);
12084 if (ASTMutationListener *ML = Context.getASTMutationListener())
12085 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12086 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12087 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12088 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12089 << Id.getName();
12090 }
12091 } else
12092 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12093}
12094
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012095static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12096 Sema &SemaRef, Decl *D) {
12097 if (!D)
12098 return;
12099 Decl *LD = nullptr;
12100 if (isa<TagDecl>(D)) {
12101 LD = cast<TagDecl>(D)->getDefinition();
12102 } else if (isa<VarDecl>(D)) {
12103 LD = cast<VarDecl>(D)->getDefinition();
12104
12105 // If this is an implicit variable that is legal and we do not need to do
12106 // anything.
12107 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012108 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12109 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12110 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012111 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012112 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012113 return;
12114 }
12115
12116 } else if (isa<FunctionDecl>(D)) {
12117 const FunctionDecl *FD = nullptr;
12118 if (cast<FunctionDecl>(D)->hasBody(FD))
12119 LD = const_cast<FunctionDecl *>(FD);
12120
12121 // If the definition is associated with the current declaration in the
12122 // target region (it can be e.g. a lambda) that is legal and we do not need
12123 // to do anything else.
12124 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012125 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12126 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12127 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012128 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012129 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012130 return;
12131 }
12132 }
12133 if (!LD)
12134 LD = D;
12135 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12136 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12137 // Outlined declaration is not declared target.
12138 if (LD->isOutOfLine()) {
12139 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12140 SemaRef.Diag(SL, diag::note_used_here) << SR;
12141 } else {
12142 DeclContext *DC = LD->getDeclContext();
12143 while (DC) {
12144 if (isa<FunctionDecl>(DC) &&
12145 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12146 break;
12147 DC = DC->getParent();
12148 }
12149 if (DC)
12150 return;
12151
12152 // Is not declared in target context.
12153 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12154 SemaRef.Diag(SL, diag::note_used_here) << SR;
12155 }
12156 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012157 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12158 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12159 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012160 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012161 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012162 }
12163}
12164
12165static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12166 Sema &SemaRef, DSAStackTy *Stack,
12167 ValueDecl *VD) {
12168 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12169 return true;
12170 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12171 return false;
12172 return true;
12173}
12174
12175void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12176 if (!D || D->isInvalidDecl())
12177 return;
12178 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12179 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12180 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12181 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12182 if (DSAStack->isThreadPrivate(VD)) {
12183 Diag(SL, diag::err_omp_threadprivate_in_target);
12184 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12185 return;
12186 }
12187 }
12188 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12189 // Problem if any with var declared with incomplete type will be reported
12190 // as normal, so no need to check it here.
12191 if ((E || !VD->getType()->isIncompleteType()) &&
12192 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12193 // Mark decl as declared target to prevent further diagnostic.
12194 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012195 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12196 Context, OMPDeclareTargetDeclAttr::MT_To);
12197 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012198 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012199 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012200 }
12201 return;
12202 }
12203 }
12204 if (!E) {
12205 // Checking declaration inside declare target region.
12206 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12207 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012208 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12209 Context, OMPDeclareTargetDeclAttr::MT_To);
12210 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012211 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012212 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012213 }
12214 return;
12215 }
12216 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12217}
Samuel Antao661c0902016-05-26 17:39:58 +000012218
12219OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12220 SourceLocation StartLoc,
12221 SourceLocation LParenLoc,
12222 SourceLocation EndLoc) {
12223 MappableVarListInfo MVLI(VarList);
12224 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12225 if (MVLI.ProcessedVarList.empty())
12226 return nullptr;
12227
12228 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12229 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12230 MVLI.VarComponents);
12231}
Samuel Antaoec172c62016-05-26 17:49:04 +000012232
12233OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12234 SourceLocation StartLoc,
12235 SourceLocation LParenLoc,
12236 SourceLocation EndLoc) {
12237 MappableVarListInfo MVLI(VarList);
12238 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12239 if (MVLI.ProcessedVarList.empty())
12240 return nullptr;
12241
12242 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12243 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12244 MVLI.VarComponents);
12245}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012246
12247OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12248 SourceLocation StartLoc,
12249 SourceLocation LParenLoc,
12250 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012251 MappableVarListInfo MVLI(VarList);
12252 SmallVector<Expr *, 8> PrivateCopies;
12253 SmallVector<Expr *, 8> Inits;
12254
Carlo Bertolli2404b172016-07-13 15:37:16 +000012255 for (auto &RefExpr : VarList) {
12256 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12257 SourceLocation ELoc;
12258 SourceRange ERange;
12259 Expr *SimpleRefExpr = RefExpr;
12260 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12261 if (Res.second) {
12262 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012263 MVLI.ProcessedVarList.push_back(RefExpr);
12264 PrivateCopies.push_back(nullptr);
12265 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012266 }
12267 ValueDecl *D = Res.first;
12268 if (!D)
12269 continue;
12270
12271 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012272 Type = Type.getNonReferenceType().getUnqualifiedType();
12273
12274 auto *VD = dyn_cast<VarDecl>(D);
12275
12276 // Item should be a pointer or reference to pointer.
12277 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012278 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12279 << 0 << RefExpr->getSourceRange();
12280 continue;
12281 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012282
12283 // Build the private variable and the expression that refers to it.
12284 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12285 D->hasAttrs() ? &D->getAttrs() : nullptr);
12286 if (VDPrivate->isInvalidDecl())
12287 continue;
12288
12289 CurContext->addDecl(VDPrivate);
12290 auto VDPrivateRefExpr = buildDeclRefExpr(
12291 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12292
12293 // Add temporary variable to initialize the private copy of the pointer.
12294 auto *VDInit =
12295 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12296 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12297 RefExpr->getExprLoc());
12298 AddInitializerToDecl(VDPrivate,
12299 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012300 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012301
12302 // If required, build a capture to implement the privatization initialized
12303 // with the current list item value.
12304 DeclRefExpr *Ref = nullptr;
12305 if (!VD)
12306 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12307 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12308 PrivateCopies.push_back(VDPrivateRefExpr);
12309 Inits.push_back(VDInitRefExpr);
12310
12311 // We need to add a data sharing attribute for this variable to make sure it
12312 // is correctly captured. A variable that shows up in a use_device_ptr has
12313 // similar properties of a first private variable.
12314 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12315
12316 // Create a mappable component for the list item. List items in this clause
12317 // only need a component.
12318 MVLI.VarBaseDeclarations.push_back(D);
12319 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12320 MVLI.VarComponents.back().push_back(
12321 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012322 }
12323
Samuel Antaocc10b852016-07-28 14:23:26 +000012324 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012325 return nullptr;
12326
Samuel Antaocc10b852016-07-28 14:23:26 +000012327 return OMPUseDevicePtrClause::Create(
12328 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12329 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012330}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012331
12332OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12333 SourceLocation StartLoc,
12334 SourceLocation LParenLoc,
12335 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012336 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012337 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012338 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012339 SourceLocation ELoc;
12340 SourceRange ERange;
12341 Expr *SimpleRefExpr = RefExpr;
12342 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12343 if (Res.second) {
12344 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012345 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012346 }
12347 ValueDecl *D = Res.first;
12348 if (!D)
12349 continue;
12350
12351 QualType Type = D->getType();
12352 // item should be a pointer or array or reference to pointer or array
12353 if (!Type.getNonReferenceType()->isPointerType() &&
12354 !Type.getNonReferenceType()->isArrayType()) {
12355 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12356 << 0 << RefExpr->getSourceRange();
12357 continue;
12358 }
Samuel Antao6890b092016-07-28 14:25:09 +000012359
12360 // Check if the declaration in the clause does not show up in any data
12361 // sharing attribute.
12362 auto DVar = DSAStack->getTopDSA(D, false);
12363 if (isOpenMPPrivate(DVar.CKind)) {
12364 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12365 << getOpenMPClauseName(DVar.CKind)
12366 << getOpenMPClauseName(OMPC_is_device_ptr)
12367 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12368 ReportOriginalDSA(*this, DSAStack, D, DVar);
12369 continue;
12370 }
12371
12372 Expr *ConflictExpr;
12373 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012374 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012375 [&ConflictExpr](
12376 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12377 OpenMPClauseKind) -> bool {
12378 ConflictExpr = R.front().getAssociatedExpression();
12379 return true;
12380 })) {
12381 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12382 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12383 << ConflictExpr->getSourceRange();
12384 continue;
12385 }
12386
12387 // Store the components in the stack so that they can be used to check
12388 // against other clauses later on.
12389 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12390 DSAStack->addMappableExpressionComponents(
12391 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12392
12393 // Record the expression we've just processed.
12394 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12395
12396 // Create a mappable component for the list item. List items in this clause
12397 // only need a component. We use a null declaration to signal fields in
12398 // 'this'.
12399 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12400 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12401 "Unexpected device pointer expression!");
12402 MVLI.VarBaseDeclarations.push_back(
12403 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12404 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12405 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012406 }
12407
Samuel Antao6890b092016-07-28 14:25:09 +000012408 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012409 return nullptr;
12410
Samuel Antao6890b092016-07-28 14:25:09 +000012411 return OMPIsDevicePtrClause::Create(
12412 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12413 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012414}