blob: 7fdd08d5e5756e9903562ac3698dff180b6ba285 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataevf47c4b42017-09-26 13:47:31 +000038static Expr *CheckMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
44/// \brief Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000046 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000048 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// \brief Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000059class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000061 struct DSAVarData final {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataevf189cb72017-07-24 14:52:13 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataev8b427062016-05-25 12:36:08 +000073 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000075
Alexey Bataev758e55e2013-09-06 18:03:48 +000076private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000077 struct DSAInfo final {
78 OpenMPClauseKind Attributes = OMPC_unknown;
79 /// Pointer to a reference expression and a flag which shows that the
80 /// variable is marked as lastprivate(true) or not (false).
81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000083 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000084 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000086 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000088 /// Struct that associates a component with the clause kind where they are
89 /// found.
90 struct MappedExprComponentTy {
91 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92 OpenMPClauseKind Kind = OMPC_unknown;
93 };
94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000095 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000096 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000098 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +0000101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000115
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000116 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000117 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000118 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000119 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000120 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000121 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000123 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000127 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000129 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131 /// get the data (loop counters etc.) about enclosing loop-based construct.
132 /// This data is required during codegen.
133 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000134 /// \brief first argument (Expr *) contains optional argument of the
135 /// 'ordered' clause, the second one is true if the regions has 'ordered'
136 /// clause, false otherwise.
137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000138 bool NowaitRegion = false;
139 bool CancelRegion = false;
140 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000141 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000142 /// Reference to the taskgroup task_reduction reference expression.
143 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000145 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000148 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 };
150
Axel Naumann323862e2016-02-03 10:45:22 +0000151 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152
153 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000154 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000157 /// \brief true, if check for DSA must be from parent directive, false, if
158 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000159 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000160 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000161 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000162 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165
David Majnemer9d168222016-08-05 17:44:54 +0000166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000167
168 /// \brief Checks if the variable is a local for OpenMP region.
169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000170
Alexey Bataev4b465392017-04-26 15:06:24 +0000171 bool isStackEmpty() const {
172 return Stack.empty() ||
173 Stack.back().second != CurrentNonCapturingFunctionScope ||
174 Stack.back().first.empty();
175 }
176
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000178 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000179
Alexey Bataevaac108a2015-06-23 04:51:00 +0000180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000181 OpenMPClauseKind getClauseParsingMode() const {
182 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
183 return ClauseKindMode;
184 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000185 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000187 bool isForceVarCapturing() const { return ForceCapturing; }
188 void setForceVarCapturing(bool V) { ForceCapturing = V; }
189
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000191 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000192 if (Stack.empty() ||
193 Stack.back().second != CurrentNonCapturingFunctionScope)
194 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
195 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
196 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197 }
198
199 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000200 assert(!Stack.back().first.empty() &&
201 "Data-sharing attributes stack is empty!");
202 Stack.back().first.pop_back();
203 }
204
205 /// Start new OpenMP region stack in new non-capturing function.
206 void pushFunction() {
207 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
208 assert(!isa<CapturingScopeInfo>(CurFnScope));
209 CurrentNonCapturingFunctionScope = CurFnScope;
210 }
211 /// Pop region stack for non-capturing function.
212 void popFunction(const FunctionScopeInfo *OldFSI) {
213 if (!Stack.empty() && Stack.back().second == OldFSI) {
214 assert(Stack.back().first.empty());
215 Stack.pop_back();
216 }
217 CurrentNonCapturingFunctionScope = nullptr;
218 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
219 if (!isa<CapturingScopeInfo>(FSI)) {
220 CurrentNonCapturingFunctionScope = FSI;
221 break;
222 }
223 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000224 }
225
Alexey Bataev28c75412015-12-15 08:19:24 +0000226 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
227 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
228 }
229 const std::pair<OMPCriticalDirective *, llvm::APSInt>
230 getCriticalWithHint(const DeclarationNameInfo &Name) const {
231 auto I = Criticals.find(Name.getAsString());
232 if (I != Criticals.end())
233 return I->second;
234 return std::make_pair(nullptr, llvm::APSInt());
235 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000236 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000237 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000238 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000239 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000240
Alexey Bataev9c821032015-04-30 04:23:23 +0000241 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000242 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000243 /// \brief Check if the specified variable is a loop control variable for
244 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000245 /// \return The index of the loop control variable in the list of associated
246 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000247 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000248 /// \brief Check if the specified variable is a loop control variable for
249 /// parent region.
250 /// \return The index of the loop control variable in the list of associated
251 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000252 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000253 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
254 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000255 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000256
Alexey Bataev758e55e2013-09-06 18:03:48 +0000257 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000258 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
259 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000260
Alexey Bataevfa312f32017-07-21 18:48:21 +0000261 /// Adds additional information for the reduction items with the reduction id
262 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000265 /// Adds additional information for the reduction items with the reduction id
266 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000267 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
268 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000269 /// Returns the location and reduction operation from the innermost parent
270 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000271 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000272 BinaryOperatorKind &BOK,
273 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000274 /// Returns the location and reduction operation from the innermost parent
275 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000276 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000277 const Expr *&ReductionRef,
278 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000279 /// Return reduction reference expression for the current taskgroup.
280 Expr *getTaskgroupReductionRef() const {
281 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
282 "taskgroup reference expression requested for non taskgroup "
283 "directive.");
284 return Stack.back().first.back().TaskgroupReductionRef;
285 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000286 /// Checks if the given \p VD declaration is actually a taskgroup reduction
287 /// descriptor variable at the \p Level of OpenMP regions.
288 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
289 return Stack.back().first[Level].TaskgroupReductionRef &&
290 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
291 ->getDecl() == VD;
292 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000293
Alexey Bataev758e55e2013-09-06 18:03:48 +0000294 /// \brief Returns data sharing attributes from top of the stack for the
295 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000296 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000297 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000298 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000299 /// \brief Checks if the specified variables has data-sharing attributes which
300 /// match specified \a CPred predicate in any directive which matches \a DPred
301 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000302 DSAVarData hasDSA(ValueDecl *D,
303 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
304 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
305 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000306 /// \brief Checks if the specified variables has data-sharing attributes which
307 /// match specified \a CPred predicate in any innermost directive which
308 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000309 DSAVarData
310 hasInnermostDSA(ValueDecl *D,
311 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
312 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
313 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000314 /// \brief Checks if the specified variables has explicit data-sharing
315 /// attributes which match specified \a CPred predicate at the specified
316 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000317 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000318 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000319 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000320
321 /// \brief Returns true if the directive at level \Level matches in the
322 /// specified \a DPred predicate.
323 bool hasExplicitDirective(
324 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
325 unsigned Level);
326
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000327 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000328 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
329 const DeclarationNameInfo &,
330 SourceLocation)> &DPred,
331 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000332
Alexey Bataev758e55e2013-09-06 18:03:48 +0000333 /// \brief Returns currently analyzed directive.
334 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000336 }
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000337 /// \brief Returns directive kind at specified level.
338 OpenMPDirectiveKind getDirective(unsigned Level) const {
339 assert(!isStackEmpty() && "No directive at specified level.");
340 return Stack.back().first[Level].Directive;
341 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000342 /// \brief Returns parent directive.
343 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000344 if (isStackEmpty() || Stack.back().first.size() == 1)
345 return OMPD_unknown;
346 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000347 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000348
349 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000350 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000351 assert(!isStackEmpty());
352 Stack.back().first.back().DefaultAttr = DSA_none;
353 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000354 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000355 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000356 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000357 assert(!isStackEmpty());
358 Stack.back().first.back().DefaultAttr = DSA_shared;
359 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000360 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000361 /// Set default data mapping attribute to 'tofrom:scalar'.
362 void setDefaultDMAToFromScalar(SourceLocation Loc) {
363 assert(!isStackEmpty());
364 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
365 Stack.back().first.back().DefaultMapAttrLoc = Loc;
366 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000367
368 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000369 return isStackEmpty() ? DSA_unspecified
370 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000371 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000372 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000373 return isStackEmpty() ? SourceLocation()
374 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000375 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000376 DefaultMapAttributes getDefaultDMA() const {
377 return isStackEmpty() ? DMA_unspecified
378 : Stack.back().first.back().DefaultMapAttr;
379 }
380 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
381 return Stack.back().first[Level].DefaultMapAttr;
382 }
383 SourceLocation getDefaultDMALocation() const {
384 return isStackEmpty() ? SourceLocation()
385 : Stack.back().first.back().DefaultMapAttrLoc;
386 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000387
Alexey Bataevf29276e2014-06-18 04:14:57 +0000388 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000389 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000390 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000391 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000392 }
393
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000394 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000395 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000396 assert(!isStackEmpty());
397 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
398 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000399 }
400 /// \brief Returns true, if parent region is ordered (has associated
401 /// 'ordered' clause), false - otherwise.
402 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000403 if (isStackEmpty() || Stack.back().first.size() == 1)
404 return false;
405 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000406 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000407 /// \brief Returns optional parameter for the ordered region.
408 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000409 if (isStackEmpty() || Stack.back().first.size() == 1)
410 return nullptr;
411 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000412 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000413 /// \brief Marks current region as nowait (it has a 'nowait' clause).
414 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000415 assert(!isStackEmpty());
416 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000417 }
418 /// \brief Returns true, if parent region is nowait (has associated
419 /// 'nowait' clause), false - otherwise.
420 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000421 if (isStackEmpty() || Stack.back().first.size() == 1)
422 return false;
423 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000424 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000425 /// \brief Marks parent region as cancel region.
426 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 if (!isStackEmpty() && Stack.back().first.size() > 1) {
428 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
429 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
430 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000431 }
432 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000433 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000434 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000435 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000436
Alexey Bataev9c821032015-04-30 04:23:23 +0000437 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000438 void setAssociatedLoops(unsigned Val) {
439 assert(!isStackEmpty());
440 Stack.back().first.back().AssociatedLoops = Val;
441 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000442 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000443 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000444 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000445 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000446
Alexey Bataev13314bf2014-10-09 04:18:56 +0000447 /// \brief Marks current target region as one with closely nested teams
448 /// region.
449 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000450 if (!isStackEmpty() && Stack.back().first.size() > 1) {
451 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
452 TeamsRegionLoc;
453 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000454 }
455 /// \brief Returns true, if current region has closely nested teams region.
456 bool hasInnerTeamsRegion() const {
457 return getInnerTeamsRegionLoc().isValid();
458 }
459 /// \brief Returns location of the nested teams region (if any).
460 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000461 return isStackEmpty() ? SourceLocation()
462 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000463 }
464
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000465 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000466 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000467 }
468 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000469 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000470 }
471 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000472 return isStackEmpty() ? SourceLocation()
473 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000474 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000475
Samuel Antao4c8035b2016-12-12 18:00:20 +0000476 /// Do the check specified in \a Check to all component lists and return true
477 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000478 bool checkMappableExprComponentListsForDecl(
479 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000480 const llvm::function_ref<
481 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
482 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000483 if (isStackEmpty())
484 return false;
485 auto SI = Stack.back().first.rbegin();
486 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000487
488 if (SI == SE)
489 return false;
490
491 if (CurrentRegionOnly) {
492 SE = std::next(SI);
493 } else {
494 ++SI;
495 }
496
497 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000498 auto MI = SI->MappedExprComponents.find(VD);
499 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000500 for (auto &L : MI->second.Components)
501 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000502 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000503 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000504 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000505 }
506
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000507 /// Do the check specified in \a Check to all component lists at a given level
508 /// and return true if any issue is found.
509 bool checkMappableExprComponentListsForDeclAtLevel(
510 ValueDecl *VD, unsigned Level,
511 const llvm::function_ref<
512 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
513 OpenMPClauseKind)> &Check) {
514 if (isStackEmpty())
515 return false;
516
517 auto StartI = Stack.back().first.begin();
518 auto EndI = Stack.back().first.end();
519 if (std::distance(StartI, EndI) <= (int)Level)
520 return false;
521 std::advance(StartI, Level);
522
523 auto MI = StartI->MappedExprComponents.find(VD);
524 if (MI != StartI->MappedExprComponents.end())
525 for (auto &L : MI->second.Components)
526 if (Check(L, MI->second.Kind))
527 return true;
528 return false;
529 }
530
Samuel Antao4c8035b2016-12-12 18:00:20 +0000531 /// Create a new mappable expression component list associated with a given
532 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000533 void addMappableExpressionComponents(
534 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000535 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
536 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000537 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000538 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000539 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000540 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000541 MEC.Components.resize(MEC.Components.size() + 1);
542 MEC.Components.back().append(Components.begin(), Components.end());
543 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000544 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000545
546 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000547 assert(!isStackEmpty());
548 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000549 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000550 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000551 assert(!isStackEmpty() && Stack.back().first.size() > 1);
552 auto &StackElem = *std::next(Stack.back().first.rbegin());
553 assert(isOpenMPWorksharingDirective(StackElem.Directive));
554 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000555 }
556 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
557 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000558 assert(!isStackEmpty());
559 auto &StackElem = Stack.back().first.back();
560 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
561 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000562 return llvm::make_range(Ref.begin(), Ref.end());
563 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000564 return llvm::make_range(StackElem.DoacrossDepends.end(),
565 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000566 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000567};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000568bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000569 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
570 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000571}
Alexey Bataeved09d242014-05-28 05:53:51 +0000572} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000574static Expr *getExprAsWritten(Expr *E) {
575 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
576 E = ExprTemp->getSubExpr();
577
578 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
579 E = MTE->GetTemporaryExpr();
580
581 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
582 E = Binder->getSubExpr();
583
584 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
585 E = ICE->getSubExprAsWritten();
586 return E->IgnoreParens();
587}
588
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000589static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000590 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
591 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
592 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000593 auto *VD = dyn_cast<VarDecl>(D);
594 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000595 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000596 VD = VD->getCanonicalDecl();
597 D = VD;
598 } else {
599 assert(FD);
600 FD = FD->getCanonicalDecl();
601 D = FD;
602 }
603 return D;
604}
605
David Majnemer9d168222016-08-05 17:44:54 +0000606DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000607 ValueDecl *D) {
608 D = getCanonicalDecl(D);
609 auto *VD = dyn_cast<VarDecl>(D);
610 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000611 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000612 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000613 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
614 // in a region but not in construct]
615 // File-scope or namespace-scope variables referenced in called routines
616 // in the region are shared unless they appear in a threadprivate
617 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000618 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000619 DVar.CKind = OMPC_shared;
620
621 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
622 // in a region but not in construct]
623 // Variables with static storage duration that are declared in called
624 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000625 if (VD && VD->hasGlobalStorage())
626 DVar.CKind = OMPC_shared;
627
628 // Non-static data members are shared by default.
629 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000630 DVar.CKind = OMPC_shared;
631
Alexey Bataev758e55e2013-09-06 18:03:48 +0000632 return DVar;
633 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000634
Alexey Bataevec3da872014-01-31 05:15:34 +0000635 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
636 // in a Construct, C/C++, predetermined, p.1]
637 // Variables with automatic storage duration that are declared in a scope
638 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000639 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
640 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000641 DVar.CKind = OMPC_private;
642 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000643 }
644
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000645 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000646 // Explicitly specified attributes and local variables with predetermined
647 // attributes.
648 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000649 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000650 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000651 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000652 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000653 return DVar;
654 }
655
656 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
657 // in a Construct, C/C++, implicitly determined, p.1]
658 // In a parallel or task construct, the data-sharing attributes of these
659 // variables are determined by the default clause, if present.
660 switch (Iter->DefaultAttr) {
661 case DSA_shared:
662 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000664 return DVar;
665 case DSA_none:
666 return DVar;
667 case DSA_unspecified:
668 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
669 // in a Construct, implicitly determined, p.2]
670 // In a parallel construct, if no default clause is present, these
671 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000672 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000673 if (isOpenMPParallelDirective(DVar.DKind) ||
674 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000675 DVar.CKind = OMPC_shared;
676 return DVar;
677 }
678
679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680 // in a Construct, implicitly determined, p.4]
681 // In a task construct, if no default clause is present, a variable that in
682 // the enclosing context is determined to be shared by all implicit tasks
683 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000684 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000685 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000686 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000687 do {
688 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000689 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000690 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691 // In a task construct, if no default clause is present, a variable
692 // whose data-sharing attribute is not determined by the rules above is
693 // firstprivate.
694 DVarTemp = getDSA(I, D);
695 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000696 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000697 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000698 return DVar;
699 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000700 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000701 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000702 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000703 return DVar;
704 }
705 }
706 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
707 // in a Construct, implicitly determined, p.3]
708 // For constructs other than task, if no default clause is present, these
709 // variables inherit their data-sharing attributes from the enclosing
710 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000711 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000712}
713
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000714Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000715 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000716 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000717 auto &StackElem = Stack.back().first.back();
718 auto It = StackElem.AlignedMap.find(D);
719 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000720 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000721 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000722 return nullptr;
723 } else {
724 assert(It->second && "Unexpected nullptr expr in the aligned map");
725 return It->second;
726 }
727 return nullptr;
728}
729
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000730void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000731 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000732 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000733 auto &StackElem = Stack.back().first.back();
734 StackElem.LCVMap.insert(
735 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000736}
737
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000738DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000739 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000740 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000741 auto &StackElem = Stack.back().first.back();
742 auto It = StackElem.LCVMap.find(D);
743 if (It != StackElem.LCVMap.end())
744 return It->second;
745 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000746}
747
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000748DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000749 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
750 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000751 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000752 auto &StackElem = *std::next(Stack.back().first.rbegin());
753 auto It = StackElem.LCVMap.find(D);
754 if (It != StackElem.LCVMap.end())
755 return It->second;
756 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000757}
758
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000759ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000760 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
761 "Data-sharing attributes stack is empty");
762 auto &StackElem = *std::next(Stack.back().first.rbegin());
763 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000764 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000765 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000766 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000767 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000768 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000769}
770
Alexey Bataev90c228f2016-02-08 09:29:13 +0000771void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
772 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000773 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000774 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000775 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000776 Data.Attributes = A;
777 Data.RefExpr.setPointer(E);
778 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000779 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000780 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
781 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000782 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
783 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
784 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
785 (isLoopControlVariable(D).first && A == OMPC_private));
786 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
787 Data.RefExpr.setInt(/*IntVal=*/true);
788 return;
789 }
790 const bool IsLastprivate =
791 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
792 Data.Attributes = A;
793 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
794 Data.PrivateCopy = PrivateCopy;
795 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000796 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000797 Data.Attributes = A;
798 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
799 Data.PrivateCopy = nullptr;
800 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000801 }
802}
803
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000804/// \brief Build a variable declaration for OpenMP loop iteration variable.
805static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
806 StringRef Name, const AttrVec *Attrs = nullptr) {
807 DeclContext *DC = SemaRef.CurContext;
808 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
809 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
810 VarDecl *Decl =
811 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
812 if (Attrs) {
813 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
814 I != E; ++I)
815 Decl->addAttr(*I);
816 }
817 Decl->setImplicit();
818 return Decl;
819}
820
821static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
822 SourceLocation Loc,
823 bool RefersToCapture = false) {
824 D->setReferenced();
825 D->markUsed(S.Context);
826 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
827 SourceLocation(), D, RefersToCapture, Loc, Ty,
828 VK_LValue);
829}
830
831void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
832 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000833 D = getCanonicalDecl(D);
834 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000835 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000836 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000837 "Additional reduction info may be specified only for reduction items.");
838 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
839 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000840 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000841 "Additional reduction info may be specified only once for reduction "
842 "items.");
843 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000844 Expr *&TaskgroupReductionRef =
845 Stack.back().first.back().TaskgroupReductionRef;
846 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000847 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000848 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000849 TaskgroupReductionRef =
850 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000851 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000852}
853
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000854void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
855 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000856 D = getCanonicalDecl(D);
857 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000858 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000859 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000860 "Additional reduction info may be specified only for reduction items.");
861 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
862 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000863 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000864 "Additional reduction info may be specified only once for reduction "
865 "items.");
866 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000867 Expr *&TaskgroupReductionRef =
868 Stack.back().first.back().TaskgroupReductionRef;
869 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000870 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
871 ".task_red.");
872 TaskgroupReductionRef =
873 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000874 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000875}
876
Alexey Bataevf189cb72017-07-24 14:52:13 +0000877DSAStackTy::DSAVarData
878DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000879 BinaryOperatorKind &BOK,
880 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000881 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000882 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
883 if (Stack.back().first.empty())
884 return DSAVarData();
885 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 E = Stack.back().first.rend();
887 I != E; std::advance(I, 1)) {
888 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000889 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000890 continue;
891 auto &ReductionData = I->ReductionMap[D];
892 if (!ReductionData.ReductionOp ||
893 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000894 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000895 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000896 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000897 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
898 "expression for the descriptor is not "
899 "set.");
900 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000901 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
902 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000903 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000904 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000905}
906
Alexey Bataevf189cb72017-07-24 14:52:13 +0000907DSAStackTy::DSAVarData
908DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000909 const Expr *&ReductionRef,
910 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000911 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000912 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
913 if (Stack.back().first.empty())
914 return DSAVarData();
915 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000916 E = Stack.back().first.rend();
917 I != E; std::advance(I, 1)) {
918 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000919 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000920 continue;
921 auto &ReductionData = I->ReductionMap[D];
922 if (!ReductionData.ReductionOp ||
923 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000924 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000925 SR = ReductionData.ReductionRange;
926 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000927 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
928 "expression for the descriptor is not "
929 "set.");
930 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000931 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
932 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000933 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000934 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000935}
936
Alexey Bataeved09d242014-05-28 05:53:51 +0000937bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000938 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +0000939 if (!isStackEmpty()) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000940 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000941 Scope *TopScope = nullptr;
Alexey Bataev852525d2018-03-02 17:17:12 +0000942 while (I != E && !isParallelOrTaskRegion(I->Directive) &&
943 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000944 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000945 if (I == E)
946 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000947 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000948 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000949 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000950 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000951 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000952 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000953 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000954}
955
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000956DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
957 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000958 DSAVarData DVar;
959
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000960 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000961 auto TI = Threadprivates.find(D);
962 if (TI != Threadprivates.end()) {
963 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000964 DVar.CKind = OMPC_threadprivate;
965 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000966 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
967 DVar.RefExpr = buildDeclRefExpr(
968 SemaRef, VD, D->getType().getNonReferenceType(),
969 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
970 DVar.CKind = OMPC_threadprivate;
971 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +0000972 return DVar;
973 }
974 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
975 // in a Construct, C/C++, predetermined, p.1]
976 // Variables appearing in threadprivate directives are threadprivate.
977 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
978 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
979 SemaRef.getLangOpts().OpenMPUseTLS &&
980 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
981 (VD && VD->getStorageClass() == SC_Register &&
982 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
983 DVar.RefExpr = buildDeclRefExpr(
984 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
985 DVar.CKind = OMPC_threadprivate;
986 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
987 return DVar;
988 }
989 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
990 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
991 !isLoopControlVariable(D).first) {
992 auto IterTarget =
993 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
994 [](const SharingMapTy &Data) {
995 return isOpenMPTargetExecutionDirective(Data.Directive);
996 });
997 if (IterTarget != Stack.back().first.rend()) {
998 auto ParentIterTarget = std::next(IterTarget, 1);
999 auto Iter = Stack.back().first.rbegin();
1000 while (Iter != ParentIterTarget) {
1001 if (isOpenMPLocal(VD, Iter)) {
1002 DVar.RefExpr =
1003 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1004 D->getLocation());
1005 DVar.CKind = OMPC_threadprivate;
1006 return DVar;
1007 }
1008 std::advance(Iter, 1);
1009 }
1010 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1011 auto DSAIter = IterTarget->SharingMap.find(D);
1012 if (DSAIter != IterTarget->SharingMap.end() &&
1013 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1014 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1015 DVar.CKind = OMPC_threadprivate;
1016 return DVar;
1017 } else if (!SemaRef.IsOpenMPCapturedByRef(
1018 D, std::distance(ParentIterTarget,
1019 Stack.back().first.rend()))) {
1020 DVar.RefExpr =
1021 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1022 IterTarget->ConstructLoc);
1023 DVar.CKind = OMPC_threadprivate;
1024 return DVar;
1025 }
1026 }
1027 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001028 }
1029
Alexey Bataev4b465392017-04-26 15:06:24 +00001030 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001031 // Not in OpenMP execution region and top scope was already checked.
1032 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001033
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001035 // in a Construct, C/C++, predetermined, p.4]
1036 // Static data members are shared.
1037 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1038 // in a Construct, C/C++, predetermined, p.7]
1039 // Variables with static storage duration that are declared in a scope
1040 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001041 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001042 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001043 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001044 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001045 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001046
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001047 DVar.CKind = OMPC_shared;
1048 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001049 }
1050
1051 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00001052 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1053 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1055 // in a Construct, C/C++, predetermined, p.6]
1056 // Variables with const qualified type having no mutable member are
1057 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001058 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001059 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001060 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1061 if (auto *CTD = CTSD->getSpecializedTemplate())
1062 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001063 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001064 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1065 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001066 // Variables with const-qualified type having no mutable member may be
1067 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001068 DSAVarData DVarTemp = hasDSA(
1069 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1070 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001071 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
Alexey Bataev9a757382018-02-16 19:16:54 +00001072 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001073
Alexey Bataev758e55e2013-09-06 18:03:48 +00001074 DVar.CKind = OMPC_shared;
1075 return DVar;
1076 }
1077
Alexey Bataev758e55e2013-09-06 18:03:48 +00001078 // Explicitly specified attributes and local variables with predetermined
1079 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001080 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001081 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001082 if (FromParent && I != EndI)
1083 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001084 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001085 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001086 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001087 DVar.CKind = I->SharingMap[D].Attributes;
1088 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001089 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001090 }
1091
1092 return DVar;
1093}
1094
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001095DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1096 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001097 if (isStackEmpty()) {
1098 StackTy::reverse_iterator I;
1099 return getDSA(I, D);
1100 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001101 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 auto StartI = Stack.back().first.rbegin();
1103 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001104 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001105 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001106 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001107}
1108
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001109DSAStackTy::DSAVarData
1110DSAStackTy::hasDSA(ValueDecl *D,
1111 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1112 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1113 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001114 if (isStackEmpty())
1115 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001116 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001117 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001118 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001119 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001120 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001121 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001122 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001123 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001124 auto NewI = I;
1125 DSAVarData DVar = getDSA(NewI, D);
1126 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001127 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001128 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001129 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001130}
1131
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001132DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1133 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1134 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1135 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001136 if (isStackEmpty())
1137 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001138 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001139 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001140 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001141 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001142 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001143 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001144 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001145 auto NewI = StartI;
1146 DSAVarData DVar = getDSA(NewI, D);
1147 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001148}
1149
Alexey Bataevaac108a2015-06-23 04:51:00 +00001150bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001151 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001152 unsigned Level, bool NotLastprivate) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001153 if (isStackEmpty())
1154 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001155 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001156 auto StartI = Stack.back().first.begin();
1157 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001158 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001159 return false;
1160 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001161 return (StartI->SharingMap.count(D) > 0) &&
1162 StartI->SharingMap[D].RefExpr.getPointer() &&
1163 CPred(StartI->SharingMap[D].Attributes) &&
1164 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001165}
1166
Samuel Antao4be30e92015-10-02 17:14:03 +00001167bool DSAStackTy::hasExplicitDirective(
1168 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1169 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001170 if (isStackEmpty())
1171 return false;
1172 auto StartI = Stack.back().first.begin();
1173 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001174 if (std::distance(StartI, EndI) <= (int)Level)
1175 return false;
1176 std::advance(StartI, Level);
1177 return DPred(StartI->Directive);
1178}
1179
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001180bool DSAStackTy::hasDirective(
1181 const llvm::function_ref<bool(OpenMPDirectiveKind,
1182 const DeclarationNameInfo &, SourceLocation)>
1183 &DPred,
1184 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001185 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001186 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001187 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001188 auto StartI = std::next(Stack.back().first.rbegin());
1189 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001190 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001191 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001192 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1193 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1194 return true;
1195 }
1196 return false;
1197}
1198
Alexey Bataev758e55e2013-09-06 18:03:48 +00001199void Sema::InitDataSharingAttributesStack() {
1200 VarDataSharingAttributesStack = new DSAStackTy(*this);
1201}
1202
1203#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1204
Alexey Bataev4b465392017-04-26 15:06:24 +00001205void Sema::pushOpenMPFunctionRegion() {
1206 DSAStack->pushFunction();
1207}
1208
1209void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1210 DSAStack->popFunction(OldFSI);
1211}
1212
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001213bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001214 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1215
1216 auto &Ctx = getASTContext();
1217 bool IsByRef = true;
1218
1219 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001220 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001221 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001222
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001223 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001224 // This table summarizes how a given variable should be passed to the device
1225 // given its type and the clauses where it appears. This table is based on
1226 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1227 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1228 //
1229 // =========================================================================
1230 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1231 // | |(tofrom:scalar)| | pvt | | | |
1232 // =========================================================================
1233 // | scl | | | | - | | bycopy|
1234 // | scl | | - | x | - | - | bycopy|
1235 // | scl | | x | - | - | - | null |
1236 // | scl | x | | | - | | byref |
1237 // | scl | x | - | x | - | - | bycopy|
1238 // | scl | x | x | - | - | - | null |
1239 // | scl | | - | - | - | x | byref |
1240 // | scl | x | - | - | - | x | byref |
1241 //
1242 // | agg | n.a. | | | - | | byref |
1243 // | agg | n.a. | - | x | - | - | byref |
1244 // | agg | n.a. | x | - | - | - | null |
1245 // | agg | n.a. | - | - | - | x | byref |
1246 // | agg | n.a. | - | - | - | x[] | byref |
1247 //
1248 // | ptr | n.a. | | | - | | bycopy|
1249 // | ptr | n.a. | - | x | - | - | bycopy|
1250 // | ptr | n.a. | x | - | - | - | null |
1251 // | ptr | n.a. | - | - | - | x | byref |
1252 // | ptr | n.a. | - | - | - | x[] | bycopy|
1253 // | ptr | n.a. | - | - | x | | bycopy|
1254 // | ptr | n.a. | - | - | x | x | bycopy|
1255 // | ptr | n.a. | - | - | x | x[] | bycopy|
1256 // =========================================================================
1257 // Legend:
1258 // scl - scalar
1259 // ptr - pointer
1260 // agg - aggregate
1261 // x - applies
1262 // - - invalid in this combination
1263 // [] - mapped with an array section
1264 // byref - should be mapped by reference
1265 // byval - should be mapped by value
1266 // null - initialize a local variable to null on the device
1267 //
1268 // Observations:
1269 // - All scalar declarations that show up in a map clause have to be passed
1270 // by reference, because they may have been mapped in the enclosing data
1271 // environment.
1272 // - If the scalar value does not fit the size of uintptr, it has to be
1273 // passed by reference, regardless the result in the table above.
1274 // - For pointers mapped by value that have either an implicit map or an
1275 // array section, the runtime library may pass the NULL value to the
1276 // device instead of the value passed to it by the compiler.
1277
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001278 if (Ty->isReferenceType())
1279 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001280
1281 // Locate map clauses and see if the variable being captured is referred to
1282 // in any of those clauses. Here we only care about variables, not fields,
1283 // because fields are part of aggregates.
1284 bool IsVariableUsedInMapClause = false;
1285 bool IsVariableAssociatedWithSection = false;
1286
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001287 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1288 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001289 MapExprComponents,
1290 OpenMPClauseKind WhereFoundClauseKind) {
1291 // Only the map clause information influences how a variable is
1292 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001293 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001294 if (WhereFoundClauseKind != OMPC_map)
1295 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001296
1297 auto EI = MapExprComponents.rbegin();
1298 auto EE = MapExprComponents.rend();
1299
1300 assert(EI != EE && "Invalid map expression!");
1301
1302 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1303 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1304
1305 ++EI;
1306 if (EI == EE)
1307 return false;
1308
1309 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1310 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1311 isa<MemberExpr>(EI->getAssociatedExpression())) {
1312 IsVariableAssociatedWithSection = true;
1313 // There is nothing more we need to know about this variable.
1314 return true;
1315 }
1316
1317 // Keep looking for more map info.
1318 return false;
1319 });
1320
1321 if (IsVariableUsedInMapClause) {
1322 // If variable is identified in a map clause it is always captured by
1323 // reference except if it is a pointer that is dereferenced somehow.
1324 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1325 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001326 // By default, all the data that has a scalar type is mapped by copy
1327 // (except for reduction variables).
1328 IsByRef =
1329 !Ty->isScalarType() ||
1330 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1331 DSAStack->hasExplicitDSA(
1332 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001333 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001334 }
1335
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001336 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001337 IsByRef =
1338 !DSAStack->hasExplicitDSA(
1339 D,
1340 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1341 Level, /*NotLastprivate=*/true) &&
1342 // If the variable is artificial and must be captured by value - try to
1343 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001344 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1345 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001346 }
1347
Samuel Antao86ace552016-04-27 22:40:57 +00001348 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001349 // and alignment, because the runtime library only deals with uintptr types.
1350 // If it does not fit the uintptr size, we need to pass the data by reference
1351 // instead.
1352 if (!IsByRef &&
1353 (Ctx.getTypeSizeInChars(Ty) >
1354 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001355 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001356 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001357 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001358
1359 return IsByRef;
1360}
1361
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001362unsigned Sema::getOpenMPNestingLevel() const {
1363 assert(getLangOpts().OpenMP);
1364 return DSAStack->getNestingLevel();
1365}
1366
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001367bool Sema::isInOpenMPTargetExecutionDirective() const {
1368 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1369 !DSAStack->isClauseParsingMode()) ||
1370 DSAStack->hasDirective(
1371 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1372 SourceLocation) -> bool {
1373 return isOpenMPTargetExecutionDirective(K);
1374 },
1375 false);
1376}
1377
Alexey Bataev90c228f2016-02-08 09:29:13 +00001378VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001379 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001380 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001381
1382 // If we are attempting to capture a global variable in a directive with
1383 // 'target' we return true so that this global is also mapped to the device.
1384 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001385 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001386 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) {
1387 // If the declaration is enclosed in a 'declare target' directive,
1388 // then it should not be captured.
1389 //
1390 for (const auto *Var = VD->getMostRecentDecl(); Var;
1391 Var = Var->getPreviousDecl())
1392 if (Var->hasAttr<OMPDeclareTargetDeclAttr>())
1393 return nullptr;
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001394 return VD;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001395 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001396
Alexey Bataev48977c32015-08-04 08:10:48 +00001397 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1398 (!DSAStack->isClauseParsingMode() ||
1399 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001400 auto &&Info = DSAStack->isLoopControlVariable(D);
1401 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001402 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001403 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001404 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001405 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001406 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001407 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001408 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001409 DVarPrivate = DSAStack->hasDSA(
1410 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1411 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001412 if (DVarPrivate.CKind != OMPC_unknown)
1413 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001414 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001415 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001416}
1417
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001418void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1419 unsigned Level) const {
1420 SmallVector<OpenMPDirectiveKind, 4> Regions;
1421 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1422 FunctionScopesIndex -= Regions.size();
1423}
1424
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001425bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001426 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1427 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001428 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1429 Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001430 (DSAStack->isClauseParsingMode() &&
1431 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001432 // Consider taskgroup reduction descriptor variable a private to avoid
1433 // possible capture in the region.
1434 (DSAStack->hasExplicitDirective(
1435 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1436 Level) &&
1437 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001438}
1439
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001440void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1441 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1442 D = getCanonicalDecl(D);
1443 OpenMPClauseKind OMPC = OMPC_unknown;
1444 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1445 const unsigned NewLevel = I - 1;
1446 if (DSAStack->hasExplicitDSA(D,
1447 [&OMPC](const OpenMPClauseKind K) {
1448 if (isOpenMPPrivate(K)) {
1449 OMPC = K;
1450 return true;
1451 }
1452 return false;
1453 },
1454 NewLevel))
1455 break;
1456 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1457 D, NewLevel,
1458 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1459 OpenMPClauseKind) { return true; })) {
1460 OMPC = OMPC_map;
1461 break;
1462 }
1463 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1464 NewLevel)) {
1465 OMPC = OMPC_firstprivate;
1466 break;
1467 }
1468 }
1469 if (OMPC != OMPC_unknown)
1470 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1471}
1472
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001473bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001474 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1475 // Return true if the current level is no longer enclosed in a target region.
1476
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001477 auto *VD = dyn_cast<VarDecl>(D);
1478 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001479 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1480 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001481}
1482
Alexey Bataeved09d242014-05-28 05:53:51 +00001483void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484
1485void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1486 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001487 Scope *CurScope, SourceLocation Loc) {
1488 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001489 PushExpressionEvaluationContext(
1490 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001491}
1492
Alexey Bataevaac108a2015-06-23 04:51:00 +00001493void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1494 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001495}
1496
Alexey Bataevaac108a2015-06-23 04:51:00 +00001497void Sema::EndOpenMPClause() {
1498 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001499}
1500
Alexey Bataev758e55e2013-09-06 18:03:48 +00001501void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001502 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1503 // A variable of class type (or array thereof) that appears in a lastprivate
1504 // clause requires an accessible, unambiguous default constructor for the
1505 // class type, unless the list item is also specified in a firstprivate
1506 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001507 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001508 for (auto *C : D->clauses()) {
1509 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1510 SmallVector<Expr *, 8> PrivateCopies;
1511 for (auto *DE : Clause->varlists()) {
1512 if (DE->isValueDependent() || DE->isTypeDependent()) {
1513 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001514 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001515 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001516 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001517 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1518 QualType Type = VD->getType().getNonReferenceType();
1519 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001520 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001521 // Generate helper private variable and initialize it with the
1522 // default value. The address of the original variable is replaced
1523 // by the address of the new private variable in CodeGen. This new
1524 // variable is not added to IdResolver, so the code in the OpenMP
1525 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001526 auto *VDPrivate = buildVarDecl(
1527 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001528 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001529 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001530 if (VDPrivate->isInvalidDecl())
1531 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001532 PrivateCopies.push_back(buildDeclRefExpr(
1533 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001534 } else {
1535 // The variable is also a firstprivate, so initialization sequence
1536 // for private copy is generated already.
1537 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001538 }
1539 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001540 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001541 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001542 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001543 }
1544 }
1545 }
1546
Alexey Bataev758e55e2013-09-06 18:03:48 +00001547 DSAStack->pop();
1548 DiscardCleanupsInEvaluationContext();
1549 PopExpressionEvaluationContext();
1550}
1551
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001552static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1553 Expr *NumIterations, Sema &SemaRef,
1554 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001555
Alexey Bataeva769e072013-03-22 06:34:35 +00001556namespace {
1557
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001558class VarDeclFilterCCC : public CorrectionCandidateCallback {
1559private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001560 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001561
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001562public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001563 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001564 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001565 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001566 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001567 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001568 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1569 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001570 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001571 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001572 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001573};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001574
1575class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1576private:
1577 Sema &SemaRef;
1578
1579public:
1580 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1581 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1582 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001583 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001584 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1585 SemaRef.getCurScope());
1586 }
1587 return false;
1588 }
1589};
1590
Alexey Bataeved09d242014-05-28 05:53:51 +00001591} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001592
1593ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1594 CXXScopeSpec &ScopeSpec,
1595 const DeclarationNameInfo &Id) {
1596 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1597 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1598
1599 if (Lookup.isAmbiguous())
1600 return ExprError();
1601
1602 VarDecl *VD;
1603 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001604 if (TypoCorrection Corrected = CorrectTypo(
1605 Id, LookupOrdinaryName, CurScope, nullptr,
1606 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001607 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001608 PDiag(Lookup.empty()
1609 ? diag::err_undeclared_var_use_suggest
1610 : diag::err_omp_expected_var_arg_suggest)
1611 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001612 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001613 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001614 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1615 : diag::err_omp_expected_var_arg)
1616 << Id.getName();
1617 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001618 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001619 } else {
1620 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001621 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001622 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1623 return ExprError();
1624 }
1625 }
1626 Lookup.suppressDiagnostics();
1627
1628 // OpenMP [2.9.2, Syntax, C/C++]
1629 // Variables must be file-scope, namespace-scope, or static block-scope.
1630 if (!VD->hasGlobalStorage()) {
1631 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001632 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1633 bool IsDecl =
1634 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001635 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001636 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1637 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001638 return ExprError();
1639 }
1640
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001641 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001642 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001643 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1644 // A threadprivate directive for file-scope variables must appear outside
1645 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001646 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1647 !getCurLexicalContext()->isTranslationUnit()) {
1648 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001649 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1650 bool IsDecl =
1651 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1652 Diag(VD->getLocation(),
1653 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1654 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001655 return ExprError();
1656 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001657 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1658 // A threadprivate directive for static class member variables must appear
1659 // in the class definition, in the same scope in which the member
1660 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001661 if (CanonicalVD->isStaticDataMember() &&
1662 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1663 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001664 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1665 bool IsDecl =
1666 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1667 Diag(VD->getLocation(),
1668 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1669 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001670 return ExprError();
1671 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001672 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1673 // A threadprivate directive for namespace-scope variables must appear
1674 // outside any definition or declaration other than the namespace
1675 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001676 if (CanonicalVD->getDeclContext()->isNamespace() &&
1677 (!getCurLexicalContext()->isFileContext() ||
1678 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1679 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001680 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1681 bool IsDecl =
1682 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1683 Diag(VD->getLocation(),
1684 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1685 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001686 return ExprError();
1687 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001688 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1689 // A threadprivate directive for static block-scope variables must appear
1690 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001691 if (CanonicalVD->isStaticLocal() && CurScope &&
1692 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001693 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001694 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1695 bool IsDecl =
1696 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1697 Diag(VD->getLocation(),
1698 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1699 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001700 return ExprError();
1701 }
1702
1703 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1704 // A threadprivate directive must lexically precede all references to any
1705 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001706 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001707 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001708 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001709 return ExprError();
1710 }
1711
1712 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001713 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1714 SourceLocation(), VD,
1715 /*RefersToEnclosingVariableOrCapture=*/false,
1716 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001717}
1718
Alexey Bataeved09d242014-05-28 05:53:51 +00001719Sema::DeclGroupPtrTy
1720Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1721 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001722 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001723 CurContext->addDecl(D);
1724 return DeclGroupPtrTy::make(DeclGroupRef(D));
1725 }
David Blaikie0403cb12016-01-15 23:43:25 +00001726 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001727}
1728
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001729namespace {
1730class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1731 Sema &SemaRef;
1732
1733public:
1734 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001735 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001736 if (VD->hasLocalStorage()) {
1737 SemaRef.Diag(E->getLocStart(),
1738 diag::err_omp_local_var_in_threadprivate_init)
1739 << E->getSourceRange();
1740 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1741 << VD << VD->getSourceRange();
1742 return true;
1743 }
1744 }
1745 return false;
1746 }
1747 bool VisitStmt(const Stmt *S) {
1748 for (auto Child : S->children()) {
1749 if (Child && Visit(Child))
1750 return true;
1751 }
1752 return false;
1753 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001754 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001755};
1756} // namespace
1757
Alexey Bataeved09d242014-05-28 05:53:51 +00001758OMPThreadPrivateDecl *
1759Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001760 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001761 for (auto &RefExpr : VarList) {
1762 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001763 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1764 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001765
Alexey Bataev376b4a42016-02-09 09:41:09 +00001766 // Mark variable as used.
1767 VD->setReferenced();
1768 VD->markUsed(Context);
1769
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001770 QualType QType = VD->getType();
1771 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1772 // It will be analyzed later.
1773 Vars.push_back(DE);
1774 continue;
1775 }
1776
Alexey Bataeva769e072013-03-22 06:34:35 +00001777 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1778 // A threadprivate variable must not have an incomplete type.
1779 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001780 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001781 continue;
1782 }
1783
1784 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1785 // A threadprivate variable must not have a reference type.
1786 if (VD->getType()->isReferenceType()) {
1787 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001788 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1789 bool IsDecl =
1790 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1791 Diag(VD->getLocation(),
1792 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1793 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001794 continue;
1795 }
1796
Samuel Antaof8b50122015-07-13 22:54:53 +00001797 // Check if this is a TLS variable. If TLS is not being supported, produce
1798 // the corresponding diagnostic.
1799 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1800 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1801 getLangOpts().OpenMPUseTLS &&
1802 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001803 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1804 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001805 Diag(ILoc, diag::err_omp_var_thread_local)
1806 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001807 bool IsDecl =
1808 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1809 Diag(VD->getLocation(),
1810 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1811 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001812 continue;
1813 }
1814
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001815 // Check if initial value of threadprivate variable reference variable with
1816 // local storage (it is not supported by runtime).
1817 if (auto Init = VD->getAnyInitializer()) {
1818 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001819 if (Checker.Visit(Init))
1820 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001821 }
1822
Alexey Bataeved09d242014-05-28 05:53:51 +00001823 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001824 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001825 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1826 Context, SourceRange(Loc, Loc)));
1827 if (auto *ML = Context.getASTMutationListener())
1828 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001829 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001830 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001831 if (!Vars.empty()) {
1832 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1833 Vars);
1834 D->setAccess(AS_public);
1835 }
1836 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001837}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001838
Alexey Bataev7ff55242014-06-19 09:13:45 +00001839static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001840 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001841 bool IsLoopIterVar = false) {
1842 if (DVar.RefExpr) {
1843 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1844 << getOpenMPClauseName(DVar.CKind);
1845 return;
1846 }
1847 enum {
1848 PDSA_StaticMemberShared,
1849 PDSA_StaticLocalVarShared,
1850 PDSA_LoopIterVarPrivate,
1851 PDSA_LoopIterVarLinear,
1852 PDSA_LoopIterVarLastprivate,
1853 PDSA_ConstVarShared,
1854 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001855 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001856 PDSA_LocalVarPrivate,
1857 PDSA_Implicit
1858 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001859 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001860 auto ReportLoc = D->getLocation();
1861 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001862 if (IsLoopIterVar) {
1863 if (DVar.CKind == OMPC_private)
1864 Reason = PDSA_LoopIterVarPrivate;
1865 else if (DVar.CKind == OMPC_lastprivate)
1866 Reason = PDSA_LoopIterVarLastprivate;
1867 else
1868 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001869 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1870 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001871 Reason = PDSA_TaskVarFirstprivate;
1872 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001873 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001874 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001875 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001876 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001877 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001878 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001879 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001880 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001881 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001882 ReportHint = true;
1883 Reason = PDSA_LocalVarPrivate;
1884 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001885 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001886 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001887 << Reason << ReportHint
1888 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1889 } else if (DVar.ImplicitDSALoc.isValid()) {
1890 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1891 << getOpenMPClauseName(DVar.CKind);
1892 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001893}
1894
Alexey Bataev758e55e2013-09-06 18:03:48 +00001895namespace {
1896class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1897 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001898 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001899 bool ErrorFound;
1900 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001901 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001902 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001903 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001904 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001905
Alexey Bataev758e55e2013-09-06 18:03:48 +00001906public:
1907 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001908 if (E->isTypeDependent() || E->isValueDependent() ||
1909 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1910 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001911 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001912 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001913 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001914 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001915 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001916
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001917 auto DVar = Stack->getTopDSA(VD, false);
1918 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001919 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001920 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001921
Alexey Bataevafe50572017-10-06 17:00:28 +00001922 // Skip internally declared static variables.
1923 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1924 return;
1925
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001926 auto ELoc = E->getExprLoc();
1927 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001928 // The default(none) clause requires that each variable that is referenced
1929 // in the construct, and does not have a predetermined data-sharing
1930 // attribute, must have its data-sharing attribute explicitly determined
1931 // by being listed in a data-sharing attribute clause.
1932 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001933 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001934 VarsWithInheritedDSA.count(VD) == 0) {
1935 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001936 return;
1937 }
1938
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001939 if (isOpenMPTargetExecutionDirective(DKind) &&
1940 !Stack->isLoopControlVariable(VD).first) {
1941 if (!Stack->checkMappableExprComponentListsForDecl(
1942 VD, /*CurrentRegionOnly=*/true,
1943 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1944 StackComponents,
1945 OpenMPClauseKind) {
1946 // Variable is used if it has been marked as an array, array
1947 // section or the variable iself.
1948 return StackComponents.size() == 1 ||
1949 std::all_of(
1950 std::next(StackComponents.rbegin()),
1951 StackComponents.rend(),
1952 [](const OMPClauseMappableExprCommon::
1953 MappableComponent &MC) {
1954 return MC.getAssociatedDeclaration() ==
1955 nullptr &&
1956 (isa<OMPArraySectionExpr>(
1957 MC.getAssociatedExpression()) ||
1958 isa<ArraySubscriptExpr>(
1959 MC.getAssociatedExpression()));
1960 });
1961 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001962 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001963 // By default lambdas are captured as firstprivates.
1964 if (const auto *RD =
1965 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001966 IsFirstprivate = RD->isLambda();
1967 IsFirstprivate =
1968 IsFirstprivate ||
1969 (VD->getType().getNonReferenceType()->isScalarType() &&
1970 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1971 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001972 ImplicitFirstprivate.emplace_back(E);
1973 else
1974 ImplicitMap.emplace_back(E);
1975 return;
1976 }
1977 }
1978
Alexey Bataev758e55e2013-09-06 18:03:48 +00001979 // OpenMP [2.9.3.6, Restrictions, p.2]
1980 // A list item that appears in a reduction clause of the innermost
1981 // enclosing worksharing or parallel construct may not be accessed in an
1982 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001983 DVar = Stack->hasInnermostDSA(
1984 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1985 [](OpenMPDirectiveKind K) -> bool {
1986 return isOpenMPParallelDirective(K) ||
1987 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1988 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001989 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001990 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001991 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001992 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1993 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001994 return;
1995 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001996
1997 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001998 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001999 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2000 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002001 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002002 }
2003 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002004 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002005 if (E->isTypeDependent() || E->isValueDependent() ||
2006 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2007 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002008 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002009 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002010 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002011 if (!FD)
2012 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002013 auto DVar = Stack->getTopDSA(FD, false);
2014 // Check if the variable has explicit DSA set and stop analysis if it
2015 // so.
2016 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2017 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002018
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002019 if (isOpenMPTargetExecutionDirective(DKind) &&
2020 !Stack->isLoopControlVariable(FD).first &&
2021 !Stack->checkMappableExprComponentListsForDecl(
2022 FD, /*CurrentRegionOnly=*/true,
2023 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2024 StackComponents,
2025 OpenMPClauseKind) {
2026 return isa<CXXThisExpr>(
2027 cast<MemberExpr>(
2028 StackComponents.back().getAssociatedExpression())
2029 ->getBase()
2030 ->IgnoreParens());
2031 })) {
2032 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2033 // A bit-field cannot appear in a map clause.
2034 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002035 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002036 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002037 ImplicitMap.emplace_back(E);
2038 return;
2039 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002040
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002041 auto ELoc = E->getExprLoc();
2042 // OpenMP [2.9.3.6, Restrictions, p.2]
2043 // A list item that appears in a reduction clause of the innermost
2044 // enclosing worksharing or parallel construct may not be accessed in
2045 // an explicit task.
2046 DVar = Stack->hasInnermostDSA(
2047 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2048 [](OpenMPDirectiveKind K) -> bool {
2049 return isOpenMPParallelDirective(K) ||
2050 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2051 },
2052 /*FromParent=*/true);
2053 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2054 ErrorFound = true;
2055 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2056 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
2057 return;
2058 }
2059
2060 // Define implicit data-sharing attributes for task.
2061 DVar = Stack->getImplicitDSA(FD, false);
2062 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2063 !Stack->isLoopControlVariable(FD).first)
2064 ImplicitFirstprivate.push_back(E);
2065 return;
2066 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002067 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002068 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002069 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2070 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002071 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002072 auto *VD = cast<ValueDecl>(
2073 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2074 if (!Stack->checkMappableExprComponentListsForDecl(
2075 VD, /*CurrentRegionOnly=*/true,
2076 [&CurComponents](
2077 OMPClauseMappableExprCommon::MappableExprComponentListRef
2078 StackComponents,
2079 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002080 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002081 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002082 for (const auto &SC : llvm::reverse(StackComponents)) {
2083 // Do both expressions have the same kind?
2084 if (CCI->getAssociatedExpression()->getStmtClass() !=
2085 SC.getAssociatedExpression()->getStmtClass())
2086 if (!(isa<OMPArraySectionExpr>(
2087 SC.getAssociatedExpression()) &&
2088 isa<ArraySubscriptExpr>(
2089 CCI->getAssociatedExpression())))
2090 return false;
2091
2092 Decl *CCD = CCI->getAssociatedDeclaration();
2093 Decl *SCD = SC.getAssociatedDeclaration();
2094 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2095 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2096 if (SCD != CCD)
2097 return false;
2098 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002099 if (CCI == CCE)
2100 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002101 }
2102 return true;
2103 })) {
2104 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002105 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002106 } else
2107 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002108 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002109 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002110 for (auto *C : S->clauses()) {
2111 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002112 // for task|target directives.
2113 // Skip analysis of arguments of implicitly defined map clause for target
2114 // directives.
2115 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2116 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002117 for (auto *CC : C->children()) {
2118 if (CC)
2119 Visit(CC);
2120 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002121 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002122 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002123 }
2124 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002125 for (auto *C : S->children()) {
2126 if (C && !isa<OMPExecutableDirective>(C))
2127 Visit(C);
2128 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002129 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002130
2131 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002132 ArrayRef<Expr *> getImplicitFirstprivate() const {
2133 return ImplicitFirstprivate;
2134 }
2135 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002136 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002137 return VarsWithInheritedDSA;
2138 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002139
Alexey Bataev7ff55242014-06-19 09:13:45 +00002140 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2141 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002142};
Alexey Bataeved09d242014-05-28 05:53:51 +00002143} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002144
Alexey Bataevbae9a792014-06-27 10:37:06 +00002145void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002146 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002147 case OMPD_parallel:
2148 case OMPD_parallel_for:
2149 case OMPD_parallel_for_simd:
2150 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002151 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002152 case OMPD_teams_distribute:
2153 case OMPD_teams_distribute_simd: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002154 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002155 QualType KmpInt32PtrTy =
2156 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002157 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002158 std::make_pair(".global_tid.", KmpInt32PtrTy),
2159 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2160 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002161 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002162 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2163 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002164 break;
2165 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002166 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002167 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002168 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002169 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002170 case OMPD_target_teams_distribute:
2171 case OMPD_target_teams_distribute_simd: {
Alexey Bataev8451efa2018-01-15 19:06:12 +00002172 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2173 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2174 FunctionProtoType::ExtProtoInfo EPI;
2175 EPI.Variadic = true;
2176 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2177 Sema::CapturedParamNameType Params[] = {
2178 std::make_pair(".global_tid.", KmpInt32Ty),
2179 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2180 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2181 std::make_pair(".copy_fn.",
2182 Context.getPointerType(CopyFnType).withConst()),
2183 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2184 std::make_pair(StringRef(), QualType()) // __context with shared vars
2185 };
2186 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2187 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002188 // Mark this captured region as inlined, because we don't use outlined
2189 // function directly.
2190 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2191 AlwaysInlineAttr::CreateImplicit(
2192 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002193 Sema::CapturedParamNameType ParamsTarget[] = {
2194 std::make_pair(StringRef(), QualType()) // __context with shared vars
2195 };
2196 // Start a captured region for 'target' with no implicit parameters.
2197 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2198 ParamsTarget);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002199 QualType KmpInt32PtrTy =
2200 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002201 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002202 std::make_pair(".global_tid.", KmpInt32PtrTy),
2203 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2204 std::make_pair(StringRef(), QualType()) // __context with shared vars
2205 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002206 // Start a captured region for 'teams' or 'parallel'. Both regions have
2207 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002208 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002209 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002210 break;
2211 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002212 case OMPD_target:
2213 case OMPD_target_simd: {
2214 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2215 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2216 FunctionProtoType::ExtProtoInfo EPI;
2217 EPI.Variadic = true;
2218 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2219 Sema::CapturedParamNameType Params[] = {
2220 std::make_pair(".global_tid.", KmpInt32Ty),
2221 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2222 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2223 std::make_pair(".copy_fn.",
2224 Context.getPointerType(CopyFnType).withConst()),
2225 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2226 std::make_pair(StringRef(), QualType()) // __context with shared vars
2227 };
2228 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2229 Params);
2230 // Mark this captured region as inlined, because we don't use outlined
2231 // function directly.
2232 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2233 AlwaysInlineAttr::CreateImplicit(
2234 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2235 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2236 std::make_pair(StringRef(), QualType()));
2237 break;
2238 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002239 case OMPD_simd:
2240 case OMPD_for:
2241 case OMPD_for_simd:
2242 case OMPD_sections:
2243 case OMPD_section:
2244 case OMPD_single:
2245 case OMPD_master:
2246 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002247 case OMPD_taskgroup:
2248 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002249 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002250 case OMPD_ordered:
2251 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002252 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002253 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002254 std::make_pair(StringRef(), QualType()) // __context with shared vars
2255 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002256 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2257 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002258 break;
2259 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002260 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002261 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002262 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2263 FunctionProtoType::ExtProtoInfo EPI;
2264 EPI.Variadic = true;
2265 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002266 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002267 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002268 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2269 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2270 std::make_pair(".copy_fn.",
2271 Context.getPointerType(CopyFnType).withConst()),
2272 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002273 std::make_pair(StringRef(), QualType()) // __context with shared vars
2274 };
2275 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2276 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002277 // Mark this captured region as inlined, because we don't use outlined
2278 // function directly.
2279 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2280 AlwaysInlineAttr::CreateImplicit(
2281 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002282 break;
2283 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002284 case OMPD_taskloop:
2285 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002286 QualType KmpInt32Ty =
2287 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2288 QualType KmpUInt64Ty =
2289 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2290 QualType KmpInt64Ty =
2291 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2292 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2293 FunctionProtoType::ExtProtoInfo EPI;
2294 EPI.Variadic = true;
2295 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002296 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002297 std::make_pair(".global_tid.", KmpInt32Ty),
2298 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2299 std::make_pair(".privates.",
2300 Context.VoidPtrTy.withConst().withRestrict()),
2301 std::make_pair(
2302 ".copy_fn.",
2303 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2304 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2305 std::make_pair(".lb.", KmpUInt64Ty),
2306 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2307 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002308 std::make_pair(".reductions.",
2309 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002310 std::make_pair(StringRef(), QualType()) // __context with shared vars
2311 };
2312 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2313 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002314 // Mark this captured region as inlined, because we don't use outlined
2315 // function directly.
2316 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2317 AlwaysInlineAttr::CreateImplicit(
2318 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002319 break;
2320 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002321 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002322 case OMPD_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002323 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2324 QualType KmpInt32PtrTy =
2325 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2326 Sema::CapturedParamNameType Params[] = {
2327 std::make_pair(".global_tid.", KmpInt32PtrTy),
2328 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2329 std::make_pair(".previous.lb.", Context.getSizeType()),
2330 std::make_pair(".previous.ub.", Context.getSizeType()),
2331 std::make_pair(StringRef(), QualType()) // __context with shared vars
2332 };
2333 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2334 Params);
2335 break;
2336 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002337 case OMPD_target_teams_distribute_parallel_for:
2338 case OMPD_target_teams_distribute_parallel_for_simd: {
Carlo Bertolli52978c32018-01-03 21:12:44 +00002339 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2340 QualType KmpInt32PtrTy =
2341 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2342
Alexey Bataev8451efa2018-01-15 19:06:12 +00002343 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2344 FunctionProtoType::ExtProtoInfo EPI;
2345 EPI.Variadic = true;
2346 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2347 Sema::CapturedParamNameType Params[] = {
2348 std::make_pair(".global_tid.", KmpInt32Ty),
2349 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2350 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2351 std::make_pair(".copy_fn.",
2352 Context.getPointerType(CopyFnType).withConst()),
2353 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2354 std::make_pair(StringRef(), QualType()) // __context with shared vars
2355 };
2356 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2357 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002358 // Mark this captured region as inlined, because we don't use outlined
2359 // function directly.
2360 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2361 AlwaysInlineAttr::CreateImplicit(
2362 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002363 Sema::CapturedParamNameType ParamsTarget[] = {
2364 std::make_pair(StringRef(), QualType()) // __context with shared vars
2365 };
2366 // Start a captured region for 'target' with no implicit parameters.
2367 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2368 ParamsTarget);
2369
2370 Sema::CapturedParamNameType ParamsTeams[] = {
2371 std::make_pair(".global_tid.", KmpInt32PtrTy),
2372 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2373 std::make_pair(StringRef(), QualType()) // __context with shared vars
2374 };
2375 // Start a captured region for 'target' with no implicit parameters.
2376 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2377 ParamsTeams);
2378
2379 Sema::CapturedParamNameType ParamsParallel[] = {
2380 std::make_pair(".global_tid.", KmpInt32PtrTy),
2381 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2382 std::make_pair(".previous.lb.", Context.getSizeType()),
2383 std::make_pair(".previous.ub.", Context.getSizeType()),
2384 std::make_pair(StringRef(), QualType()) // __context with shared vars
2385 };
2386 // Start a captured region for 'teams' or 'parallel'. Both regions have
2387 // the same implicit parameters.
2388 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2389 ParamsParallel);
2390 break;
2391 }
2392
Alexey Bataev46506272017-12-05 17:41:34 +00002393 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002394 case OMPD_teams_distribute_parallel_for_simd: {
Carlo Bertolli62fae152017-11-20 20:46:39 +00002395 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2396 QualType KmpInt32PtrTy =
2397 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2398
2399 Sema::CapturedParamNameType ParamsTeams[] = {
2400 std::make_pair(".global_tid.", KmpInt32PtrTy),
2401 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2402 std::make_pair(StringRef(), QualType()) // __context with shared vars
2403 };
2404 // Start a captured region for 'target' with no implicit parameters.
2405 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2406 ParamsTeams);
2407
2408 Sema::CapturedParamNameType ParamsParallel[] = {
2409 std::make_pair(".global_tid.", KmpInt32PtrTy),
2410 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2411 std::make_pair(".previous.lb.", Context.getSizeType()),
2412 std::make_pair(".previous.ub.", Context.getSizeType()),
2413 std::make_pair(StringRef(), QualType()) // __context with shared vars
2414 };
2415 // Start a captured region for 'teams' or 'parallel'. Both regions have
2416 // the same implicit parameters.
2417 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2418 ParamsParallel);
2419 break;
2420 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002421 case OMPD_target_update:
2422 case OMPD_target_enter_data:
2423 case OMPD_target_exit_data: {
2424 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2425 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2426 FunctionProtoType::ExtProtoInfo EPI;
2427 EPI.Variadic = true;
2428 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2429 Sema::CapturedParamNameType Params[] = {
2430 std::make_pair(".global_tid.", KmpInt32Ty),
2431 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2432 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2433 std::make_pair(".copy_fn.",
2434 Context.getPointerType(CopyFnType).withConst()),
2435 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2436 std::make_pair(StringRef(), QualType()) // __context with shared vars
2437 };
2438 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2439 Params);
2440 // Mark this captured region as inlined, because we don't use outlined
2441 // function directly.
2442 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2443 AlwaysInlineAttr::CreateImplicit(
2444 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2445 break;
2446 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002447 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002448 case OMPD_taskyield:
2449 case OMPD_barrier:
2450 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002451 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002452 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002453 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002454 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002455 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002456 case OMPD_declare_target:
2457 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002458 llvm_unreachable("OpenMP Directive is not allowed");
2459 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002460 llvm_unreachable("Unknown OpenMP directive");
2461 }
2462}
2463
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002464int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2465 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2466 getOpenMPCaptureRegions(CaptureRegions, DKind);
2467 return CaptureRegions.size();
2468}
2469
Alexey Bataev3392d762016-02-16 11:18:12 +00002470static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002471 Expr *CaptureExpr, bool WithInit,
2472 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002473 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002474 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002475 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002476 QualType Ty = Init->getType();
2477 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002478 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002479 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002480 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002481 Ty = C.getPointerType(Ty);
2482 ExprResult Res =
2483 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2484 if (!Res.isUsable())
2485 return nullptr;
2486 Init = Res.get();
2487 }
Alexey Bataev61205072016-03-02 04:57:40 +00002488 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002489 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002490 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2491 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002492 if (!WithInit)
2493 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002494 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002495 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002496 return CED;
2497}
2498
Alexey Bataev61205072016-03-02 04:57:40 +00002499static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2500 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002501 OMPCapturedExprDecl *CD;
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002502 if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002503 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002504 } else {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002505 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2506 /*AsExpression=*/false);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002507 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002508 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002509 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002510}
2511
Alexey Bataev5a3af132016-03-29 08:58:54 +00002512static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002513 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002514 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002515 OMPCapturedExprDecl *CD = buildCaptureDecl(
2516 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2517 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002518 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2519 CaptureExpr->getExprLoc());
2520 }
2521 ExprResult Res = Ref;
2522 if (!S.getLangOpts().CPlusPlus &&
2523 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002524 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002525 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002526 if (!Res.isUsable())
2527 return ExprError();
2528 }
2529 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002530}
2531
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002532namespace {
2533// OpenMP directives parsed in this section are represented as a
2534// CapturedStatement with an associated statement. If a syntax error
2535// is detected during the parsing of the associated statement, the
2536// compiler must abort processing and close the CapturedStatement.
2537//
2538// Combined directives such as 'target parallel' have more than one
2539// nested CapturedStatements. This RAII ensures that we unwind out
2540// of all the nested CapturedStatements when an error is found.
2541class CaptureRegionUnwinderRAII {
2542private:
2543 Sema &S;
2544 bool &ErrorFound;
2545 OpenMPDirectiveKind DKind;
2546
2547public:
2548 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2549 OpenMPDirectiveKind DKind)
2550 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2551 ~CaptureRegionUnwinderRAII() {
2552 if (ErrorFound) {
2553 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2554 while (--ThisCaptureLevel >= 0)
2555 S.ActOnCapturedRegionError();
2556 }
2557 }
2558};
2559} // namespace
2560
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002561StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2562 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002563 bool ErrorFound = false;
2564 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2565 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002566 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002567 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002568 return StmtError();
2569 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002570
Alexey Bataev2ba67042017-11-28 21:11:44 +00002571 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2572 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002573 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002574 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002575 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002576 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002577 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002578 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002579 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2580 Clause->getClauseKind() == OMPC_in_reduction) {
2581 // Capture taskgroup task_reduction descriptors inside the tasking regions
2582 // with the corresponding in_reduction items.
2583 auto *IRC = cast<OMPInReductionClause>(Clause);
2584 for (auto *E : IRC->taskgroup_descriptors())
2585 if (E)
2586 MarkDeclarationsReferencedInExpr(E);
2587 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002588 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002589 Clause->getClauseKind() == OMPC_copyprivate ||
2590 (getLangOpts().OpenMPUseTLS &&
2591 getASTContext().getTargetInfo().isTLSSupported() &&
2592 Clause->getClauseKind() == OMPC_copyin)) {
2593 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002594 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002595 for (auto *VarRef : Clause->children()) {
2596 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002597 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002598 }
2599 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002600 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002601 } else if (CaptureRegions.size() > 1 ||
2602 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002603 if (auto *C = OMPClauseWithPreInit::get(Clause))
2604 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002605 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2606 if (auto *E = C->getPostUpdateExpr())
2607 MarkDeclarationsReferencedInExpr(E);
2608 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002609 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002610 if (Clause->getClauseKind() == OMPC_schedule)
2611 SC = cast<OMPScheduleClause>(Clause);
2612 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002613 OC = cast<OMPOrderedClause>(Clause);
2614 else if (Clause->getClauseKind() == OMPC_linear)
2615 LCs.push_back(cast<OMPLinearClause>(Clause));
2616 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002617 // OpenMP, 2.7.1 Loop Construct, Restrictions
2618 // The nonmonotonic modifier cannot be specified if an ordered clause is
2619 // specified.
2620 if (SC &&
2621 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2622 SC->getSecondScheduleModifier() ==
2623 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2624 OC) {
2625 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2626 ? SC->getFirstScheduleModifierLoc()
2627 : SC->getSecondScheduleModifierLoc(),
2628 diag::err_omp_schedule_nonmonotonic_ordered)
2629 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2630 ErrorFound = true;
2631 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002632 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2633 for (auto *C : LCs) {
2634 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2635 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2636 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002637 ErrorFound = true;
2638 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002639 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2640 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2641 OC->getNumForLoops()) {
2642 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2643 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2644 ErrorFound = true;
2645 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002646 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002647 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002648 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002649 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002650 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002651 // Mark all variables in private list clauses as used in inner region.
2652 // Required for proper codegen of combined directives.
2653 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002654 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002655 for (auto *C : PICs) {
2656 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2657 // Find the particular capture region for the clause if the
2658 // directive is a combined one with multiple capture regions.
2659 // If the directive is not a combined one, the capture region
2660 // associated with the clause is OMPD_unknown and is generated
2661 // only once.
2662 if (CaptureRegion == ThisCaptureRegion ||
2663 CaptureRegion == OMPD_unknown) {
2664 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2665 for (auto *D : DS->decls())
2666 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2667 }
2668 }
2669 }
2670 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002671 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002672 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002673 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002674}
2675
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002676static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2677 OpenMPDirectiveKind CancelRegion,
2678 SourceLocation StartLoc) {
2679 // CancelRegion is only needed for cancel and cancellation_point.
2680 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2681 return false;
2682
2683 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2684 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2685 return false;
2686
2687 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2688 << getOpenMPDirectiveName(CancelRegion);
2689 return true;
2690}
2691
2692static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002693 OpenMPDirectiveKind CurrentRegion,
2694 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002695 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002696 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002697 if (Stack->getCurScope()) {
2698 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002699 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002700 bool NestingProhibited = false;
2701 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002702 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002703 enum {
2704 NoRecommend,
2705 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002706 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002707 ShouldBeInTargetRegion,
2708 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002709 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002710 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002711 // OpenMP [2.16, Nesting of Regions]
2712 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002713 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002714 // An ordered construct with the simd clause is the only OpenMP
2715 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002716 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002717 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2718 // message.
2719 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2720 ? diag::err_omp_prohibited_region_simd
2721 : diag::warn_omp_nesting_simd);
2722 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002723 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002724 if (ParentRegion == OMPD_atomic) {
2725 // OpenMP [2.16, Nesting of Regions]
2726 // OpenMP constructs may not be nested inside an atomic region.
2727 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2728 return true;
2729 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002730 if (CurrentRegion == OMPD_section) {
2731 // OpenMP [2.7.2, sections Construct, Restrictions]
2732 // Orphaned section directives are prohibited. That is, the section
2733 // directives must appear within the sections construct and must not be
2734 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002735 if (ParentRegion != OMPD_sections &&
2736 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002737 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2738 << (ParentRegion != OMPD_unknown)
2739 << getOpenMPDirectiveName(ParentRegion);
2740 return true;
2741 }
2742 return false;
2743 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002744 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002745 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002746 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002747 if (ParentRegion == OMPD_unknown &&
2748 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002749 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002750 if (CurrentRegion == OMPD_cancellation_point ||
2751 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002752 // OpenMP [2.16, Nesting of Regions]
2753 // A cancellation point construct for which construct-type-clause is
2754 // taskgroup must be nested inside a task construct. A cancellation
2755 // point construct for which construct-type-clause is not taskgroup must
2756 // be closely nested inside an OpenMP construct that matches the type
2757 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002758 // A cancel construct for which construct-type-clause is taskgroup must be
2759 // nested inside a task construct. A cancel construct for which
2760 // construct-type-clause is not taskgroup must be closely nested inside an
2761 // OpenMP construct that matches the type specified in
2762 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002763 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002764 !((CancelRegion == OMPD_parallel &&
2765 (ParentRegion == OMPD_parallel ||
2766 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002767 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002768 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002769 ParentRegion == OMPD_target_parallel_for ||
2770 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002771 ParentRegion == OMPD_teams_distribute_parallel_for ||
2772 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002773 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2774 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002775 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2776 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002777 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002778 // OpenMP [2.16, Nesting of Regions]
2779 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002780 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002781 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002782 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002783 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2784 // OpenMP [2.16, Nesting of Regions]
2785 // A critical region may not be nested (closely or otherwise) inside a
2786 // critical region with the same name. Note that this restriction is not
2787 // sufficient to prevent deadlock.
2788 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002789 bool DeadLock = Stack->hasDirective(
2790 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2791 const DeclarationNameInfo &DNI,
2792 SourceLocation Loc) -> bool {
2793 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2794 PreviousCriticalLoc = Loc;
2795 return true;
2796 } else
2797 return false;
2798 },
2799 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002800 if (DeadLock) {
2801 SemaRef.Diag(StartLoc,
2802 diag::err_omp_prohibited_region_critical_same_name)
2803 << CurrentName.getName();
2804 if (PreviousCriticalLoc.isValid())
2805 SemaRef.Diag(PreviousCriticalLoc,
2806 diag::note_omp_previous_critical_region);
2807 return true;
2808 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002809 } else if (CurrentRegion == OMPD_barrier) {
2810 // OpenMP [2.16, Nesting of Regions]
2811 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002812 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002813 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2814 isOpenMPTaskingDirective(ParentRegion) ||
2815 ParentRegion == OMPD_master ||
2816 ParentRegion == OMPD_critical ||
2817 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002818 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002819 !isOpenMPParallelDirective(CurrentRegion) &&
2820 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002821 // OpenMP [2.16, Nesting of Regions]
2822 // A worksharing region may not be closely nested inside a worksharing,
2823 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002824 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2825 isOpenMPTaskingDirective(ParentRegion) ||
2826 ParentRegion == OMPD_master ||
2827 ParentRegion == OMPD_critical ||
2828 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002829 Recommend = ShouldBeInParallelRegion;
2830 } else if (CurrentRegion == OMPD_ordered) {
2831 // OpenMP [2.16, Nesting of Regions]
2832 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002833 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002834 // An ordered region must be closely nested inside a loop region (or
2835 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002836 // OpenMP [2.8.1,simd Construct, Restrictions]
2837 // An ordered construct with the simd clause is the only OpenMP construct
2838 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002839 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002840 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002841 !(isOpenMPSimdDirective(ParentRegion) ||
2842 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002843 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002844 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002845 // OpenMP [2.16, Nesting of Regions]
2846 // If specified, a teams construct must be contained within a target
2847 // construct.
2848 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002849 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002850 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002851 }
Kelvin Libf594a52016-12-17 05:48:59 +00002852 if (!NestingProhibited &&
2853 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2854 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2855 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002856 // OpenMP [2.16, Nesting of Regions]
2857 // distribute, parallel, parallel sections, parallel workshare, and the
2858 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2859 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002860 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2861 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002862 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002863 }
David Majnemer9d168222016-08-05 17:44:54 +00002864 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002865 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002866 // OpenMP 4.5 [2.17 Nesting of Regions]
2867 // The region associated with the distribute construct must be strictly
2868 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002869 NestingProhibited =
2870 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002871 Recommend = ShouldBeInTeamsRegion;
2872 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002873 if (!NestingProhibited &&
2874 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2875 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2876 // OpenMP 4.5 [2.17 Nesting of Regions]
2877 // If a target, target update, target data, target enter data, or
2878 // target exit data construct is encountered during execution of a
2879 // target region, the behavior is unspecified.
2880 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002881 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2882 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002883 if (isOpenMPTargetExecutionDirective(K)) {
2884 OffendingRegion = K;
2885 return true;
2886 } else
2887 return false;
2888 },
2889 false /* don't skip top directive */);
2890 CloseNesting = false;
2891 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002892 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002893 if (OrphanSeen) {
2894 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2895 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2896 } else {
2897 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2898 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2899 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2900 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002901 return true;
2902 }
2903 }
2904 return false;
2905}
2906
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002907static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2908 ArrayRef<OMPClause *> Clauses,
2909 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2910 bool ErrorFound = false;
2911 unsigned NamedModifiersNumber = 0;
2912 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2913 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002914 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002915 for (const auto *C : Clauses) {
2916 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2917 // At most one if clause without a directive-name-modifier can appear on
2918 // the directive.
2919 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2920 if (FoundNameModifiers[CurNM]) {
2921 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2922 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2923 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2924 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002925 } else if (CurNM != OMPD_unknown) {
2926 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002927 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002928 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002929 FoundNameModifiers[CurNM] = IC;
2930 if (CurNM == OMPD_unknown)
2931 continue;
2932 // Check if the specified name modifier is allowed for the current
2933 // directive.
2934 // At most one if clause with the particular directive-name-modifier can
2935 // appear on the directive.
2936 bool MatchFound = false;
2937 for (auto NM : AllowedNameModifiers) {
2938 if (CurNM == NM) {
2939 MatchFound = true;
2940 break;
2941 }
2942 }
2943 if (!MatchFound) {
2944 S.Diag(IC->getNameModifierLoc(),
2945 diag::err_omp_wrong_if_directive_name_modifier)
2946 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2947 ErrorFound = true;
2948 }
2949 }
2950 }
2951 // If any if clause on the directive includes a directive-name-modifier then
2952 // all if clauses on the directive must include a directive-name-modifier.
2953 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2954 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2955 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2956 diag::err_omp_no_more_if_clause);
2957 } else {
2958 std::string Values;
2959 std::string Sep(", ");
2960 unsigned AllowedCnt = 0;
2961 unsigned TotalAllowedNum =
2962 AllowedNameModifiers.size() - NamedModifiersNumber;
2963 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2964 ++Cnt) {
2965 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2966 if (!FoundNameModifiers[NM]) {
2967 Values += "'";
2968 Values += getOpenMPDirectiveName(NM);
2969 Values += "'";
2970 if (AllowedCnt + 2 == TotalAllowedNum)
2971 Values += " or ";
2972 else if (AllowedCnt + 1 != TotalAllowedNum)
2973 Values += Sep;
2974 ++AllowedCnt;
2975 }
2976 }
2977 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2978 diag::err_omp_unnamed_if_clause)
2979 << (TotalAllowedNum > 1) << Values;
2980 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002981 for (auto Loc : NameModifierLoc) {
2982 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2983 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002984 ErrorFound = true;
2985 }
2986 return ErrorFound;
2987}
2988
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002989StmtResult Sema::ActOnOpenMPExecutableDirective(
2990 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2991 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2992 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002993 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002994 // First check CancelRegion which is then used in checkNestingOfRegions.
2995 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2996 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002997 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002998 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002999
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003000 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003001 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003002 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003003 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003004 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003005 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3006
3007 // Check default data sharing attributes for referenced variables.
3008 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003009 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3010 Stmt *S = AStmt;
3011 while (--ThisCaptureLevel >= 0)
3012 S = cast<CapturedStmt>(S)->getCapturedStmt();
3013 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003014 if (DSAChecker.isErrorFound())
3015 return StmtError();
3016 // Generate list of implicitly defined firstprivate variables.
3017 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003018
Alexey Bataev88202be2017-07-27 13:20:36 +00003019 SmallVector<Expr *, 4> ImplicitFirstprivates(
3020 DSAChecker.getImplicitFirstprivate().begin(),
3021 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003022 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3023 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003024 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3025 for (auto *C : Clauses) {
3026 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3027 for (auto *E : IRC->taskgroup_descriptors())
3028 if (E)
3029 ImplicitFirstprivates.emplace_back(E);
3030 }
3031 }
3032 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003033 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003034 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3035 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003036 ClausesWithImplicit.push_back(Implicit);
3037 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003038 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00003039 } else
3040 ErrorFound = true;
3041 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003042 if (!ImplicitMaps.empty()) {
3043 if (OMPClause *Implicit = ActOnOpenMPMapClause(
3044 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3045 SourceLocation(), SourceLocation(), ImplicitMaps,
3046 SourceLocation(), SourceLocation(), SourceLocation())) {
3047 ClausesWithImplicit.emplace_back(Implicit);
3048 ErrorFound |=
3049 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3050 } else
3051 ErrorFound = true;
3052 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003053 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003054
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003055 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003056 switch (Kind) {
3057 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003058 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3059 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003060 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003061 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003062 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003063 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3064 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003065 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003066 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003067 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3068 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003069 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003070 case OMPD_for_simd:
3071 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3072 EndLoc, VarsWithInheritedDSA);
3073 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003074 case OMPD_sections:
3075 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3076 EndLoc);
3077 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003078 case OMPD_section:
3079 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003080 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003081 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3082 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003083 case OMPD_single:
3084 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3085 EndLoc);
3086 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003087 case OMPD_master:
3088 assert(ClausesWithImplicit.empty() &&
3089 "No clauses are allowed for 'omp master' directive");
3090 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3091 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003092 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003093 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3094 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003095 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003096 case OMPD_parallel_for:
3097 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3098 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003099 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003100 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003101 case OMPD_parallel_for_simd:
3102 Res = ActOnOpenMPParallelForSimdDirective(
3103 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003104 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003105 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003106 case OMPD_parallel_sections:
3107 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3108 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003109 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003110 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003111 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003112 Res =
3113 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003114 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003115 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003116 case OMPD_taskyield:
3117 assert(ClausesWithImplicit.empty() &&
3118 "No clauses are allowed for 'omp taskyield' directive");
3119 assert(AStmt == nullptr &&
3120 "No associated statement allowed for 'omp taskyield' directive");
3121 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3122 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003123 case OMPD_barrier:
3124 assert(ClausesWithImplicit.empty() &&
3125 "No clauses are allowed for 'omp barrier' directive");
3126 assert(AStmt == nullptr &&
3127 "No associated statement allowed for 'omp barrier' directive");
3128 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3129 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003130 case OMPD_taskwait:
3131 assert(ClausesWithImplicit.empty() &&
3132 "No clauses are allowed for 'omp taskwait' directive");
3133 assert(AStmt == nullptr &&
3134 "No associated statement allowed for 'omp taskwait' directive");
3135 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3136 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003137 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003138 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3139 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003140 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003141 case OMPD_flush:
3142 assert(AStmt == nullptr &&
3143 "No associated statement allowed for 'omp flush' directive");
3144 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3145 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003146 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003147 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3148 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003149 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003150 case OMPD_atomic:
3151 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3152 EndLoc);
3153 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003154 case OMPD_teams:
3155 Res =
3156 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3157 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003158 case OMPD_target:
3159 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3160 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003161 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003162 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003163 case OMPD_target_parallel:
3164 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3165 StartLoc, EndLoc);
3166 AllowedNameModifiers.push_back(OMPD_target);
3167 AllowedNameModifiers.push_back(OMPD_parallel);
3168 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003169 case OMPD_target_parallel_for:
3170 Res = ActOnOpenMPTargetParallelForDirective(
3171 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3172 AllowedNameModifiers.push_back(OMPD_target);
3173 AllowedNameModifiers.push_back(OMPD_parallel);
3174 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003175 case OMPD_cancellation_point:
3176 assert(ClausesWithImplicit.empty() &&
3177 "No clauses are allowed for 'omp cancellation point' directive");
3178 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3179 "cancellation point' directive");
3180 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3181 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003182 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003183 assert(AStmt == nullptr &&
3184 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003185 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3186 CancelRegion);
3187 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003188 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003189 case OMPD_target_data:
3190 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3191 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003192 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003193 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003194 case OMPD_target_enter_data:
3195 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003196 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003197 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3198 break;
Samuel Antao72590762016-01-19 20:04:50 +00003199 case OMPD_target_exit_data:
3200 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003201 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003202 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3203 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003204 case OMPD_taskloop:
3205 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3206 EndLoc, VarsWithInheritedDSA);
3207 AllowedNameModifiers.push_back(OMPD_taskloop);
3208 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003209 case OMPD_taskloop_simd:
3210 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3211 EndLoc, VarsWithInheritedDSA);
3212 AllowedNameModifiers.push_back(OMPD_taskloop);
3213 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003214 case OMPD_distribute:
3215 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3216 EndLoc, VarsWithInheritedDSA);
3217 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003218 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003219 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3220 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003221 AllowedNameModifiers.push_back(OMPD_target_update);
3222 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003223 case OMPD_distribute_parallel_for:
3224 Res = ActOnOpenMPDistributeParallelForDirective(
3225 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3226 AllowedNameModifiers.push_back(OMPD_parallel);
3227 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003228 case OMPD_distribute_parallel_for_simd:
3229 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3230 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3231 AllowedNameModifiers.push_back(OMPD_parallel);
3232 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003233 case OMPD_distribute_simd:
3234 Res = ActOnOpenMPDistributeSimdDirective(
3235 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3236 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003237 case OMPD_target_parallel_for_simd:
3238 Res = ActOnOpenMPTargetParallelForSimdDirective(
3239 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3240 AllowedNameModifiers.push_back(OMPD_target);
3241 AllowedNameModifiers.push_back(OMPD_parallel);
3242 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003243 case OMPD_target_simd:
3244 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3245 EndLoc, VarsWithInheritedDSA);
3246 AllowedNameModifiers.push_back(OMPD_target);
3247 break;
Kelvin Li02532872016-08-05 14:37:37 +00003248 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003249 Res = ActOnOpenMPTeamsDistributeDirective(
3250 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003251 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003252 case OMPD_teams_distribute_simd:
3253 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3254 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3255 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003256 case OMPD_teams_distribute_parallel_for_simd:
3257 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3258 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3259 AllowedNameModifiers.push_back(OMPD_parallel);
3260 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003261 case OMPD_teams_distribute_parallel_for:
3262 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3263 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3264 AllowedNameModifiers.push_back(OMPD_parallel);
3265 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003266 case OMPD_target_teams:
3267 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3268 EndLoc);
3269 AllowedNameModifiers.push_back(OMPD_target);
3270 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003271 case OMPD_target_teams_distribute:
3272 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3273 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3274 AllowedNameModifiers.push_back(OMPD_target);
3275 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003276 case OMPD_target_teams_distribute_parallel_for:
3277 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3278 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3279 AllowedNameModifiers.push_back(OMPD_target);
3280 AllowedNameModifiers.push_back(OMPD_parallel);
3281 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003282 case OMPD_target_teams_distribute_parallel_for_simd:
3283 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3284 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3285 AllowedNameModifiers.push_back(OMPD_target);
3286 AllowedNameModifiers.push_back(OMPD_parallel);
3287 break;
Kelvin Lida681182017-01-10 18:08:18 +00003288 case OMPD_target_teams_distribute_simd:
3289 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3290 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3291 AllowedNameModifiers.push_back(OMPD_target);
3292 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003293 case OMPD_declare_target:
3294 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003295 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003296 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003297 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003298 llvm_unreachable("OpenMP Directive is not allowed");
3299 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003300 llvm_unreachable("Unknown OpenMP directive");
3301 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003302
Alexey Bataev4acb8592014-07-07 13:01:15 +00003303 for (auto P : VarsWithInheritedDSA) {
3304 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3305 << P.first << P.second->getSourceRange();
3306 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003307 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3308
3309 if (!AllowedNameModifiers.empty())
3310 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3311 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003312
Alexey Bataeved09d242014-05-28 05:53:51 +00003313 if (ErrorFound)
3314 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003315 return Res;
3316}
3317
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003318Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3319 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003320 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003321 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3322 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003323 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003324 assert(Linears.size() == LinModifiers.size());
3325 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003326 if (!DG || DG.get().isNull())
3327 return DeclGroupPtrTy();
3328
3329 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003330 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003331 return DG;
3332 }
3333 auto *ADecl = DG.get().getSingleDecl();
3334 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3335 ADecl = FTD->getTemplatedDecl();
3336
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003337 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3338 if (!FD) {
3339 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003340 return DeclGroupPtrTy();
3341 }
3342
Alexey Bataev2af33e32016-04-07 12:45:37 +00003343 // OpenMP [2.8.2, declare simd construct, Description]
3344 // The parameter of the simdlen clause must be a constant positive integer
3345 // expression.
3346 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003347 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003348 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003349 // OpenMP [2.8.2, declare simd construct, Description]
3350 // The special this pointer can be used as if was one of the arguments to the
3351 // function in any of the linear, aligned, or uniform clauses.
3352 // The uniform clause declares one or more arguments to have an invariant
3353 // value for all concurrent invocations of the function in the execution of a
3354 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003355 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3356 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003357 for (auto *E : Uniforms) {
3358 E = E->IgnoreParenImpCasts();
3359 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3360 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3361 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3362 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003363 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3364 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003365 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003366 }
3367 if (isa<CXXThisExpr>(E)) {
3368 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003369 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003370 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003371 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3372 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003373 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003374 // OpenMP [2.8.2, declare simd construct, Description]
3375 // The aligned clause declares that the object to which each list item points
3376 // is aligned to the number of bytes expressed in the optional parameter of
3377 // the aligned clause.
3378 // The special this pointer can be used as if was one of the arguments to the
3379 // function in any of the linear, aligned, or uniform clauses.
3380 // The type of list items appearing in the aligned clause must be array,
3381 // pointer, reference to array, or reference to pointer.
3382 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3383 Expr *AlignedThis = nullptr;
3384 for (auto *E : Aligneds) {
3385 E = E->IgnoreParenImpCasts();
3386 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3387 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3388 auto *CanonPVD = PVD->getCanonicalDecl();
3389 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3390 FD->getParamDecl(PVD->getFunctionScopeIndex())
3391 ->getCanonicalDecl() == CanonPVD) {
3392 // OpenMP [2.8.1, simd construct, Restrictions]
3393 // A list-item cannot appear in more than one aligned clause.
3394 if (AlignedArgs.count(CanonPVD) > 0) {
3395 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3396 << 1 << E->getSourceRange();
3397 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3398 diag::note_omp_explicit_dsa)
3399 << getOpenMPClauseName(OMPC_aligned);
3400 continue;
3401 }
3402 AlignedArgs[CanonPVD] = E;
3403 QualType QTy = PVD->getType()
3404 .getNonReferenceType()
3405 .getUnqualifiedType()
3406 .getCanonicalType();
3407 const Type *Ty = QTy.getTypePtrOrNull();
3408 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3409 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3410 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3411 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3412 }
3413 continue;
3414 }
3415 }
3416 if (isa<CXXThisExpr>(E)) {
3417 if (AlignedThis) {
3418 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3419 << 2 << E->getSourceRange();
3420 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3421 << getOpenMPClauseName(OMPC_aligned);
3422 }
3423 AlignedThis = E;
3424 continue;
3425 }
3426 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3427 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3428 }
3429 // The optional parameter of the aligned clause, alignment, must be a constant
3430 // positive integer expression. If no optional parameter is specified,
3431 // implementation-defined default alignments for SIMD instructions on the
3432 // target platforms are assumed.
3433 SmallVector<Expr *, 4> NewAligns;
3434 for (auto *E : Alignments) {
3435 ExprResult Align;
3436 if (E)
3437 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3438 NewAligns.push_back(Align.get());
3439 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003440 // OpenMP [2.8.2, declare simd construct, Description]
3441 // The linear clause declares one or more list items to be private to a SIMD
3442 // lane and to have a linear relationship with respect to the iteration space
3443 // of a loop.
3444 // The special this pointer can be used as if was one of the arguments to the
3445 // function in any of the linear, aligned, or uniform clauses.
3446 // When a linear-step expression is specified in a linear clause it must be
3447 // either a constant integer expression or an integer-typed parameter that is
3448 // specified in a uniform clause on the directive.
3449 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3450 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3451 auto MI = LinModifiers.begin();
3452 for (auto *E : Linears) {
3453 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3454 ++MI;
3455 E = E->IgnoreParenImpCasts();
3456 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3457 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3458 auto *CanonPVD = PVD->getCanonicalDecl();
3459 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3460 FD->getParamDecl(PVD->getFunctionScopeIndex())
3461 ->getCanonicalDecl() == CanonPVD) {
3462 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3463 // A list-item cannot appear in more than one linear clause.
3464 if (LinearArgs.count(CanonPVD) > 0) {
3465 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3466 << getOpenMPClauseName(OMPC_linear)
3467 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3468 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3469 diag::note_omp_explicit_dsa)
3470 << getOpenMPClauseName(OMPC_linear);
3471 continue;
3472 }
3473 // Each argument can appear in at most one uniform or linear clause.
3474 if (UniformedArgs.count(CanonPVD) > 0) {
3475 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3476 << getOpenMPClauseName(OMPC_linear)
3477 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3478 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3479 diag::note_omp_explicit_dsa)
3480 << getOpenMPClauseName(OMPC_uniform);
3481 continue;
3482 }
3483 LinearArgs[CanonPVD] = E;
3484 if (E->isValueDependent() || E->isTypeDependent() ||
3485 E->isInstantiationDependent() ||
3486 E->containsUnexpandedParameterPack())
3487 continue;
3488 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3489 PVD->getOriginalType());
3490 continue;
3491 }
3492 }
3493 if (isa<CXXThisExpr>(E)) {
3494 if (UniformedLinearThis) {
3495 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3496 << getOpenMPClauseName(OMPC_linear)
3497 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3498 << E->getSourceRange();
3499 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3500 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3501 : OMPC_linear);
3502 continue;
3503 }
3504 UniformedLinearThis = E;
3505 if (E->isValueDependent() || E->isTypeDependent() ||
3506 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3507 continue;
3508 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3509 E->getType());
3510 continue;
3511 }
3512 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3513 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3514 }
3515 Expr *Step = nullptr;
3516 Expr *NewStep = nullptr;
3517 SmallVector<Expr *, 4> NewSteps;
3518 for (auto *E : Steps) {
3519 // Skip the same step expression, it was checked already.
3520 if (Step == E || !E) {
3521 NewSteps.push_back(E ? NewStep : nullptr);
3522 continue;
3523 }
3524 Step = E;
3525 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3526 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3527 auto *CanonPVD = PVD->getCanonicalDecl();
3528 if (UniformedArgs.count(CanonPVD) == 0) {
3529 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3530 << Step->getSourceRange();
3531 } else if (E->isValueDependent() || E->isTypeDependent() ||
3532 E->isInstantiationDependent() ||
3533 E->containsUnexpandedParameterPack() ||
3534 CanonPVD->getType()->hasIntegerRepresentation())
3535 NewSteps.push_back(Step);
3536 else {
3537 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3538 << Step->getSourceRange();
3539 }
3540 continue;
3541 }
3542 NewStep = Step;
3543 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3544 !Step->isInstantiationDependent() &&
3545 !Step->containsUnexpandedParameterPack()) {
3546 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3547 .get();
3548 if (NewStep)
3549 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3550 }
3551 NewSteps.push_back(NewStep);
3552 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003553 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3554 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003555 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003556 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3557 const_cast<Expr **>(Linears.data()), Linears.size(),
3558 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3559 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003560 ADecl->addAttr(NewAttr);
3561 return ConvertDeclToDeclGroup(ADecl);
3562}
3563
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003564StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3565 Stmt *AStmt,
3566 SourceLocation StartLoc,
3567 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003568 if (!AStmt)
3569 return StmtError();
3570
Alexey Bataev9959db52014-05-06 10:08:46 +00003571 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3572 // 1.2.2 OpenMP Language Terminology
3573 // Structured block - An executable statement with a single entry at the
3574 // top and a single exit at the bottom.
3575 // The point of exit cannot be a branch out of the structured block.
3576 // longjmp() and throw() must not violate the entry/exit criteria.
3577 CS->getCapturedDecl()->setNothrow();
3578
Reid Kleckner87a31802018-03-12 21:43:02 +00003579 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003580
Alexey Bataev25e5b442015-09-15 12:52:43 +00003581 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3582 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003583}
3584
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003585namespace {
3586/// \brief Helper class for checking canonical form of the OpenMP loops and
3587/// extracting iteration space of each loop in the loop nest, that will be used
3588/// for IR generation.
3589class OpenMPIterationSpaceChecker {
3590 /// \brief Reference to Sema.
3591 Sema &SemaRef;
3592 /// \brief A location for diagnostics (when there is no some better location).
3593 SourceLocation DefaultLoc;
3594 /// \brief A location for diagnostics (when increment is not compatible).
3595 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003596 /// \brief A source location for referring to loop init later.
3597 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003598 /// \brief A source location for referring to condition later.
3599 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003600 /// \brief A source location for referring to increment later.
3601 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003602 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003603 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003604 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003605 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003606 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003607 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003608 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003609 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003610 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003611 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003612 /// \brief This flag is true when condition is one of:
3613 /// Var < UB
3614 /// Var <= UB
3615 /// UB > Var
3616 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003617 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003618 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003619 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003620 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003621 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003622
3623public:
3624 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003625 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003626 /// \brief Check init-expr for canonical loop form and save loop counter
3627 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003628 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003629 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3630 /// for less/greater and for strict/non-strict comparison.
3631 bool CheckCond(Expr *S);
3632 /// \brief Check incr-expr for canonical loop form and return true if it
3633 /// does not conform, otherwise save loop step (#Step).
3634 bool CheckInc(Expr *S);
3635 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003636 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003637 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003638 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003639 /// \brief Source range of the loop init.
3640 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3641 /// \brief Source range of the loop condition.
3642 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3643 /// \brief Source range of the loop increment.
3644 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3645 /// \brief True if the step should be subtracted.
3646 bool ShouldSubtractStep() const { return SubtractStep; }
3647 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003648 Expr *
3649 BuildNumIterations(Scope *S, const bool LimitedType,
3650 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003651 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003652 Expr *BuildPreCond(Scope *S, Expr *Cond,
3653 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003654 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003655 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3656 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003657 /// \brief Build reference expression to the private counter be used for
3658 /// codegen.
3659 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003660 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003661 Expr *BuildCounterInit() const;
3662 /// \brief Build step of the counter be used for codegen.
3663 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003664 /// \brief Return true if any expression is dependent.
3665 bool Dependent() const;
3666
3667private:
3668 /// \brief Check the right-hand side of an assignment in the increment
3669 /// expression.
3670 bool CheckIncRHS(Expr *RHS);
3671 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003672 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003673 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003674 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003675 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003676 /// \brief Helper to set loop increment.
3677 bool SetStep(Expr *NewStep, bool Subtract);
3678};
3679
3680bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003681 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682 assert(!LB && !UB && !Step);
3683 return false;
3684 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003685 return LCDecl->getType()->isDependentType() ||
3686 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3687 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003688}
3689
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003690bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3691 Expr *NewLCRefExpr,
3692 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003693 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003694 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003695 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003697 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003698 LCDecl = getCanonicalDecl(NewLCDecl);
3699 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003700 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3701 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003702 if ((Ctor->isCopyOrMoveConstructor() ||
3703 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3704 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003705 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706 LB = NewLB;
3707 return false;
3708}
3709
3710bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003711 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003712 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003713 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3714 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 if (!NewUB)
3716 return true;
3717 UB = NewUB;
3718 TestIsLessOp = LessOp;
3719 TestIsStrictOp = StrictOp;
3720 ConditionSrcRange = SR;
3721 ConditionLoc = SL;
3722 return false;
3723}
3724
3725bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3726 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003727 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003728 if (!NewStep)
3729 return true;
3730 if (!NewStep->isValueDependent()) {
3731 // Check that the step is integer expression.
3732 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003733 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3734 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003735 if (Val.isInvalid())
3736 return true;
3737 NewStep = Val.get();
3738
3739 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3740 // If test-expr is of form var relational-op b and relational-op is < or
3741 // <= then incr-expr must cause var to increase on each iteration of the
3742 // loop. If test-expr is of form var relational-op b and relational-op is
3743 // > or >= then incr-expr must cause var to decrease on each iteration of
3744 // the loop.
3745 // If test-expr is of form b relational-op var and relational-op is < or
3746 // <= then incr-expr must cause var to decrease on each iteration of the
3747 // loop. If test-expr is of form b relational-op var and relational-op is
3748 // > or >= then incr-expr must cause var to increase on each iteration of
3749 // the loop.
3750 llvm::APSInt Result;
3751 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3752 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3753 bool IsConstNeg =
3754 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003755 bool IsConstPos =
3756 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003757 bool IsConstZero = IsConstant && !Result.getBoolValue();
3758 if (UB && (IsConstZero ||
3759 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003760 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003761 SemaRef.Diag(NewStep->getExprLoc(),
3762 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003763 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003764 SemaRef.Diag(ConditionLoc,
3765 diag::note_omp_loop_cond_requres_compatible_incr)
3766 << TestIsLessOp << ConditionSrcRange;
3767 return true;
3768 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003769 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003770 NewStep =
3771 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3772 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003773 Subtract = !Subtract;
3774 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003775 }
3776
3777 Step = NewStep;
3778 SubtractStep = Subtract;
3779 return false;
3780}
3781
Alexey Bataev9c821032015-04-30 04:23:23 +00003782bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003783 // Check init-expr for canonical loop form and save loop counter
3784 // variable - #Var and its initialization value - #LB.
3785 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3786 // var = lb
3787 // integer-type var = lb
3788 // random-access-iterator-type var = lb
3789 // pointer-type var = lb
3790 //
3791 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003792 if (EmitDiags) {
3793 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3794 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003795 return true;
3796 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003797 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3798 if (!ExprTemp->cleanupsHaveSideEffects())
3799 S = ExprTemp->getSubExpr();
3800
Alexander Musmana5f070a2014-10-01 06:03:56 +00003801 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003802 if (Expr *E = dyn_cast<Expr>(S))
3803 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003804 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003805 if (BO->getOpcode() == BO_Assign) {
3806 auto *LHS = BO->getLHS()->IgnoreParens();
3807 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3808 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3809 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3810 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3811 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3812 }
3813 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3814 if (ME->isArrow() &&
3815 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3816 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3817 }
3818 }
David Majnemer9d168222016-08-05 17:44:54 +00003819 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003820 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003821 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003822 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003823 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003824 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003825 SemaRef.Diag(S->getLocStart(),
3826 diag::ext_omp_loop_not_canonical_init)
3827 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003828 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003829 }
3830 }
3831 }
David Majnemer9d168222016-08-05 17:44:54 +00003832 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003833 if (CE->getOperator() == OO_Equal) {
3834 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003835 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003836 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3837 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3838 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3839 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3840 }
3841 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3842 if (ME->isArrow() &&
3843 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3844 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3845 }
3846 }
3847 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003848
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003849 if (Dependent() || SemaRef.CurContext->isDependentContext())
3850 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003851 if (EmitDiags) {
3852 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3853 << S->getSourceRange();
3854 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003855 return true;
3856}
3857
Alexey Bataev23b69422014-06-18 07:08:49 +00003858/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003859/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003860static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003861 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003862 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003863 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003864 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3865 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003866 if ((Ctor->isCopyOrMoveConstructor() ||
3867 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3868 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003869 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003870 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003871 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003872 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003873 }
3874 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3875 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3876 return getCanonicalDecl(ME->getMemberDecl());
3877 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003878}
3879
3880bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3881 // Check test-expr for canonical form, save upper-bound UB, flags for
3882 // less/greater and for strict/non-strict comparison.
3883 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3884 // var relational-op b
3885 // b relational-op var
3886 //
3887 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003888 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003889 return true;
3890 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003891 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003892 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003893 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003894 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003895 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003896 return SetUB(BO->getRHS(),
3897 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3898 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3899 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003900 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901 return SetUB(BO->getLHS(),
3902 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3903 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3904 BO->getSourceRange(), BO->getOperatorLoc());
3905 }
David Majnemer9d168222016-08-05 17:44:54 +00003906 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003907 if (CE->getNumArgs() == 2) {
3908 auto Op = CE->getOperator();
3909 switch (Op) {
3910 case OO_Greater:
3911 case OO_GreaterEqual:
3912 case OO_Less:
3913 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003914 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003915 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3916 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3917 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003918 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003919 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3920 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3921 CE->getOperatorLoc());
3922 break;
3923 default:
3924 break;
3925 }
3926 }
3927 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003928 if (Dependent() || SemaRef.CurContext->isDependentContext())
3929 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003930 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003931 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003932 return true;
3933}
3934
3935bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3936 // RHS of canonical loop form increment can be:
3937 // var + incr
3938 // incr + var
3939 // var - incr
3940 //
3941 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003942 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003943 if (BO->isAdditiveOp()) {
3944 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003945 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003946 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003947 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003948 return SetStep(BO->getLHS(), false);
3949 }
David Majnemer9d168222016-08-05 17:44:54 +00003950 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003951 bool IsAdd = CE->getOperator() == OO_Plus;
3952 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003953 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003954 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003955 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003956 return SetStep(CE->getArg(0), false);
3957 }
3958 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003959 if (Dependent() || SemaRef.CurContext->isDependentContext())
3960 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003961 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003962 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003963 return true;
3964}
3965
3966bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3967 // Check incr-expr for canonical loop form and return true if it
3968 // does not conform.
3969 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3970 // ++var
3971 // var++
3972 // --var
3973 // var--
3974 // var += incr
3975 // var -= incr
3976 // var = var + incr
3977 // var = incr + var
3978 // var = var - incr
3979 //
3980 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003981 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003982 return true;
3983 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003984 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3985 if (!ExprTemp->cleanupsHaveSideEffects())
3986 S = ExprTemp->getSubExpr();
3987
Alexander Musmana5f070a2014-10-01 06:03:56 +00003988 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003989 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003990 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003991 if (UO->isIncrementDecrementOp() &&
3992 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003993 return SetStep(SemaRef
3994 .ActOnIntegerConstant(UO->getLocStart(),
3995 (UO->isDecrementOp() ? -1 : 1))
3996 .get(),
3997 false);
3998 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003999 switch (BO->getOpcode()) {
4000 case BO_AddAssign:
4001 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004002 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004003 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4004 break;
4005 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004006 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004007 return CheckIncRHS(BO->getRHS());
4008 break;
4009 default:
4010 break;
4011 }
David Majnemer9d168222016-08-05 17:44:54 +00004012 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004013 switch (CE->getOperator()) {
4014 case OO_PlusPlus:
4015 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004016 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00004017 return SetStep(SemaRef
4018 .ActOnIntegerConstant(
4019 CE->getLocStart(),
4020 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4021 .get(),
4022 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004023 break;
4024 case OO_PlusEqual:
4025 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004026 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004027 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4028 break;
4029 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004030 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004031 return CheckIncRHS(CE->getArg(1));
4032 break;
4033 default:
4034 break;
4035 }
4036 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004037 if (Dependent() || SemaRef.CurContext->isDependentContext())
4038 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004039 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004040 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004041 return true;
4042}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004043
Alexey Bataev5a3af132016-03-29 08:58:54 +00004044static ExprResult
4045tryBuildCapture(Sema &SemaRef, Expr *Capture,
4046 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004047 if (SemaRef.CurContext->isDependentContext())
4048 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004049 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4050 return SemaRef.PerformImplicitConversion(
4051 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4052 /*AllowExplicit=*/true);
4053 auto I = Captures.find(Capture);
4054 if (I != Captures.end())
4055 return buildCapture(SemaRef, Capture, I->second);
4056 DeclRefExpr *Ref = nullptr;
4057 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4058 Captures[Capture] = Ref;
4059 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004060}
4061
Alexander Musmana5f070a2014-10-01 06:03:56 +00004062/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004063Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4064 Scope *S, const bool LimitedType,
4065 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004066 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004067 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004068 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004069 SemaRef.getLangOpts().CPlusPlus) {
4070 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004071 auto *UBExpr = TestIsLessOp ? UB : LB;
4072 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004073 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4074 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004075 if (!Upper || !Lower)
4076 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004077
4078 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4079
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004080 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004081 // BuildBinOp already emitted error, this one is to point user to upper
4082 // and lower bound, and to tell what is passed to 'operator-'.
4083 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4084 << Upper->getSourceRange() << Lower->getSourceRange();
4085 return nullptr;
4086 }
4087 }
4088
4089 if (!Diff.isUsable())
4090 return nullptr;
4091
4092 // Upper - Lower [- 1]
4093 if (TestIsStrictOp)
4094 Diff = SemaRef.BuildBinOp(
4095 S, DefaultLoc, BO_Sub, Diff.get(),
4096 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4097 if (!Diff.isUsable())
4098 return nullptr;
4099
4100 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00004101 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4102 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004103 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004104 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004105 if (!Diff.isUsable())
4106 return nullptr;
4107
4108 // Parentheses (for dumping/debugging purposes only).
4109 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4110 if (!Diff.isUsable())
4111 return nullptr;
4112
4113 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004114 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004115 if (!Diff.isUsable())
4116 return nullptr;
4117
Alexander Musman174b3ca2014-10-06 11:16:29 +00004118 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004119 QualType Type = Diff.get()->getType();
4120 auto &C = SemaRef.Context;
4121 bool UseVarType = VarType->hasIntegerRepresentation() &&
4122 C.getTypeSize(Type) > C.getTypeSize(VarType);
4123 if (!Type->isIntegerType() || UseVarType) {
4124 unsigned NewSize =
4125 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4126 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4127 : Type->hasSignedIntegerRepresentation();
4128 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004129 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4130 Diff = SemaRef.PerformImplicitConversion(
4131 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4132 if (!Diff.isUsable())
4133 return nullptr;
4134 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004135 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004136 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004137 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4138 if (NewSize != C.getTypeSize(Type)) {
4139 if (NewSize < C.getTypeSize(Type)) {
4140 assert(NewSize == 64 && "incorrect loop var size");
4141 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4142 << InitSrcRange << ConditionSrcRange;
4143 }
4144 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004145 NewSize, Type->hasSignedIntegerRepresentation() ||
4146 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004147 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4148 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4149 Sema::AA_Converting, true);
4150 if (!Diff.isUsable())
4151 return nullptr;
4152 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004153 }
4154 }
4155
Alexander Musmana5f070a2014-10-01 06:03:56 +00004156 return Diff.get();
4157}
4158
Alexey Bataev5a3af132016-03-29 08:58:54 +00004159Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4160 Scope *S, Expr *Cond,
4161 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004162 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4163 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4164 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004165
Alexey Bataev5a3af132016-03-29 08:58:54 +00004166 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4167 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4168 if (!NewLB.isUsable() || !NewUB.isUsable())
4169 return nullptr;
4170
Alexey Bataev62dbb972015-04-22 11:59:37 +00004171 auto CondExpr = SemaRef.BuildBinOp(
4172 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4173 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004174 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004175 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004176 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4177 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004178 CondExpr = SemaRef.PerformImplicitConversion(
4179 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4180 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004181 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004182 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4183 // Otherwise use original loop conditon and evaluate it in runtime.
4184 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4185}
4186
Alexander Musmana5f070a2014-10-01 06:03:56 +00004187/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004188DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004189 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004190 auto *VD = dyn_cast<VarDecl>(LCDecl);
4191 if (!VD) {
4192 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4193 auto *Ref = buildDeclRefExpr(
4194 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004195 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4196 // If the loop control decl is explicitly marked as private, do not mark it
4197 // as captured again.
4198 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4199 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004200 return Ref;
4201 }
4202 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004203 DefaultLoc);
4204}
4205
4206Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004207 if (LCDecl && !LCDecl->isInvalidDecl()) {
4208 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004209 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004210 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4211 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004212 if (PrivateVar->isInvalidDecl())
4213 return nullptr;
4214 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4215 }
4216 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004217}
4218
Samuel Antao4c8035b2016-12-12 18:00:20 +00004219/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004220Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4221
4222/// \brief Build step of the counter be used for codegen.
4223Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4224
4225/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004226struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004227 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004228 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004229 /// \brief This expression calculates the number of iterations in the loop.
4230 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004231 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004232 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004233 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004234 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004235 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004236 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004237 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004238 /// \brief This is step for the #CounterVar used to generate its update:
4239 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004240 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004241 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004242 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004243 /// \brief Source range of the loop init.
4244 SourceRange InitSrcRange;
4245 /// \brief Source range of the loop condition.
4246 SourceRange CondSrcRange;
4247 /// \brief Source range of the loop increment.
4248 SourceRange IncSrcRange;
4249};
4250
Alexey Bataev23b69422014-06-18 07:08:49 +00004251} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004252
Alexey Bataev9c821032015-04-30 04:23:23 +00004253void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4254 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4255 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004256 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4257 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004258 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4259 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004260 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4261 if (auto *D = ISC.GetLoopDecl()) {
4262 auto *VD = dyn_cast<VarDecl>(D);
4263 if (!VD) {
4264 if (auto *Private = IsOpenMPCapturedDecl(D))
4265 VD = Private;
4266 else {
4267 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4268 /*WithInit=*/false);
4269 VD = cast<VarDecl>(Ref->getDecl());
4270 }
4271 }
4272 DSAStack->addLoopControlVariable(D, VD);
4273 }
4274 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004275 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004276 }
4277}
4278
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004279/// \brief Called on a for stmt to check and extract its iteration space
4280/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004281static bool CheckOpenMPIterationSpace(
4282 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4283 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004284 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004285 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004286 LoopIterationSpace &ResultIterSpace,
4287 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004288 // OpenMP [2.6, Canonical Loop Form]
4289 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004290 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004291 if (!For) {
4292 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004293 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4294 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4295 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4296 if (NestedLoopCount > 1) {
4297 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4298 SemaRef.Diag(DSA.getConstructLoc(),
4299 diag::note_omp_collapse_ordered_expr)
4300 << 2 << CollapseLoopCountExpr->getSourceRange()
4301 << OrderedLoopCountExpr->getSourceRange();
4302 else if (CollapseLoopCountExpr)
4303 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4304 diag::note_omp_collapse_ordered_expr)
4305 << 0 << CollapseLoopCountExpr->getSourceRange();
4306 else
4307 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4308 diag::note_omp_collapse_ordered_expr)
4309 << 1 << OrderedLoopCountExpr->getSourceRange();
4310 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004311 return true;
4312 }
4313 assert(For->getBody());
4314
4315 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4316
4317 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004318 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004319 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004320 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004321
4322 bool HasErrors = false;
4323
4324 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004325 if (auto *LCDecl = ISC.GetLoopDecl()) {
4326 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004327
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004328 // OpenMP [2.6, Canonical Loop Form]
4329 // Var is one of the following:
4330 // A variable of signed or unsigned integer type.
4331 // For C++, a variable of a random access iterator type.
4332 // For C, a variable of a pointer type.
4333 auto VarType = LCDecl->getType().getNonReferenceType();
4334 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4335 !VarType->isPointerType() &&
4336 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4337 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4338 << SemaRef.getLangOpts().CPlusPlus;
4339 HasErrors = true;
4340 }
4341
4342 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4343 // a Construct
4344 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4345 // parallel for construct is (are) private.
4346 // The loop iteration variable in the associated for-loop of a simd
4347 // construct with just one associated for-loop is linear with a
4348 // constant-linear-step that is the increment of the associated for-loop.
4349 // Exclude loop var from the list of variables with implicitly defined data
4350 // sharing attributes.
4351 VarsWithImplicitDSA.erase(LCDecl);
4352
4353 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4354 // in a Construct, C/C++].
4355 // The loop iteration variable in the associated for-loop of a simd
4356 // construct with just one associated for-loop may be listed in a linear
4357 // clause with a constant-linear-step that is the increment of the
4358 // associated for-loop.
4359 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4360 // parallel for construct may be listed in a private or lastprivate clause.
4361 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4362 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4363 // declared in the loop and it is predetermined as a private.
4364 auto PredeterminedCKind =
4365 isOpenMPSimdDirective(DKind)
4366 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4367 : OMPC_private;
4368 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4369 DVar.CKind != PredeterminedCKind) ||
4370 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4371 isOpenMPDistributeDirective(DKind)) &&
4372 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4373 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4374 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4375 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4376 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4377 << getOpenMPClauseName(PredeterminedCKind);
4378 if (DVar.RefExpr == nullptr)
4379 DVar.CKind = PredeterminedCKind;
4380 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4381 HasErrors = true;
4382 } else if (LoopDeclRefExpr != nullptr) {
4383 // Make the loop iteration variable private (for worksharing constructs),
4384 // linear (for simd directives with the only one associated loop) or
4385 // lastprivate (for simd directives with several collapsed or ordered
4386 // loops).
4387 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004388 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4389 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004390 /*FromParent=*/false);
4391 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4392 }
4393
4394 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4395
4396 // Check test-expr.
4397 HasErrors |= ISC.CheckCond(For->getCond());
4398
4399 // Check incr-expr.
4400 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004401 }
4402
Alexander Musmana5f070a2014-10-01 06:03:56 +00004403 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004404 return HasErrors;
4405
Alexander Musmana5f070a2014-10-01 06:03:56 +00004406 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004407 ResultIterSpace.PreCond =
4408 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004409 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004410 DSA.getCurScope(),
4411 (isOpenMPWorksharingDirective(DKind) ||
4412 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4413 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004414 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004415 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004416 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4417 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4418 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4419 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4420 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4421 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4422
Alexey Bataev62dbb972015-04-22 11:59:37 +00004423 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4424 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004425 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004426 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004427 ResultIterSpace.CounterInit == nullptr ||
4428 ResultIterSpace.CounterStep == nullptr);
4429
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004430 return HasErrors;
4431}
4432
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004433/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004434static ExprResult
4435BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4436 ExprResult Start,
4437 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004438 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004439 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4440 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004441 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004442 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004443 VarRef.get()->getType())) {
4444 NewStart = SemaRef.PerformImplicitConversion(
4445 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4446 /*AllowExplicit=*/true);
4447 if (!NewStart.isUsable())
4448 return ExprError();
4449 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004450
4451 auto Init =
4452 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4453 return Init;
4454}
4455
Alexander Musmana5f070a2014-10-01 06:03:56 +00004456/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004457static ExprResult
4458BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4459 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4460 ExprResult Step, bool Subtract,
4461 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004462 // Add parentheses (for debugging purposes only).
4463 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4464 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4465 !Step.isUsable())
4466 return ExprError();
4467
Alexey Bataev5a3af132016-03-29 08:58:54 +00004468 ExprResult NewStep = Step;
4469 if (Captures)
4470 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004471 if (NewStep.isInvalid())
4472 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004473 ExprResult Update =
4474 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004475 if (!Update.isUsable())
4476 return ExprError();
4477
Alexey Bataevc0214e02016-02-16 12:13:49 +00004478 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4479 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004480 ExprResult NewStart = Start;
4481 if (Captures)
4482 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004483 if (NewStart.isInvalid())
4484 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004485
Alexey Bataevc0214e02016-02-16 12:13:49 +00004486 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4487 ExprResult SavedUpdate = Update;
4488 ExprResult UpdateVal;
4489 if (VarRef.get()->getType()->isOverloadableType() ||
4490 NewStart.get()->getType()->isOverloadableType() ||
4491 Update.get()->getType()->isOverloadableType()) {
4492 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4493 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4494 Update =
4495 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4496 if (Update.isUsable()) {
4497 UpdateVal =
4498 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4499 VarRef.get(), SavedUpdate.get());
4500 if (UpdateVal.isUsable()) {
4501 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4502 UpdateVal.get());
4503 }
4504 }
4505 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4506 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004507
Alexey Bataevc0214e02016-02-16 12:13:49 +00004508 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4509 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4510 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4511 NewStart.get(), SavedUpdate.get());
4512 if (!Update.isUsable())
4513 return ExprError();
4514
Alexey Bataev11481f52016-02-17 10:29:05 +00004515 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4516 VarRef.get()->getType())) {
4517 Update = SemaRef.PerformImplicitConversion(
4518 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4519 if (!Update.isUsable())
4520 return ExprError();
4521 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004522
4523 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4524 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004525 return Update;
4526}
4527
4528/// \brief Convert integer expression \a E to make it have at least \a Bits
4529/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004530static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004531 if (E == nullptr)
4532 return ExprError();
4533 auto &C = SemaRef.Context;
4534 QualType OldType = E->getType();
4535 unsigned HasBits = C.getTypeSize(OldType);
4536 if (HasBits >= Bits)
4537 return ExprResult(E);
4538 // OK to convert to signed, because new type has more bits than old.
4539 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4540 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4541 true);
4542}
4543
4544/// \brief Check if the given expression \a E is a constant integer that fits
4545/// into \a Bits bits.
4546static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4547 if (E == nullptr)
4548 return false;
4549 llvm::APSInt Result;
4550 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4551 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4552 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004553}
4554
Alexey Bataev5a3af132016-03-29 08:58:54 +00004555/// Build preinits statement for the given declarations.
4556static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004557 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004558 if (!PreInits.empty()) {
4559 return new (Context) DeclStmt(
4560 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4561 SourceLocation(), SourceLocation());
4562 }
4563 return nullptr;
4564}
4565
4566/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004567static Stmt *
4568buildPreInits(ASTContext &Context,
4569 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004570 if (!Captures.empty()) {
4571 SmallVector<Decl *, 16> PreInits;
4572 for (auto &Pair : Captures)
4573 PreInits.push_back(Pair.second->getDecl());
4574 return buildPreInits(Context, PreInits);
4575 }
4576 return nullptr;
4577}
4578
4579/// Build postupdate expression for the given list of postupdates expressions.
4580static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4581 Expr *PostUpdate = nullptr;
4582 if (!PostUpdates.empty()) {
4583 for (auto *E : PostUpdates) {
4584 Expr *ConvE = S.BuildCStyleCastExpr(
4585 E->getExprLoc(),
4586 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4587 E->getExprLoc(), E)
4588 .get();
4589 PostUpdate = PostUpdate
4590 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4591 PostUpdate, ConvE)
4592 .get()
4593 : ConvE;
4594 }
4595 }
4596 return PostUpdate;
4597}
4598
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004599/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004600/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4601/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004602static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004603CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4604 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4605 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004606 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004607 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004608 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004609 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004610 // Found 'collapse' clause - calculate collapse number.
4611 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004612 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004613 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004614 }
4615 if (OrderedLoopCountExpr) {
4616 // Found 'ordered' clause - calculate collapse number.
4617 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004618 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4619 if (Result.getLimitedValue() < NestedLoopCount) {
4620 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4621 diag::err_omp_wrong_ordered_loop_count)
4622 << OrderedLoopCountExpr->getSourceRange();
4623 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4624 diag::note_collapse_loop_count)
4625 << CollapseLoopCountExpr->getSourceRange();
4626 }
4627 NestedLoopCount = Result.getLimitedValue();
4628 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004629 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004630 // This is helper routine for loop directives (e.g., 'for', 'simd',
4631 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004632 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004633 SmallVector<LoopIterationSpace, 4> IterSpaces;
4634 IterSpaces.resize(NestedLoopCount);
4635 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004636 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004637 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004638 NestedLoopCount, CollapseLoopCountExpr,
4639 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004640 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004641 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004642 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004643 // OpenMP [2.8.1, simd construct, Restrictions]
4644 // All loops associated with the construct must be perfectly nested; that
4645 // is, there must be no intervening code nor any OpenMP directive between
4646 // any two loops.
4647 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004648 }
4649
Alexander Musmana5f070a2014-10-01 06:03:56 +00004650 Built.clear(/* size */ NestedLoopCount);
4651
4652 if (SemaRef.CurContext->isDependentContext())
4653 return NestedLoopCount;
4654
4655 // An example of what is generated for the following code:
4656 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004657 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004658 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004659 // for (k = 0; k < NK; ++k)
4660 // for (j = J0; j < NJ; j+=2) {
4661 // <loop body>
4662 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004663 //
4664 // We generate the code below.
4665 // Note: the loop body may be outlined in CodeGen.
4666 // Note: some counters may be C++ classes, operator- is used to find number of
4667 // iterations and operator+= to calculate counter value.
4668 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4669 // or i64 is currently supported).
4670 //
4671 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4672 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4673 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4674 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4675 // // similar updates for vars in clauses (e.g. 'linear')
4676 // <loop body (using local i and j)>
4677 // }
4678 // i = NI; // assign final values of counters
4679 // j = NJ;
4680 //
4681
4682 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4683 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004684 // Precondition tests if there is at least one iteration (all conditions are
4685 // true).
4686 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004687 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004688 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004689 32 /* Bits */, SemaRef
4690 .PerformImplicitConversion(
4691 N0->IgnoreImpCasts(), N0->getType(),
4692 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004693 .get(),
4694 SemaRef);
4695 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004696 64 /* Bits */, SemaRef
4697 .PerformImplicitConversion(
4698 N0->IgnoreImpCasts(), N0->getType(),
4699 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004700 .get(),
4701 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004702
4703 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4704 return NestedLoopCount;
4705
4706 auto &C = SemaRef.Context;
4707 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4708
4709 Scope *CurScope = DSA.getCurScope();
4710 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004711 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004712 PreCond =
4713 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4714 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004715 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004716 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004717 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004718 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4719 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004720 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004721 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004722 SemaRef
4723 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4724 Sema::AA_Converting,
4725 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004726 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004727 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004728 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004729 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004730 SemaRef
4731 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4732 Sema::AA_Converting,
4733 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004734 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004735 }
4736
4737 // Choose either the 32-bit or 64-bit version.
4738 ExprResult LastIteration = LastIteration64;
4739 if (LastIteration32.isUsable() &&
4740 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4741 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4742 FitsInto(
4743 32 /* Bits */,
4744 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4745 LastIteration64.get(), SemaRef)))
4746 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004747 QualType VType = LastIteration.get()->getType();
4748 QualType RealVType = VType;
4749 QualType StrideVType = VType;
4750 if (isOpenMPTaskLoopDirective(DKind)) {
4751 VType =
4752 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4753 StrideVType =
4754 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4755 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004756
4757 if (!LastIteration.isUsable())
4758 return 0;
4759
4760 // Save the number of iterations.
4761 ExprResult NumIterations = LastIteration;
4762 {
4763 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004764 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4765 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004766 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4767 if (!LastIteration.isUsable())
4768 return 0;
4769 }
4770
4771 // Calculate the last iteration number beforehand instead of doing this on
4772 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4773 llvm::APSInt Result;
4774 bool IsConstant =
4775 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4776 ExprResult CalcLastIteration;
4777 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004778 ExprResult SaveRef =
4779 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004780 LastIteration = SaveRef;
4781
4782 // Prepare SaveRef + 1.
4783 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004784 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004785 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4786 if (!NumIterations.isUsable())
4787 return 0;
4788 }
4789
4790 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4791
David Majnemer9d168222016-08-05 17:44:54 +00004792 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004793 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004794 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4795 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004796 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004797 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4798 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004799 SemaRef.AddInitializerToDecl(LBDecl,
4800 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4801 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004802
4803 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004804 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4805 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004806 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004807 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004808
4809 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4810 // This will be used to implement clause 'lastprivate'.
4811 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004812 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4813 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004814 SemaRef.AddInitializerToDecl(ILDecl,
4815 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4816 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004817
4818 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004819 VarDecl *STDecl =
4820 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4821 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004822 SemaRef.AddInitializerToDecl(STDecl,
4823 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4824 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004825
4826 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004827 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004828 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4829 UB.get(), LastIteration.get());
4830 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4831 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4832 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4833 CondOp.get());
4834 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004835
4836 // If we have a combined directive that combines 'distribute', 'for' or
4837 // 'simd' we need to be able to access the bounds of the schedule of the
4838 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4839 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4840 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004841
Carlo Bertolliffafe102017-04-20 00:39:39 +00004842 // Lower bound variable, initialized with zero.
4843 VarDecl *CombLBDecl =
4844 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4845 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4846 SemaRef.AddInitializerToDecl(
4847 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4848 /*DirectInit*/ false);
4849
4850 // Upper bound variable, initialized with last iteration number.
4851 VarDecl *CombUBDecl =
4852 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4853 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4854 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4855 /*DirectInit*/ false);
4856
4857 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4858 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4859 ExprResult CombCondOp =
4860 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4861 LastIteration.get(), CombUB.get());
4862 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4863 CombCondOp.get());
4864 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4865
4866 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004867 // We expect to have at least 2 more parameters than the 'parallel'
4868 // directive does - the lower and upper bounds of the previous schedule.
4869 assert(CD->getNumParams() >= 4 &&
4870 "Unexpected number of parameters in loop combined directive");
4871
4872 // Set the proper type for the bounds given what we learned from the
4873 // enclosed loops.
4874 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4875 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4876
4877 // Previous lower and upper bounds are obtained from the region
4878 // parameters.
4879 PrevLB =
4880 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4881 PrevUB =
4882 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4883 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004884 }
4885
4886 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004887 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004888 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004889 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004890 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4891 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004892 Expr *RHS =
4893 (isOpenMPWorksharingDirective(DKind) ||
4894 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4895 ? LB.get()
4896 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004897 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4898 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004899
4900 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4901 Expr *CombRHS =
4902 (isOpenMPWorksharingDirective(DKind) ||
4903 isOpenMPTaskLoopDirective(DKind) ||
4904 isOpenMPDistributeDirective(DKind))
4905 ? CombLB.get()
4906 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4907 CombInit =
4908 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4909 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4910 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004911 }
4912
Alexander Musmanc6388682014-12-15 07:07:06 +00004913 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004914 SourceLocation CondLoc = AStmt->getLocStart();
Alexander Musmanc6388682014-12-15 07:07:06 +00004915 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004916 (isOpenMPWorksharingDirective(DKind) ||
4917 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004918 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4919 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4920 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004921 ExprResult CombCond;
4922 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4923 CombCond =
4924 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4925 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004926 // Loop increment (IV = IV + 1)
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004927 SourceLocation IncLoc = AStmt->getLocStart();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004928 ExprResult Inc =
4929 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4930 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4931 if (!Inc.isUsable())
4932 return 0;
4933 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004934 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4935 if (!Inc.isUsable())
4936 return 0;
4937
4938 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4939 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004940 // In combined construct, add combined version that use CombLB and CombUB
4941 // base variables for the update
4942 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004943 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4944 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004945 // LB + ST
4946 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4947 if (!NextLB.isUsable())
4948 return 0;
4949 // LB = LB + ST
4950 NextLB =
4951 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4952 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4953 if (!NextLB.isUsable())
4954 return 0;
4955 // UB + ST
4956 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4957 if (!NextUB.isUsable())
4958 return 0;
4959 // UB = UB + ST
4960 NextUB =
4961 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4962 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4963 if (!NextUB.isUsable())
4964 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004965 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4966 CombNextLB =
4967 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4968 if (!NextLB.isUsable())
4969 return 0;
4970 // LB = LB + ST
4971 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4972 CombNextLB.get());
4973 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4974 if (!CombNextLB.isUsable())
4975 return 0;
4976 // UB + ST
4977 CombNextUB =
4978 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4979 if (!CombNextUB.isUsable())
4980 return 0;
4981 // UB = UB + ST
4982 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4983 CombNextUB.get());
4984 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4985 if (!CombNextUB.isUsable())
4986 return 0;
4987 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004988 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004989
Carlo Bertolliffafe102017-04-20 00:39:39 +00004990 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004991 // directive with for as IV = IV + ST; ensure upper bound expression based
4992 // on PrevUB instead of NumIterations - used to implement 'for' when found
4993 // in combination with 'distribute', like in 'distribute parallel for'
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004994 SourceLocation DistIncLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004995 ExprResult DistCond, DistInc, PrevEUB;
4996 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4997 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4998 assert(DistCond.isUsable() && "distribute cond expr was not built");
4999
5000 DistInc =
5001 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5002 assert(DistInc.isUsable() && "distribute inc expr was not built");
5003 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5004 DistInc.get());
5005 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5006 assert(DistInc.isUsable() && "distribute inc expr was not built");
5007
5008 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5009 // construct
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005010 SourceLocation DistEUBLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005011 ExprResult IsUBGreater =
5012 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5013 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5014 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5015 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5016 CondOp.get());
5017 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5018 }
5019
Alexander Musmana5f070a2014-10-01 06:03:56 +00005020 // Build updates and final values of the loop counters.
5021 bool HasErrors = false;
5022 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005023 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005024 Built.Updates.resize(NestedLoopCount);
5025 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00005026 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005027 {
5028 ExprResult Div;
5029 // Go from inner nested loop to outer.
5030 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5031 LoopIterationSpace &IS = IterSpaces[Cnt];
5032 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5033 // Build: Iter = (IV / Div) % IS.NumIters
5034 // where Div is product of previous iterations' IS.NumIters.
5035 ExprResult Iter;
5036 if (Div.isUsable()) {
5037 Iter =
5038 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5039 } else {
5040 Iter = IV;
5041 assert((Cnt == (int)NestedLoopCount - 1) &&
5042 "unusable div expected on first iteration only");
5043 }
5044
5045 if (Cnt != 0 && Iter.isUsable())
5046 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5047 IS.NumIterations);
5048 if (!Iter.isUsable()) {
5049 HasErrors = true;
5050 break;
5051 }
5052
Alexey Bataev39f915b82015-05-08 10:41:21 +00005053 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005054 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5055 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
5056 IS.CounterVar->getExprLoc(),
5057 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005058 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005059 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005060 if (!Init.isUsable()) {
5061 HasErrors = true;
5062 break;
5063 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00005064 ExprResult Update = BuildCounterUpdate(
5065 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5066 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005067 if (!Update.isUsable()) {
5068 HasErrors = true;
5069 break;
5070 }
5071
5072 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5073 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005074 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005075 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005076 if (!Final.isUsable()) {
5077 HasErrors = true;
5078 break;
5079 }
5080
5081 // Build Div for the next iteration: Div <- Div * IS.NumIters
5082 if (Cnt != 0) {
5083 if (Div.isUnset())
5084 Div = IS.NumIterations;
5085 else
5086 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5087 IS.NumIterations);
5088
5089 // Add parentheses (for debugging purposes only).
5090 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00005091 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005092 if (!Div.isUsable()) {
5093 HasErrors = true;
5094 break;
5095 }
Alexey Bataev8b427062016-05-25 12:36:08 +00005096 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005097 }
5098 if (!Update.isUsable() || !Final.isUsable()) {
5099 HasErrors = true;
5100 break;
5101 }
5102 // Save results
5103 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005104 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005105 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005106 Built.Updates[Cnt] = Update.get();
5107 Built.Finals[Cnt] = Final.get();
5108 }
5109 }
5110
5111 if (HasErrors)
5112 return 0;
5113
5114 // Save results
5115 Built.IterationVarRef = IV.get();
5116 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005117 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005118 Built.CalcLastIteration =
5119 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005120 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005121 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005122 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005123 Built.Init = Init.get();
5124 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005125 Built.LB = LB.get();
5126 Built.UB = UB.get();
5127 Built.IL = IL.get();
5128 Built.ST = ST.get();
5129 Built.EUB = EUB.get();
5130 Built.NLB = NextLB.get();
5131 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005132 Built.PrevLB = PrevLB.get();
5133 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005134 Built.DistInc = DistInc.get();
5135 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005136 Built.DistCombinedFields.LB = CombLB.get();
5137 Built.DistCombinedFields.UB = CombUB.get();
5138 Built.DistCombinedFields.EUB = CombEUB.get();
5139 Built.DistCombinedFields.Init = CombInit.get();
5140 Built.DistCombinedFields.Cond = CombCond.get();
5141 Built.DistCombinedFields.NLB = CombNextLB.get();
5142 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005143
Alexey Bataev8b427062016-05-25 12:36:08 +00005144 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5145 // Fill data for doacross depend clauses.
5146 for (auto Pair : DSA.getDoacrossDependClauses()) {
5147 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5148 Pair.first->setCounterValue(CounterVal);
5149 else {
5150 if (NestedLoopCount != Pair.second.size() ||
5151 NestedLoopCount != LoopMultipliers.size() + 1) {
5152 // Erroneous case - clause has some problems.
5153 Pair.first->setCounterValue(CounterVal);
5154 continue;
5155 }
5156 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5157 auto I = Pair.second.rbegin();
5158 auto IS = IterSpaces.rbegin();
5159 auto ILM = LoopMultipliers.rbegin();
5160 Expr *UpCounterVal = CounterVal;
5161 Expr *Multiplier = nullptr;
5162 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5163 if (I->first) {
5164 assert(IS->CounterStep);
5165 Expr *NormalizedOffset =
5166 SemaRef
5167 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5168 I->first, IS->CounterStep)
5169 .get();
5170 if (Multiplier) {
5171 NormalizedOffset =
5172 SemaRef
5173 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5174 NormalizedOffset, Multiplier)
5175 .get();
5176 }
5177 assert(I->second == OO_Plus || I->second == OO_Minus);
5178 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005179 UpCounterVal = SemaRef
5180 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5181 UpCounterVal, NormalizedOffset)
5182 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005183 }
5184 Multiplier = *ILM;
5185 ++I;
5186 ++IS;
5187 ++ILM;
5188 }
5189 Pair.first->setCounterValue(UpCounterVal);
5190 }
5191 }
5192
Alexey Bataevabfc0692014-06-25 06:52:00 +00005193 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005194}
5195
Alexey Bataev10e775f2015-07-30 11:36:16 +00005196static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005197 auto CollapseClauses =
5198 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5199 if (CollapseClauses.begin() != CollapseClauses.end())
5200 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005201 return nullptr;
5202}
5203
Alexey Bataev10e775f2015-07-30 11:36:16 +00005204static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005205 auto OrderedClauses =
5206 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5207 if (OrderedClauses.begin() != OrderedClauses.end())
5208 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005209 return nullptr;
5210}
5211
Kelvin Lic5609492016-07-15 04:39:07 +00005212static bool checkSimdlenSafelenSpecified(Sema &S,
5213 const ArrayRef<OMPClause *> Clauses) {
5214 OMPSafelenClause *Safelen = nullptr;
5215 OMPSimdlenClause *Simdlen = nullptr;
5216
5217 for (auto *Clause : Clauses) {
5218 if (Clause->getClauseKind() == OMPC_safelen)
5219 Safelen = cast<OMPSafelenClause>(Clause);
5220 else if (Clause->getClauseKind() == OMPC_simdlen)
5221 Simdlen = cast<OMPSimdlenClause>(Clause);
5222 if (Safelen && Simdlen)
5223 break;
5224 }
5225
5226 if (Simdlen && Safelen) {
5227 llvm::APSInt SimdlenRes, SafelenRes;
5228 auto SimdlenLength = Simdlen->getSimdlen();
5229 auto SafelenLength = Safelen->getSafelen();
5230 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5231 SimdlenLength->isInstantiationDependent() ||
5232 SimdlenLength->containsUnexpandedParameterPack())
5233 return false;
5234 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5235 SafelenLength->isInstantiationDependent() ||
5236 SafelenLength->containsUnexpandedParameterPack())
5237 return false;
5238 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5239 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5240 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5241 // If both simdlen and safelen clauses are specified, the value of the
5242 // simdlen parameter must be less than or equal to the value of the safelen
5243 // parameter.
5244 if (SimdlenRes > SafelenRes) {
5245 S.Diag(SimdlenLength->getExprLoc(),
5246 diag::err_omp_wrong_simdlen_safelen_values)
5247 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5248 return true;
5249 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005250 }
5251 return false;
5252}
5253
Alexey Bataev4acb8592014-07-07 13:01:15 +00005254StmtResult Sema::ActOnOpenMPSimdDirective(
5255 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5256 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005257 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005258 if (!AStmt)
5259 return StmtError();
5260
5261 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005262 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005263 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5264 // define the nested loops number.
5265 unsigned NestedLoopCount = CheckOpenMPLoop(
5266 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5267 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005268 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005269 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005270
Alexander Musmana5f070a2014-10-01 06:03:56 +00005271 assert((CurContext->isDependentContext() || B.builtAll()) &&
5272 "omp simd loop exprs were not built");
5273
Alexander Musman3276a272015-03-21 10:12:56 +00005274 if (!CurContext->isDependentContext()) {
5275 // Finalize the clauses that need pre-built expressions for CodeGen.
5276 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005277 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005278 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005279 B.NumIterations, *this, CurScope,
5280 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005281 return StmtError();
5282 }
5283 }
5284
Kelvin Lic5609492016-07-15 04:39:07 +00005285 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005286 return StmtError();
5287
Reid Kleckner87a31802018-03-12 21:43:02 +00005288 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005289 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5290 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005291}
5292
Alexey Bataev4acb8592014-07-07 13:01:15 +00005293StmtResult Sema::ActOnOpenMPForDirective(
5294 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5295 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005296 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005297 if (!AStmt)
5298 return StmtError();
5299
5300 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005301 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005302 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5303 // define the nested loops number.
5304 unsigned NestedLoopCount = CheckOpenMPLoop(
5305 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5306 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005307 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005308 return StmtError();
5309
Alexander Musmana5f070a2014-10-01 06:03:56 +00005310 assert((CurContext->isDependentContext() || B.builtAll()) &&
5311 "omp for loop exprs were not built");
5312
Alexey Bataev54acd402015-08-04 11:18:19 +00005313 if (!CurContext->isDependentContext()) {
5314 // Finalize the clauses that need pre-built expressions for CodeGen.
5315 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005316 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005317 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005318 B.NumIterations, *this, CurScope,
5319 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005320 return StmtError();
5321 }
5322 }
5323
Reid Kleckner87a31802018-03-12 21:43:02 +00005324 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005325 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005326 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005327}
5328
Alexander Musmanf82886e2014-09-18 05:12:34 +00005329StmtResult Sema::ActOnOpenMPForSimdDirective(
5330 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5331 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005332 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005333 if (!AStmt)
5334 return StmtError();
5335
5336 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005337 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005338 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5339 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005340 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005341 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5342 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5343 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005344 if (NestedLoopCount == 0)
5345 return StmtError();
5346
Alexander Musmanc6388682014-12-15 07:07:06 +00005347 assert((CurContext->isDependentContext() || B.builtAll()) &&
5348 "omp for simd loop exprs were not built");
5349
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005350 if (!CurContext->isDependentContext()) {
5351 // Finalize the clauses that need pre-built expressions for CodeGen.
5352 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005353 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005354 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005355 B.NumIterations, *this, CurScope,
5356 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005357 return StmtError();
5358 }
5359 }
5360
Kelvin Lic5609492016-07-15 04:39:07 +00005361 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005362 return StmtError();
5363
Reid Kleckner87a31802018-03-12 21:43:02 +00005364 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005365 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5366 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005367}
5368
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005369StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5370 Stmt *AStmt,
5371 SourceLocation StartLoc,
5372 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005373 if (!AStmt)
5374 return StmtError();
5375
5376 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005377 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005378 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005379 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005380 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005381 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005382 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005383 return StmtError();
5384 // All associated statements must be '#pragma omp section' except for
5385 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005386 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005387 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5388 if (SectionStmt)
5389 Diag(SectionStmt->getLocStart(),
5390 diag::err_omp_sections_substmt_not_section);
5391 return StmtError();
5392 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005393 cast<OMPSectionDirective>(SectionStmt)
5394 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005395 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005396 } else {
5397 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5398 return StmtError();
5399 }
5400
Reid Kleckner87a31802018-03-12 21:43:02 +00005401 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005402
Alexey Bataev25e5b442015-09-15 12:52:43 +00005403 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5404 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005405}
5406
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005407StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5408 SourceLocation StartLoc,
5409 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005410 if (!AStmt)
5411 return StmtError();
5412
5413 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005414
Reid Kleckner87a31802018-03-12 21:43:02 +00005415 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005416 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005417
Alexey Bataev25e5b442015-09-15 12:52:43 +00005418 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5419 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005420}
5421
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005422StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5423 Stmt *AStmt,
5424 SourceLocation StartLoc,
5425 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005426 if (!AStmt)
5427 return StmtError();
5428
5429 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005430
Reid Kleckner87a31802018-03-12 21:43:02 +00005431 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005432
Alexey Bataev3255bf32015-01-19 05:20:46 +00005433 // OpenMP [2.7.3, single Construct, Restrictions]
5434 // The copyprivate clause must not be used with the nowait clause.
5435 OMPClause *Nowait = nullptr;
5436 OMPClause *Copyprivate = nullptr;
5437 for (auto *Clause : Clauses) {
5438 if (Clause->getClauseKind() == OMPC_nowait)
5439 Nowait = Clause;
5440 else if (Clause->getClauseKind() == OMPC_copyprivate)
5441 Copyprivate = Clause;
5442 if (Copyprivate && Nowait) {
5443 Diag(Copyprivate->getLocStart(),
5444 diag::err_omp_single_copyprivate_with_nowait);
5445 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5446 return StmtError();
5447 }
5448 }
5449
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005450 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5451}
5452
Alexander Musman80c22892014-07-17 08:54:58 +00005453StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5454 SourceLocation StartLoc,
5455 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005456 if (!AStmt)
5457 return StmtError();
5458
5459 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005460
Reid Kleckner87a31802018-03-12 21:43:02 +00005461 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00005462
5463 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5464}
5465
Alexey Bataev28c75412015-12-15 08:19:24 +00005466StmtResult Sema::ActOnOpenMPCriticalDirective(
5467 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5468 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005469 if (!AStmt)
5470 return StmtError();
5471
5472 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005473
Alexey Bataev28c75412015-12-15 08:19:24 +00005474 bool ErrorFound = false;
5475 llvm::APSInt Hint;
5476 SourceLocation HintLoc;
5477 bool DependentHint = false;
5478 for (auto *C : Clauses) {
5479 if (C->getClauseKind() == OMPC_hint) {
5480 if (!DirName.getName()) {
5481 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5482 ErrorFound = true;
5483 }
5484 Expr *E = cast<OMPHintClause>(C)->getHint();
5485 if (E->isTypeDependent() || E->isValueDependent() ||
5486 E->isInstantiationDependent())
5487 DependentHint = true;
5488 else {
5489 Hint = E->EvaluateKnownConstInt(Context);
5490 HintLoc = C->getLocStart();
5491 }
5492 }
5493 }
5494 if (ErrorFound)
5495 return StmtError();
5496 auto Pair = DSAStack->getCriticalWithHint(DirName);
5497 if (Pair.first && DirName.getName() && !DependentHint) {
5498 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5499 Diag(StartLoc, diag::err_omp_critical_with_hint);
5500 if (HintLoc.isValid()) {
5501 Diag(HintLoc, diag::note_omp_critical_hint_here)
5502 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5503 } else
5504 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5505 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5506 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5507 << 1
5508 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5509 /*Radix=*/10, /*Signed=*/false);
5510 } else
5511 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5512 }
5513 }
5514
Reid Kleckner87a31802018-03-12 21:43:02 +00005515 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005516
Alexey Bataev28c75412015-12-15 08:19:24 +00005517 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5518 Clauses, AStmt);
5519 if (!Pair.first && DirName.getName() && !DependentHint)
5520 DSAStack->addCriticalWithHint(Dir, Hint);
5521 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005522}
5523
Alexey Bataev4acb8592014-07-07 13:01:15 +00005524StmtResult Sema::ActOnOpenMPParallelForDirective(
5525 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5526 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005527 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005528 if (!AStmt)
5529 return StmtError();
5530
Alexey Bataev4acb8592014-07-07 13:01:15 +00005531 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5532 // 1.2.2 OpenMP Language Terminology
5533 // Structured block - An executable statement with a single entry at the
5534 // top and a single exit at the bottom.
5535 // The point of exit cannot be a branch out of the structured block.
5536 // longjmp() and throw() must not violate the entry/exit criteria.
5537 CS->getCapturedDecl()->setNothrow();
5538
Alexander Musmanc6388682014-12-15 07:07:06 +00005539 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005540 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5541 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005542 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005543 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5544 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5545 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005546 if (NestedLoopCount == 0)
5547 return StmtError();
5548
Alexander Musmana5f070a2014-10-01 06:03:56 +00005549 assert((CurContext->isDependentContext() || B.builtAll()) &&
5550 "omp parallel for loop exprs were not built");
5551
Alexey Bataev54acd402015-08-04 11:18:19 +00005552 if (!CurContext->isDependentContext()) {
5553 // Finalize the clauses that need pre-built expressions for CodeGen.
5554 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005555 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005556 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005557 B.NumIterations, *this, CurScope,
5558 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005559 return StmtError();
5560 }
5561 }
5562
Reid Kleckner87a31802018-03-12 21:43:02 +00005563 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005564 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005565 NestedLoopCount, Clauses, AStmt, B,
5566 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005567}
5568
Alexander Musmane4e893b2014-09-23 09:33:00 +00005569StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5570 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5571 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005572 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005573 if (!AStmt)
5574 return StmtError();
5575
Alexander Musmane4e893b2014-09-23 09:33:00 +00005576 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5577 // 1.2.2 OpenMP Language Terminology
5578 // Structured block - An executable statement with a single entry at the
5579 // top and a single exit at the bottom.
5580 // The point of exit cannot be a branch out of the structured block.
5581 // longjmp() and throw() must not violate the entry/exit criteria.
5582 CS->getCapturedDecl()->setNothrow();
5583
Alexander Musmanc6388682014-12-15 07:07:06 +00005584 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005585 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5586 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005587 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005588 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5589 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5590 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005591 if (NestedLoopCount == 0)
5592 return StmtError();
5593
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005594 if (!CurContext->isDependentContext()) {
5595 // Finalize the clauses that need pre-built expressions for CodeGen.
5596 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005597 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005598 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005599 B.NumIterations, *this, CurScope,
5600 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005601 return StmtError();
5602 }
5603 }
5604
Kelvin Lic5609492016-07-15 04:39:07 +00005605 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005606 return StmtError();
5607
Reid Kleckner87a31802018-03-12 21:43:02 +00005608 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005609 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005610 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005611}
5612
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005613StmtResult
5614Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5615 Stmt *AStmt, SourceLocation StartLoc,
5616 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005617 if (!AStmt)
5618 return StmtError();
5619
5620 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005621 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005622 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005623 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005624 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005625 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005626 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005627 return StmtError();
5628 // All associated statements must be '#pragma omp section' except for
5629 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005630 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005631 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5632 if (SectionStmt)
5633 Diag(SectionStmt->getLocStart(),
5634 diag::err_omp_parallel_sections_substmt_not_section);
5635 return StmtError();
5636 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005637 cast<OMPSectionDirective>(SectionStmt)
5638 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005639 }
5640 } else {
5641 Diag(AStmt->getLocStart(),
5642 diag::err_omp_parallel_sections_not_compound_stmt);
5643 return StmtError();
5644 }
5645
Reid Kleckner87a31802018-03-12 21:43:02 +00005646 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005647
Alexey Bataev25e5b442015-09-15 12:52:43 +00005648 return OMPParallelSectionsDirective::Create(
5649 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005650}
5651
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005652StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5653 Stmt *AStmt, SourceLocation StartLoc,
5654 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005655 if (!AStmt)
5656 return StmtError();
5657
David Majnemer9d168222016-08-05 17:44:54 +00005658 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005659 // 1.2.2 OpenMP Language Terminology
5660 // Structured block - An executable statement with a single entry at the
5661 // top and a single exit at the bottom.
5662 // The point of exit cannot be a branch out of the structured block.
5663 // longjmp() and throw() must not violate the entry/exit criteria.
5664 CS->getCapturedDecl()->setNothrow();
5665
Reid Kleckner87a31802018-03-12 21:43:02 +00005666 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005667
Alexey Bataev25e5b442015-09-15 12:52:43 +00005668 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5669 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005670}
5671
Alexey Bataev68446b72014-07-18 07:47:19 +00005672StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5673 SourceLocation EndLoc) {
5674 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5675}
5676
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005677StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5678 SourceLocation EndLoc) {
5679 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5680}
5681
Alexey Bataev2df347a2014-07-18 10:17:07 +00005682StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5683 SourceLocation EndLoc) {
5684 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5685}
5686
Alexey Bataev169d96a2017-07-18 20:17:46 +00005687StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5688 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005689 SourceLocation StartLoc,
5690 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005691 if (!AStmt)
5692 return StmtError();
5693
5694 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005695
Reid Kleckner87a31802018-03-12 21:43:02 +00005696 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005697
Alexey Bataev169d96a2017-07-18 20:17:46 +00005698 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005699 AStmt,
5700 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005701}
5702
Alexey Bataev6125da92014-07-21 11:26:11 +00005703StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5704 SourceLocation StartLoc,
5705 SourceLocation EndLoc) {
5706 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5707 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5708}
5709
Alexey Bataev346265e2015-09-25 10:37:12 +00005710StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5711 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005712 SourceLocation StartLoc,
5713 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005714 OMPClause *DependFound = nullptr;
5715 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005716 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005717 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005718 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005719 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005720 for (auto *C : Clauses) {
5721 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5722 DependFound = C;
5723 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5724 if (DependSourceClause) {
5725 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5726 << getOpenMPDirectiveName(OMPD_ordered)
5727 << getOpenMPClauseName(OMPC_depend) << 2;
5728 ErrorFound = true;
5729 } else
5730 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005731 if (DependSinkClause) {
5732 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5733 << 0;
5734 ErrorFound = true;
5735 }
5736 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5737 if (DependSourceClause) {
5738 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5739 << 1;
5740 ErrorFound = true;
5741 }
5742 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005743 }
5744 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005745 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005746 else if (C->getClauseKind() == OMPC_simd)
5747 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005748 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005749 if (!ErrorFound && !SC &&
5750 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005751 // OpenMP [2.8.1,simd Construct, Restrictions]
5752 // An ordered construct with the simd clause is the only OpenMP construct
5753 // that can appear in the simd region.
5754 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005755 ErrorFound = true;
5756 } else if (DependFound && (TC || SC)) {
5757 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5758 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5759 ErrorFound = true;
5760 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5761 Diag(DependFound->getLocStart(),
5762 diag::err_omp_ordered_directive_without_param);
5763 ErrorFound = true;
5764 } else if (TC || Clauses.empty()) {
5765 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5766 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5767 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5768 << (TC != nullptr);
5769 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5770 ErrorFound = true;
5771 }
5772 }
5773 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005774 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005775
5776 if (AStmt) {
5777 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5778
Reid Kleckner87a31802018-03-12 21:43:02 +00005779 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005780 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005781
5782 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005783}
5784
Alexey Bataev1d160b12015-03-13 12:27:31 +00005785namespace {
5786/// \brief Helper class for checking expression in 'omp atomic [update]'
5787/// construct.
5788class OpenMPAtomicUpdateChecker {
5789 /// \brief Error results for atomic update expressions.
5790 enum ExprAnalysisErrorCode {
5791 /// \brief A statement is not an expression statement.
5792 NotAnExpression,
5793 /// \brief Expression is not builtin binary or unary operation.
5794 NotABinaryOrUnaryExpression,
5795 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5796 NotAnUnaryIncDecExpression,
5797 /// \brief An expression is not of scalar type.
5798 NotAScalarType,
5799 /// \brief A binary operation is not an assignment operation.
5800 NotAnAssignmentOp,
5801 /// \brief RHS part of the binary operation is not a binary expression.
5802 NotABinaryExpression,
5803 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5804 /// expression.
5805 NotABinaryOperator,
5806 /// \brief RHS binary operation does not have reference to the updated LHS
5807 /// part.
5808 NotAnUpdateExpression,
5809 /// \brief No errors is found.
5810 NoError
5811 };
5812 /// \brief Reference to Sema.
5813 Sema &SemaRef;
5814 /// \brief A location for note diagnostics (when error is found).
5815 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005816 /// \brief 'x' lvalue part of the source atomic expression.
5817 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005818 /// \brief 'expr' rvalue part of the source atomic expression.
5819 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005820 /// \brief Helper expression of the form
5821 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5822 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5823 Expr *UpdateExpr;
5824 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5825 /// important for non-associative operations.
5826 bool IsXLHSInRHSPart;
5827 BinaryOperatorKind Op;
5828 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005829 /// \brief true if the source expression is a postfix unary operation, false
5830 /// if it is a prefix unary operation.
5831 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005832
5833public:
5834 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005835 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005836 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005837 /// \brief Check specified statement that it is suitable for 'atomic update'
5838 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005839 /// expression. If DiagId and NoteId == 0, then only check is performed
5840 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005841 /// \param DiagId Diagnostic which should be emitted if error is found.
5842 /// \param NoteId Diagnostic note for the main error message.
5843 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005844 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005845 /// \brief Return the 'x' lvalue part of the source atomic expression.
5846 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005847 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5848 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005849 /// \brief Return the update expression used in calculation of the updated
5850 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5851 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5852 Expr *getUpdateExpr() const { return UpdateExpr; }
5853 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5854 /// false otherwise.
5855 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5856
Alexey Bataevb78ca832015-04-01 03:33:17 +00005857 /// \brief true if the source expression is a postfix unary operation, false
5858 /// if it is a prefix unary operation.
5859 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5860
Alexey Bataev1d160b12015-03-13 12:27:31 +00005861private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005862 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5863 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005864};
5865} // namespace
5866
5867bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5868 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5869 ExprAnalysisErrorCode ErrorFound = NoError;
5870 SourceLocation ErrorLoc, NoteLoc;
5871 SourceRange ErrorRange, NoteRange;
5872 // Allowed constructs are:
5873 // x = x binop expr;
5874 // x = expr binop x;
5875 if (AtomicBinOp->getOpcode() == BO_Assign) {
5876 X = AtomicBinOp->getLHS();
5877 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5878 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5879 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5880 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5881 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005882 Op = AtomicInnerBinOp->getOpcode();
5883 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005884 auto *LHS = AtomicInnerBinOp->getLHS();
5885 auto *RHS = AtomicInnerBinOp->getRHS();
5886 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5887 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5888 /*Canonical=*/true);
5889 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5890 /*Canonical=*/true);
5891 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5892 /*Canonical=*/true);
5893 if (XId == LHSId) {
5894 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005895 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005896 } else if (XId == RHSId) {
5897 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005898 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005899 } else {
5900 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5901 ErrorRange = AtomicInnerBinOp->getSourceRange();
5902 NoteLoc = X->getExprLoc();
5903 NoteRange = X->getSourceRange();
5904 ErrorFound = NotAnUpdateExpression;
5905 }
5906 } else {
5907 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5908 ErrorRange = AtomicInnerBinOp->getSourceRange();
5909 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5910 NoteRange = SourceRange(NoteLoc, NoteLoc);
5911 ErrorFound = NotABinaryOperator;
5912 }
5913 } else {
5914 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5915 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5916 ErrorFound = NotABinaryExpression;
5917 }
5918 } else {
5919 ErrorLoc = AtomicBinOp->getExprLoc();
5920 ErrorRange = AtomicBinOp->getSourceRange();
5921 NoteLoc = AtomicBinOp->getOperatorLoc();
5922 NoteRange = SourceRange(NoteLoc, NoteLoc);
5923 ErrorFound = NotAnAssignmentOp;
5924 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005925 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005926 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5927 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5928 return true;
5929 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005930 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005931 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005932}
5933
5934bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5935 unsigned NoteId) {
5936 ExprAnalysisErrorCode ErrorFound = NoError;
5937 SourceLocation ErrorLoc, NoteLoc;
5938 SourceRange ErrorRange, NoteRange;
5939 // Allowed constructs are:
5940 // x++;
5941 // x--;
5942 // ++x;
5943 // --x;
5944 // x binop= expr;
5945 // x = x binop expr;
5946 // x = expr binop x;
5947 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5948 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5949 if (AtomicBody->getType()->isScalarType() ||
5950 AtomicBody->isInstantiationDependent()) {
5951 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5952 AtomicBody->IgnoreParenImpCasts())) {
5953 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005954 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005955 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005956 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005957 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005958 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005959 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005960 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5961 AtomicBody->IgnoreParenImpCasts())) {
5962 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005963 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005964 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005965 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5966 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005967 // Check for Unary Operation
5968 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005969 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005970 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5971 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005972 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005973 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5974 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005975 } else {
5976 ErrorFound = NotAnUnaryIncDecExpression;
5977 ErrorLoc = AtomicUnaryOp->getExprLoc();
5978 ErrorRange = AtomicUnaryOp->getSourceRange();
5979 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5980 NoteRange = SourceRange(NoteLoc, NoteLoc);
5981 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005982 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005983 ErrorFound = NotABinaryOrUnaryExpression;
5984 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5985 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5986 }
5987 } else {
5988 ErrorFound = NotAScalarType;
5989 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5990 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5991 }
5992 } else {
5993 ErrorFound = NotAnExpression;
5994 NoteLoc = ErrorLoc = S->getLocStart();
5995 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5996 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005997 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005998 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5999 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6000 return true;
6001 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006002 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006003 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006004 // Build an update expression of form 'OpaqueValueExpr(x) binop
6005 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6006 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6007 auto *OVEX = new (SemaRef.getASTContext())
6008 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6009 auto *OVEExpr = new (SemaRef.getASTContext())
6010 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6011 auto Update =
6012 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6013 IsXLHSInRHSPart ? OVEExpr : OVEX);
6014 if (Update.isInvalid())
6015 return true;
6016 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6017 Sema::AA_Casting);
6018 if (Update.isInvalid())
6019 return true;
6020 UpdateExpr = Update.get();
6021 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006022 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006023}
6024
Alexey Bataev0162e452014-07-22 10:10:35 +00006025StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6026 Stmt *AStmt,
6027 SourceLocation StartLoc,
6028 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006029 if (!AStmt)
6030 return StmtError();
6031
David Majnemer9d168222016-08-05 17:44:54 +00006032 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006033 // 1.2.2 OpenMP Language Terminology
6034 // Structured block - An executable statement with a single entry at the
6035 // top and a single exit at the bottom.
6036 // The point of exit cannot be a branch out of the structured block.
6037 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006038 OpenMPClauseKind AtomicKind = OMPC_unknown;
6039 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006040 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006041 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006042 C->getClauseKind() == OMPC_update ||
6043 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006044 if (AtomicKind != OMPC_unknown) {
6045 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6046 << SourceRange(C->getLocStart(), C->getLocEnd());
6047 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6048 << getOpenMPClauseName(AtomicKind);
6049 } else {
6050 AtomicKind = C->getClauseKind();
6051 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006052 }
6053 }
6054 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006055
Alexey Bataev459dec02014-07-24 06:46:57 +00006056 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006057 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6058 Body = EWC->getSubExpr();
6059
Alexey Bataev62cec442014-11-18 10:14:22 +00006060 Expr *X = nullptr;
6061 Expr *V = nullptr;
6062 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006063 Expr *UE = nullptr;
6064 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006065 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006066 // OpenMP [2.12.6, atomic Construct]
6067 // In the next expressions:
6068 // * x and v (as applicable) are both l-value expressions with scalar type.
6069 // * During the execution of an atomic region, multiple syntactic
6070 // occurrences of x must designate the same storage location.
6071 // * Neither of v and expr (as applicable) may access the storage location
6072 // designated by x.
6073 // * Neither of x and expr (as applicable) may access the storage location
6074 // designated by v.
6075 // * expr is an expression with scalar type.
6076 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6077 // * binop, binop=, ++, and -- are not overloaded operators.
6078 // * The expression x binop expr must be numerically equivalent to x binop
6079 // (expr). This requirement is satisfied if the operators in expr have
6080 // precedence greater than binop, or by using parentheses around expr or
6081 // subexpressions of expr.
6082 // * The expression expr binop x must be numerically equivalent to (expr)
6083 // binop x. This requirement is satisfied if the operators in expr have
6084 // precedence equal to or greater than binop, or by using parentheses around
6085 // expr or subexpressions of expr.
6086 // * For forms that allow multiple occurrences of x, the number of times
6087 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006088 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006089 enum {
6090 NotAnExpression,
6091 NotAnAssignmentOp,
6092 NotAScalarType,
6093 NotAnLValue,
6094 NoError
6095 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006096 SourceLocation ErrorLoc, NoteLoc;
6097 SourceRange ErrorRange, NoteRange;
6098 // If clause is read:
6099 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00006100 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6101 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006102 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6103 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6104 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6105 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6106 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6107 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6108 if (!X->isLValue() || !V->isLValue()) {
6109 auto NotLValueExpr = X->isLValue() ? V : X;
6110 ErrorFound = NotAnLValue;
6111 ErrorLoc = AtomicBinOp->getExprLoc();
6112 ErrorRange = AtomicBinOp->getSourceRange();
6113 NoteLoc = NotLValueExpr->getExprLoc();
6114 NoteRange = NotLValueExpr->getSourceRange();
6115 }
6116 } else if (!X->isInstantiationDependent() ||
6117 !V->isInstantiationDependent()) {
6118 auto NotScalarExpr =
6119 (X->isInstantiationDependent() || X->getType()->isScalarType())
6120 ? V
6121 : X;
6122 ErrorFound = NotAScalarType;
6123 ErrorLoc = AtomicBinOp->getExprLoc();
6124 ErrorRange = AtomicBinOp->getSourceRange();
6125 NoteLoc = NotScalarExpr->getExprLoc();
6126 NoteRange = NotScalarExpr->getSourceRange();
6127 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006128 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006129 ErrorFound = NotAnAssignmentOp;
6130 ErrorLoc = AtomicBody->getExprLoc();
6131 ErrorRange = AtomicBody->getSourceRange();
6132 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6133 : AtomicBody->getExprLoc();
6134 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6135 : AtomicBody->getSourceRange();
6136 }
6137 } else {
6138 ErrorFound = NotAnExpression;
6139 NoteLoc = ErrorLoc = Body->getLocStart();
6140 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006141 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006142 if (ErrorFound != NoError) {
6143 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6144 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006145 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6146 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006147 return StmtError();
6148 } else if (CurContext->isDependentContext())
6149 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006150 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006151 enum {
6152 NotAnExpression,
6153 NotAnAssignmentOp,
6154 NotAScalarType,
6155 NotAnLValue,
6156 NoError
6157 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006158 SourceLocation ErrorLoc, NoteLoc;
6159 SourceRange ErrorRange, NoteRange;
6160 // If clause is write:
6161 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00006162 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6163 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006164 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6165 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006166 X = AtomicBinOp->getLHS();
6167 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006168 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6169 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6170 if (!X->isLValue()) {
6171 ErrorFound = NotAnLValue;
6172 ErrorLoc = AtomicBinOp->getExprLoc();
6173 ErrorRange = AtomicBinOp->getSourceRange();
6174 NoteLoc = X->getExprLoc();
6175 NoteRange = X->getSourceRange();
6176 }
6177 } else if (!X->isInstantiationDependent() ||
6178 !E->isInstantiationDependent()) {
6179 auto NotScalarExpr =
6180 (X->isInstantiationDependent() || X->getType()->isScalarType())
6181 ? E
6182 : X;
6183 ErrorFound = NotAScalarType;
6184 ErrorLoc = AtomicBinOp->getExprLoc();
6185 ErrorRange = AtomicBinOp->getSourceRange();
6186 NoteLoc = NotScalarExpr->getExprLoc();
6187 NoteRange = NotScalarExpr->getSourceRange();
6188 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006189 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006190 ErrorFound = NotAnAssignmentOp;
6191 ErrorLoc = AtomicBody->getExprLoc();
6192 ErrorRange = AtomicBody->getSourceRange();
6193 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6194 : AtomicBody->getExprLoc();
6195 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6196 : AtomicBody->getSourceRange();
6197 }
6198 } else {
6199 ErrorFound = NotAnExpression;
6200 NoteLoc = ErrorLoc = Body->getLocStart();
6201 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006202 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006203 if (ErrorFound != NoError) {
6204 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6205 << ErrorRange;
6206 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6207 << NoteRange;
6208 return StmtError();
6209 } else if (CurContext->isDependentContext())
6210 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006211 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006212 // If clause is update:
6213 // x++;
6214 // x--;
6215 // ++x;
6216 // --x;
6217 // x binop= expr;
6218 // x = x binop expr;
6219 // x = expr binop x;
6220 OpenMPAtomicUpdateChecker Checker(*this);
6221 if (Checker.checkStatement(
6222 Body, (AtomicKind == OMPC_update)
6223 ? diag::err_omp_atomic_update_not_expression_statement
6224 : diag::err_omp_atomic_not_expression_statement,
6225 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006226 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006227 if (!CurContext->isDependentContext()) {
6228 E = Checker.getExpr();
6229 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006230 UE = Checker.getUpdateExpr();
6231 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006232 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006233 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006234 enum {
6235 NotAnAssignmentOp,
6236 NotACompoundStatement,
6237 NotTwoSubstatements,
6238 NotASpecificExpression,
6239 NoError
6240 } ErrorFound = NoError;
6241 SourceLocation ErrorLoc, NoteLoc;
6242 SourceRange ErrorRange, NoteRange;
6243 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6244 // If clause is a capture:
6245 // v = x++;
6246 // v = x--;
6247 // v = ++x;
6248 // v = --x;
6249 // v = x binop= expr;
6250 // v = x = x binop expr;
6251 // v = x = expr binop x;
6252 auto *AtomicBinOp =
6253 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6254 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6255 V = AtomicBinOp->getLHS();
6256 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6257 OpenMPAtomicUpdateChecker Checker(*this);
6258 if (Checker.checkStatement(
6259 Body, diag::err_omp_atomic_capture_not_expression_statement,
6260 diag::note_omp_atomic_update))
6261 return StmtError();
6262 E = Checker.getExpr();
6263 X = Checker.getX();
6264 UE = Checker.getUpdateExpr();
6265 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6266 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006267 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006268 ErrorLoc = AtomicBody->getExprLoc();
6269 ErrorRange = AtomicBody->getSourceRange();
6270 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6271 : AtomicBody->getExprLoc();
6272 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6273 : AtomicBody->getSourceRange();
6274 ErrorFound = NotAnAssignmentOp;
6275 }
6276 if (ErrorFound != NoError) {
6277 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6278 << ErrorRange;
6279 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6280 return StmtError();
6281 } else if (CurContext->isDependentContext()) {
6282 UE = V = E = X = nullptr;
6283 }
6284 } else {
6285 // If clause is a capture:
6286 // { v = x; x = expr; }
6287 // { v = x; x++; }
6288 // { v = x; x--; }
6289 // { v = x; ++x; }
6290 // { v = x; --x; }
6291 // { v = x; x binop= expr; }
6292 // { v = x; x = x binop expr; }
6293 // { v = x; x = expr binop x; }
6294 // { x++; v = x; }
6295 // { x--; v = x; }
6296 // { ++x; v = x; }
6297 // { --x; v = x; }
6298 // { x binop= expr; v = x; }
6299 // { x = x binop expr; v = x; }
6300 // { x = expr binop x; v = x; }
6301 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6302 // Check that this is { expr1; expr2; }
6303 if (CS->size() == 2) {
6304 auto *First = CS->body_front();
6305 auto *Second = CS->body_back();
6306 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6307 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6308 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6309 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6310 // Need to find what subexpression is 'v' and what is 'x'.
6311 OpenMPAtomicUpdateChecker Checker(*this);
6312 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6313 BinaryOperator *BinOp = nullptr;
6314 if (IsUpdateExprFound) {
6315 BinOp = dyn_cast<BinaryOperator>(First);
6316 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6317 }
6318 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6319 // { v = x; x++; }
6320 // { v = x; x--; }
6321 // { v = x; ++x; }
6322 // { v = x; --x; }
6323 // { v = x; x binop= expr; }
6324 // { v = x; x = x binop expr; }
6325 // { v = x; x = expr binop x; }
6326 // Check that the first expression has form v = x.
6327 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6328 llvm::FoldingSetNodeID XId, PossibleXId;
6329 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6330 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6331 IsUpdateExprFound = XId == PossibleXId;
6332 if (IsUpdateExprFound) {
6333 V = BinOp->getLHS();
6334 X = Checker.getX();
6335 E = Checker.getExpr();
6336 UE = Checker.getUpdateExpr();
6337 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006338 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006339 }
6340 }
6341 if (!IsUpdateExprFound) {
6342 IsUpdateExprFound = !Checker.checkStatement(First);
6343 BinOp = nullptr;
6344 if (IsUpdateExprFound) {
6345 BinOp = dyn_cast<BinaryOperator>(Second);
6346 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6347 }
6348 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6349 // { x++; v = x; }
6350 // { x--; v = x; }
6351 // { ++x; v = x; }
6352 // { --x; v = x; }
6353 // { x binop= expr; v = x; }
6354 // { x = x binop expr; v = x; }
6355 // { x = expr binop x; v = x; }
6356 // Check that the second expression has form v = x.
6357 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6358 llvm::FoldingSetNodeID XId, PossibleXId;
6359 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6360 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6361 IsUpdateExprFound = XId == PossibleXId;
6362 if (IsUpdateExprFound) {
6363 V = BinOp->getLHS();
6364 X = Checker.getX();
6365 E = Checker.getExpr();
6366 UE = Checker.getUpdateExpr();
6367 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006368 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006369 }
6370 }
6371 }
6372 if (!IsUpdateExprFound) {
6373 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006374 auto *FirstExpr = dyn_cast<Expr>(First);
6375 auto *SecondExpr = dyn_cast<Expr>(Second);
6376 if (!FirstExpr || !SecondExpr ||
6377 !(FirstExpr->isInstantiationDependent() ||
6378 SecondExpr->isInstantiationDependent())) {
6379 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6380 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006381 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006382 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6383 : First->getLocStart();
6384 NoteRange = ErrorRange = FirstBinOp
6385 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006386 : SourceRange(ErrorLoc, ErrorLoc);
6387 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006388 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6389 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6390 ErrorFound = NotAnAssignmentOp;
6391 NoteLoc = ErrorLoc = SecondBinOp
6392 ? SecondBinOp->getOperatorLoc()
6393 : Second->getLocStart();
6394 NoteRange = ErrorRange =
6395 SecondBinOp ? SecondBinOp->getSourceRange()
6396 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006397 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006398 auto *PossibleXRHSInFirst =
6399 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6400 auto *PossibleXLHSInSecond =
6401 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6402 llvm::FoldingSetNodeID X1Id, X2Id;
6403 PossibleXRHSInFirst->Profile(X1Id, Context,
6404 /*Canonical=*/true);
6405 PossibleXLHSInSecond->Profile(X2Id, Context,
6406 /*Canonical=*/true);
6407 IsUpdateExprFound = X1Id == X2Id;
6408 if (IsUpdateExprFound) {
6409 V = FirstBinOp->getLHS();
6410 X = SecondBinOp->getLHS();
6411 E = SecondBinOp->getRHS();
6412 UE = nullptr;
6413 IsXLHSInRHSPart = false;
6414 IsPostfixUpdate = true;
6415 } else {
6416 ErrorFound = NotASpecificExpression;
6417 ErrorLoc = FirstBinOp->getExprLoc();
6418 ErrorRange = FirstBinOp->getSourceRange();
6419 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6420 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6421 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006422 }
6423 }
6424 }
6425 }
6426 } else {
6427 NoteLoc = ErrorLoc = Body->getLocStart();
6428 NoteRange = ErrorRange =
6429 SourceRange(Body->getLocStart(), Body->getLocStart());
6430 ErrorFound = NotTwoSubstatements;
6431 }
6432 } else {
6433 NoteLoc = ErrorLoc = Body->getLocStart();
6434 NoteRange = ErrorRange =
6435 SourceRange(Body->getLocStart(), Body->getLocStart());
6436 ErrorFound = NotACompoundStatement;
6437 }
6438 if (ErrorFound != NoError) {
6439 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6440 << ErrorRange;
6441 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6442 return StmtError();
6443 } else if (CurContext->isDependentContext()) {
6444 UE = V = E = X = nullptr;
6445 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006446 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006447 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006448
Reid Kleckner87a31802018-03-12 21:43:02 +00006449 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00006450
Alexey Bataev62cec442014-11-18 10:14:22 +00006451 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006452 X, V, E, UE, IsXLHSInRHSPart,
6453 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006454}
6455
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006456StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6457 Stmt *AStmt,
6458 SourceLocation StartLoc,
6459 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006460 if (!AStmt)
6461 return StmtError();
6462
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006463 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6464 // 1.2.2 OpenMP Language Terminology
6465 // Structured block - An executable statement with a single entry at the
6466 // top and a single exit at the bottom.
6467 // The point of exit cannot be a branch out of the structured block.
6468 // longjmp() and throw() must not violate the entry/exit criteria.
6469 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006470 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6471 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6472 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6473 // 1.2.2 OpenMP Language Terminology
6474 // Structured block - An executable statement with a single entry at the
6475 // top and a single exit at the bottom.
6476 // The point of exit cannot be a branch out of the structured block.
6477 // longjmp() and throw() must not violate the entry/exit criteria.
6478 CS->getCapturedDecl()->setNothrow();
6479 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006480
Alexey Bataev13314bf2014-10-09 04:18:56 +00006481 // OpenMP [2.16, Nesting of Regions]
6482 // If specified, a teams construct must be contained within a target
6483 // construct. That target construct must contain no statements or directives
6484 // outside of the teams construct.
6485 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00006486 Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006487 bool OMPTeamsFound = true;
6488 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6489 auto I = CS->body_begin();
6490 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006491 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006492 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6493 OMPTeamsFound = false;
6494 break;
6495 }
6496 ++I;
6497 }
6498 assert(I != CS->body_end() && "Not found statement");
6499 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006500 } else {
6501 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6502 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006503 }
6504 if (!OMPTeamsFound) {
6505 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6506 Diag(DSAStack->getInnerTeamsRegionLoc(),
6507 diag::note_omp_nested_teams_construct_here);
6508 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6509 << isa<OMPExecutableDirective>(S);
6510 return StmtError();
6511 }
6512 }
6513
Reid Kleckner87a31802018-03-12 21:43:02 +00006514 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006515
6516 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6517}
6518
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006519StmtResult
6520Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6521 Stmt *AStmt, SourceLocation StartLoc,
6522 SourceLocation EndLoc) {
6523 if (!AStmt)
6524 return StmtError();
6525
6526 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6527 // 1.2.2 OpenMP Language Terminology
6528 // Structured block - An executable statement with a single entry at the
6529 // top and a single exit at the bottom.
6530 // The point of exit cannot be a branch out of the structured block.
6531 // longjmp() and throw() must not violate the entry/exit criteria.
6532 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006533 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6534 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6535 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6536 // 1.2.2 OpenMP Language Terminology
6537 // Structured block - An executable statement with a single entry at the
6538 // top and a single exit at the bottom.
6539 // The point of exit cannot be a branch out of the structured block.
6540 // longjmp() and throw() must not violate the entry/exit criteria.
6541 CS->getCapturedDecl()->setNothrow();
6542 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006543
Reid Kleckner87a31802018-03-12 21:43:02 +00006544 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006545
6546 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6547 AStmt);
6548}
6549
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006550StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6551 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6552 SourceLocation EndLoc,
6553 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6554 if (!AStmt)
6555 return StmtError();
6556
6557 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6558 // 1.2.2 OpenMP Language Terminology
6559 // Structured block - An executable statement with a single entry at the
6560 // top and a single exit at the bottom.
6561 // The point of exit cannot be a branch out of the structured block.
6562 // longjmp() and throw() must not violate the entry/exit criteria.
6563 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006564 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6565 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6566 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6567 // 1.2.2 OpenMP Language Terminology
6568 // Structured block - An executable statement with a single entry at the
6569 // top and a single exit at the bottom.
6570 // The point of exit cannot be a branch out of the structured block.
6571 // longjmp() and throw() must not violate the entry/exit criteria.
6572 CS->getCapturedDecl()->setNothrow();
6573 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006574
6575 OMPLoopDirective::HelperExprs B;
6576 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6577 // define the nested loops number.
6578 unsigned NestedLoopCount =
6579 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006580 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006581 VarsWithImplicitDSA, B);
6582 if (NestedLoopCount == 0)
6583 return StmtError();
6584
6585 assert((CurContext->isDependentContext() || B.builtAll()) &&
6586 "omp target parallel for loop exprs were not built");
6587
6588 if (!CurContext->isDependentContext()) {
6589 // Finalize the clauses that need pre-built expressions for CodeGen.
6590 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006591 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006592 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006593 B.NumIterations, *this, CurScope,
6594 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006595 return StmtError();
6596 }
6597 }
6598
Reid Kleckner87a31802018-03-12 21:43:02 +00006599 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006600 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6601 NestedLoopCount, Clauses, AStmt,
6602 B, DSAStack->isCancelRegion());
6603}
6604
Alexey Bataev95b64a92017-05-30 16:00:04 +00006605/// Check for existence of a map clause in the list of clauses.
6606static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6607 const OpenMPClauseKind K) {
6608 return llvm::any_of(
6609 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6610}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006611
Alexey Bataev95b64a92017-05-30 16:00:04 +00006612template <typename... Params>
6613static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6614 const Params... ClauseTypes) {
6615 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006616}
6617
Michael Wong65f367f2015-07-21 13:44:28 +00006618StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6619 Stmt *AStmt,
6620 SourceLocation StartLoc,
6621 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006622 if (!AStmt)
6623 return StmtError();
6624
6625 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6626
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006627 // OpenMP [2.10.1, Restrictions, p. 97]
6628 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006629 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6630 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6631 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006632 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006633 return StmtError();
6634 }
6635
Reid Kleckner87a31802018-03-12 21:43:02 +00006636 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00006637
6638 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6639 AStmt);
6640}
6641
Samuel Antaodf67fc42016-01-19 19:15:56 +00006642StmtResult
6643Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6644 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006645 SourceLocation EndLoc, Stmt *AStmt) {
6646 if (!AStmt)
6647 return StmtError();
6648
6649 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6650 // 1.2.2 OpenMP Language Terminology
6651 // Structured block - An executable statement with a single entry at the
6652 // top and a single exit at the bottom.
6653 // The point of exit cannot be a branch out of the structured block.
6654 // longjmp() and throw() must not violate the entry/exit criteria.
6655 CS->getCapturedDecl()->setNothrow();
6656 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6657 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6658 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6659 // 1.2.2 OpenMP Language Terminology
6660 // Structured block - An executable statement with a single entry at the
6661 // top and a single exit at the bottom.
6662 // The point of exit cannot be a branch out of the structured block.
6663 // longjmp() and throw() must not violate the entry/exit criteria.
6664 CS->getCapturedDecl()->setNothrow();
6665 }
6666
Samuel Antaodf67fc42016-01-19 19:15:56 +00006667 // OpenMP [2.10.2, Restrictions, p. 99]
6668 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006669 if (!hasClauses(Clauses, OMPC_map)) {
6670 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6671 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006672 return StmtError();
6673 }
6674
Alexey Bataev7828b252017-11-21 17:08:48 +00006675 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6676 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006677}
6678
Samuel Antao72590762016-01-19 20:04:50 +00006679StmtResult
6680Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6681 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006682 SourceLocation EndLoc, Stmt *AStmt) {
6683 if (!AStmt)
6684 return StmtError();
6685
6686 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6687 // 1.2.2 OpenMP Language Terminology
6688 // Structured block - An executable statement with a single entry at the
6689 // top and a single exit at the bottom.
6690 // The point of exit cannot be a branch out of the structured block.
6691 // longjmp() and throw() must not violate the entry/exit criteria.
6692 CS->getCapturedDecl()->setNothrow();
6693 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6694 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6695 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6696 // 1.2.2 OpenMP Language Terminology
6697 // Structured block - An executable statement with a single entry at the
6698 // top and a single exit at the bottom.
6699 // The point of exit cannot be a branch out of the structured block.
6700 // longjmp() and throw() must not violate the entry/exit criteria.
6701 CS->getCapturedDecl()->setNothrow();
6702 }
6703
Samuel Antao72590762016-01-19 20:04:50 +00006704 // OpenMP [2.10.3, Restrictions, p. 102]
6705 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006706 if (!hasClauses(Clauses, OMPC_map)) {
6707 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6708 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006709 return StmtError();
6710 }
6711
Alexey Bataev7828b252017-11-21 17:08:48 +00006712 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6713 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006714}
6715
Samuel Antao686c70c2016-05-26 17:30:50 +00006716StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6717 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006718 SourceLocation EndLoc,
6719 Stmt *AStmt) {
6720 if (!AStmt)
6721 return StmtError();
6722
6723 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6724 // 1.2.2 OpenMP Language Terminology
6725 // Structured block - An executable statement with a single entry at the
6726 // top and a single exit at the bottom.
6727 // The point of exit cannot be a branch out of the structured block.
6728 // longjmp() and throw() must not violate the entry/exit criteria.
6729 CS->getCapturedDecl()->setNothrow();
6730 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6731 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6732 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6733 // 1.2.2 OpenMP Language Terminology
6734 // Structured block - An executable statement with a single entry at the
6735 // top and a single exit at the bottom.
6736 // The point of exit cannot be a branch out of the structured block.
6737 // longjmp() and throw() must not violate the entry/exit criteria.
6738 CS->getCapturedDecl()->setNothrow();
6739 }
6740
Alexey Bataev95b64a92017-05-30 16:00:04 +00006741 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006742 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6743 return StmtError();
6744 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006745 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6746 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006747}
6748
Alexey Bataev13314bf2014-10-09 04:18:56 +00006749StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6750 Stmt *AStmt, SourceLocation StartLoc,
6751 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006752 if (!AStmt)
6753 return StmtError();
6754
Alexey Bataev13314bf2014-10-09 04:18:56 +00006755 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6756 // 1.2.2 OpenMP Language Terminology
6757 // Structured block - An executable statement with a single entry at the
6758 // top and a single exit at the bottom.
6759 // The point of exit cannot be a branch out of the structured block.
6760 // longjmp() and throw() must not violate the entry/exit criteria.
6761 CS->getCapturedDecl()->setNothrow();
6762
Reid Kleckner87a31802018-03-12 21:43:02 +00006763 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00006764
Alexey Bataevceabd412017-11-30 18:01:54 +00006765 DSAStack->setParentTeamsRegionLoc(StartLoc);
6766
Alexey Bataev13314bf2014-10-09 04:18:56 +00006767 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6768}
6769
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006770StmtResult
6771Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6772 SourceLocation EndLoc,
6773 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006774 if (DSAStack->isParentNowaitRegion()) {
6775 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6776 return StmtError();
6777 }
6778 if (DSAStack->isParentOrderedRegion()) {
6779 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6780 return StmtError();
6781 }
6782 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6783 CancelRegion);
6784}
6785
Alexey Bataev87933c72015-09-18 08:07:34 +00006786StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6787 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006788 SourceLocation EndLoc,
6789 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006790 if (DSAStack->isParentNowaitRegion()) {
6791 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6792 return StmtError();
6793 }
6794 if (DSAStack->isParentOrderedRegion()) {
6795 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6796 return StmtError();
6797 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006798 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006799 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6800 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006801}
6802
Alexey Bataev382967a2015-12-08 12:06:20 +00006803static bool checkGrainsizeNumTasksClauses(Sema &S,
6804 ArrayRef<OMPClause *> Clauses) {
6805 OMPClause *PrevClause = nullptr;
6806 bool ErrorFound = false;
6807 for (auto *C : Clauses) {
6808 if (C->getClauseKind() == OMPC_grainsize ||
6809 C->getClauseKind() == OMPC_num_tasks) {
6810 if (!PrevClause)
6811 PrevClause = C;
6812 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6813 S.Diag(C->getLocStart(),
6814 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6815 << getOpenMPClauseName(C->getClauseKind())
6816 << getOpenMPClauseName(PrevClause->getClauseKind());
6817 S.Diag(PrevClause->getLocStart(),
6818 diag::note_omp_previous_grainsize_num_tasks)
6819 << getOpenMPClauseName(PrevClause->getClauseKind());
6820 ErrorFound = true;
6821 }
6822 }
6823 }
6824 return ErrorFound;
6825}
6826
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006827static bool checkReductionClauseWithNogroup(Sema &S,
6828 ArrayRef<OMPClause *> Clauses) {
6829 OMPClause *ReductionClause = nullptr;
6830 OMPClause *NogroupClause = nullptr;
6831 for (auto *C : Clauses) {
6832 if (C->getClauseKind() == OMPC_reduction) {
6833 ReductionClause = C;
6834 if (NogroupClause)
6835 break;
6836 continue;
6837 }
6838 if (C->getClauseKind() == OMPC_nogroup) {
6839 NogroupClause = C;
6840 if (ReductionClause)
6841 break;
6842 continue;
6843 }
6844 }
6845 if (ReductionClause && NogroupClause) {
6846 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6847 << SourceRange(NogroupClause->getLocStart(),
6848 NogroupClause->getLocEnd());
6849 return true;
6850 }
6851 return false;
6852}
6853
Alexey Bataev49f6e782015-12-01 04:18:41 +00006854StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6855 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6856 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006857 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006858 if (!AStmt)
6859 return StmtError();
6860
6861 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6862 OMPLoopDirective::HelperExprs B;
6863 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6864 // define the nested loops number.
6865 unsigned NestedLoopCount =
6866 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006867 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006868 VarsWithImplicitDSA, B);
6869 if (NestedLoopCount == 0)
6870 return StmtError();
6871
6872 assert((CurContext->isDependentContext() || B.builtAll()) &&
6873 "omp for loop exprs were not built");
6874
Alexey Bataev382967a2015-12-08 12:06:20 +00006875 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6876 // The grainsize clause and num_tasks clause are mutually exclusive and may
6877 // not appear on the same taskloop directive.
6878 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6879 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006880 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6881 // If a reduction clause is present on the taskloop directive, the nogroup
6882 // clause must not be specified.
6883 if (checkReductionClauseWithNogroup(*this, Clauses))
6884 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006885
Reid Kleckner87a31802018-03-12 21:43:02 +00006886 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00006887 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6888 NestedLoopCount, Clauses, AStmt, B);
6889}
6890
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006891StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6892 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6893 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006894 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006895 if (!AStmt)
6896 return StmtError();
6897
6898 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6899 OMPLoopDirective::HelperExprs B;
6900 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6901 // define the nested loops number.
6902 unsigned NestedLoopCount =
6903 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6904 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6905 VarsWithImplicitDSA, B);
6906 if (NestedLoopCount == 0)
6907 return StmtError();
6908
6909 assert((CurContext->isDependentContext() || B.builtAll()) &&
6910 "omp for loop exprs were not built");
6911
Alexey Bataev5a3af132016-03-29 08:58:54 +00006912 if (!CurContext->isDependentContext()) {
6913 // Finalize the clauses that need pre-built expressions for CodeGen.
6914 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006915 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006916 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006917 B.NumIterations, *this, CurScope,
6918 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006919 return StmtError();
6920 }
6921 }
6922
Alexey Bataev382967a2015-12-08 12:06:20 +00006923 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6924 // The grainsize clause and num_tasks clause are mutually exclusive and may
6925 // not appear on the same taskloop directive.
6926 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6927 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006928 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6929 // If a reduction clause is present on the taskloop directive, the nogroup
6930 // clause must not be specified.
6931 if (checkReductionClauseWithNogroup(*this, Clauses))
6932 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006933 if (checkSimdlenSafelenSpecified(*this, Clauses))
6934 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006935
Reid Kleckner87a31802018-03-12 21:43:02 +00006936 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006937 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6938 NestedLoopCount, Clauses, AStmt, B);
6939}
6940
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006941StmtResult Sema::ActOnOpenMPDistributeDirective(
6942 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6943 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006944 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006945 if (!AStmt)
6946 return StmtError();
6947
6948 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6949 OMPLoopDirective::HelperExprs B;
6950 // In presence of clause 'collapse' with number of loops, it will
6951 // define the nested loops number.
6952 unsigned NestedLoopCount =
6953 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6954 nullptr /*ordered not a clause on distribute*/, AStmt,
6955 *this, *DSAStack, VarsWithImplicitDSA, B);
6956 if (NestedLoopCount == 0)
6957 return StmtError();
6958
6959 assert((CurContext->isDependentContext() || B.builtAll()) &&
6960 "omp for loop exprs were not built");
6961
Reid Kleckner87a31802018-03-12 21:43:02 +00006962 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006963 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6964 NestedLoopCount, Clauses, AStmt, B);
6965}
6966
Carlo Bertolli9925f152016-06-27 14:55:37 +00006967StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6968 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6969 SourceLocation EndLoc,
6970 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6971 if (!AStmt)
6972 return StmtError();
6973
6974 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6975 // 1.2.2 OpenMP Language Terminology
6976 // Structured block - An executable statement with a single entry at the
6977 // top and a single exit at the bottom.
6978 // The point of exit cannot be a branch out of the structured block.
6979 // longjmp() and throw() must not violate the entry/exit criteria.
6980 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006981 for (int ThisCaptureLevel =
6982 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6983 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6984 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6985 // 1.2.2 OpenMP Language Terminology
6986 // Structured block - An executable statement with a single entry at the
6987 // top and a single exit at the bottom.
6988 // The point of exit cannot be a branch out of the structured block.
6989 // longjmp() and throw() must not violate the entry/exit criteria.
6990 CS->getCapturedDecl()->setNothrow();
6991 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006992
6993 OMPLoopDirective::HelperExprs B;
6994 // In presence of clause 'collapse' with number of loops, it will
6995 // define the nested loops number.
6996 unsigned NestedLoopCount = CheckOpenMPLoop(
6997 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006998 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006999 VarsWithImplicitDSA, B);
7000 if (NestedLoopCount == 0)
7001 return StmtError();
7002
7003 assert((CurContext->isDependentContext() || B.builtAll()) &&
7004 "omp for loop exprs were not built");
7005
Reid Kleckner87a31802018-03-12 21:43:02 +00007006 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007007 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007008 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7009 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007010}
7011
Kelvin Li4a39add2016-07-05 05:00:15 +00007012StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7014 SourceLocation EndLoc,
7015 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7016 if (!AStmt)
7017 return StmtError();
7018
7019 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7020 // 1.2.2 OpenMP Language Terminology
7021 // Structured block - An executable statement with a single entry at the
7022 // top and a single exit at the bottom.
7023 // The point of exit cannot be a branch out of the structured block.
7024 // longjmp() and throw() must not violate the entry/exit criteria.
7025 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007026 for (int ThisCaptureLevel =
7027 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7028 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7029 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7030 // 1.2.2 OpenMP Language Terminology
7031 // Structured block - An executable statement with a single entry at the
7032 // top and a single exit at the bottom.
7033 // The point of exit cannot be a branch out of the structured block.
7034 // longjmp() and throw() must not violate the entry/exit criteria.
7035 CS->getCapturedDecl()->setNothrow();
7036 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007037
7038 OMPLoopDirective::HelperExprs B;
7039 // In presence of clause 'collapse' with number of loops, it will
7040 // define the nested loops number.
7041 unsigned NestedLoopCount = CheckOpenMPLoop(
7042 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007043 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007044 VarsWithImplicitDSA, B);
7045 if (NestedLoopCount == 0)
7046 return StmtError();
7047
7048 assert((CurContext->isDependentContext() || B.builtAll()) &&
7049 "omp for loop exprs were not built");
7050
Alexey Bataev438388c2017-11-22 18:34:02 +00007051 if (!CurContext->isDependentContext()) {
7052 // Finalize the clauses that need pre-built expressions for CodeGen.
7053 for (auto C : Clauses) {
7054 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7055 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7056 B.NumIterations, *this, CurScope,
7057 DSAStack))
7058 return StmtError();
7059 }
7060 }
7061
Kelvin Lic5609492016-07-15 04:39:07 +00007062 if (checkSimdlenSafelenSpecified(*this, Clauses))
7063 return StmtError();
7064
Reid Kleckner87a31802018-03-12 21:43:02 +00007065 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007066 return OMPDistributeParallelForSimdDirective::Create(
7067 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7068}
7069
Kelvin Li787f3fc2016-07-06 04:45:38 +00007070StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7071 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7072 SourceLocation EndLoc,
7073 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7074 if (!AStmt)
7075 return StmtError();
7076
7077 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7078 // 1.2.2 OpenMP Language Terminology
7079 // Structured block - An executable statement with a single entry at the
7080 // top and a single exit at the bottom.
7081 // The point of exit cannot be a branch out of the structured block.
7082 // longjmp() and throw() must not violate the entry/exit criteria.
7083 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007084 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7085 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7086 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7087 // 1.2.2 OpenMP Language Terminology
7088 // Structured block - An executable statement with a single entry at the
7089 // top and a single exit at the bottom.
7090 // The point of exit cannot be a branch out of the structured block.
7091 // longjmp() and throw() must not violate the entry/exit criteria.
7092 CS->getCapturedDecl()->setNothrow();
7093 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007094
7095 OMPLoopDirective::HelperExprs B;
7096 // In presence of clause 'collapse' with number of loops, it will
7097 // define the nested loops number.
7098 unsigned NestedLoopCount =
7099 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007100 nullptr /*ordered not a clause on distribute*/, CS, *this,
7101 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007102 if (NestedLoopCount == 0)
7103 return StmtError();
7104
7105 assert((CurContext->isDependentContext() || B.builtAll()) &&
7106 "omp for loop exprs were not built");
7107
Alexey Bataev438388c2017-11-22 18:34:02 +00007108 if (!CurContext->isDependentContext()) {
7109 // Finalize the clauses that need pre-built expressions for CodeGen.
7110 for (auto C : Clauses) {
7111 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7112 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7113 B.NumIterations, *this, CurScope,
7114 DSAStack))
7115 return StmtError();
7116 }
7117 }
7118
Kelvin Lic5609492016-07-15 04:39:07 +00007119 if (checkSimdlenSafelenSpecified(*this, Clauses))
7120 return StmtError();
7121
Reid Kleckner87a31802018-03-12 21:43:02 +00007122 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007123 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7124 NestedLoopCount, Clauses, AStmt, B);
7125}
7126
Kelvin Lia579b912016-07-14 02:54:56 +00007127StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7128 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7129 SourceLocation EndLoc,
7130 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7131 if (!AStmt)
7132 return StmtError();
7133
7134 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7135 // 1.2.2 OpenMP Language Terminology
7136 // Structured block - An executable statement with a single entry at the
7137 // top and a single exit at the bottom.
7138 // The point of exit cannot be a branch out of the structured block.
7139 // longjmp() and throw() must not violate the entry/exit criteria.
7140 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007141 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7142 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7143 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7144 // 1.2.2 OpenMP Language Terminology
7145 // Structured block - An executable statement with a single entry at the
7146 // top and a single exit at the bottom.
7147 // The point of exit cannot be a branch out of the structured block.
7148 // longjmp() and throw() must not violate the entry/exit criteria.
7149 CS->getCapturedDecl()->setNothrow();
7150 }
Kelvin Lia579b912016-07-14 02:54:56 +00007151
7152 OMPLoopDirective::HelperExprs B;
7153 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7154 // define the nested loops number.
7155 unsigned NestedLoopCount = CheckOpenMPLoop(
7156 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007157 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007158 VarsWithImplicitDSA, B);
7159 if (NestedLoopCount == 0)
7160 return StmtError();
7161
7162 assert((CurContext->isDependentContext() || B.builtAll()) &&
7163 "omp target parallel for simd loop exprs were not built");
7164
7165 if (!CurContext->isDependentContext()) {
7166 // Finalize the clauses that need pre-built expressions for CodeGen.
7167 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007168 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007169 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7170 B.NumIterations, *this, CurScope,
7171 DSAStack))
7172 return StmtError();
7173 }
7174 }
Kelvin Lic5609492016-07-15 04:39:07 +00007175 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007176 return StmtError();
7177
Reid Kleckner87a31802018-03-12 21:43:02 +00007178 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007179 return OMPTargetParallelForSimdDirective::Create(
7180 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7181}
7182
Kelvin Li986330c2016-07-20 22:57:10 +00007183StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7184 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7185 SourceLocation EndLoc,
7186 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7187 if (!AStmt)
7188 return StmtError();
7189
7190 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7191 // 1.2.2 OpenMP Language Terminology
7192 // Structured block - An executable statement with a single entry at the
7193 // top and a single exit at the bottom.
7194 // The point of exit cannot be a branch out of the structured block.
7195 // longjmp() and throw() must not violate the entry/exit criteria.
7196 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007197 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7198 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7199 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7200 // 1.2.2 OpenMP Language Terminology
7201 // Structured block - An executable statement with a single entry at the
7202 // top and a single exit at the bottom.
7203 // The point of exit cannot be a branch out of the structured block.
7204 // longjmp() and throw() must not violate the entry/exit criteria.
7205 CS->getCapturedDecl()->setNothrow();
7206 }
7207
Kelvin Li986330c2016-07-20 22:57:10 +00007208 OMPLoopDirective::HelperExprs B;
7209 // In presence of clause 'collapse' with number of loops, it will define the
7210 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007211 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007212 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007213 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007214 VarsWithImplicitDSA, B);
7215 if (NestedLoopCount == 0)
7216 return StmtError();
7217
7218 assert((CurContext->isDependentContext() || B.builtAll()) &&
7219 "omp target simd loop exprs were not built");
7220
7221 if (!CurContext->isDependentContext()) {
7222 // Finalize the clauses that need pre-built expressions for CodeGen.
7223 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007224 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007225 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7226 B.NumIterations, *this, CurScope,
7227 DSAStack))
7228 return StmtError();
7229 }
7230 }
7231
7232 if (checkSimdlenSafelenSpecified(*this, Clauses))
7233 return StmtError();
7234
Reid Kleckner87a31802018-03-12 21:43:02 +00007235 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007236 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7237 NestedLoopCount, Clauses, AStmt, B);
7238}
7239
Kelvin Li02532872016-08-05 14:37:37 +00007240StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7241 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7242 SourceLocation EndLoc,
7243 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7244 if (!AStmt)
7245 return StmtError();
7246
7247 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7248 // 1.2.2 OpenMP Language Terminology
7249 // Structured block - An executable statement with a single entry at the
7250 // top and a single exit at the bottom.
7251 // The point of exit cannot be a branch out of the structured block.
7252 // longjmp() and throw() must not violate the entry/exit criteria.
7253 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007254 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7255 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7256 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7257 // 1.2.2 OpenMP Language Terminology
7258 // Structured block - An executable statement with a single entry at the
7259 // top and a single exit at the bottom.
7260 // The point of exit cannot be a branch out of the structured block.
7261 // longjmp() and throw() must not violate the entry/exit criteria.
7262 CS->getCapturedDecl()->setNothrow();
7263 }
Kelvin Li02532872016-08-05 14:37:37 +00007264
7265 OMPLoopDirective::HelperExprs B;
7266 // In presence of clause 'collapse' with number of loops, it will
7267 // define the nested loops number.
7268 unsigned NestedLoopCount =
7269 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007270 nullptr /*ordered not a clause on distribute*/, CS, *this,
7271 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007272 if (NestedLoopCount == 0)
7273 return StmtError();
7274
7275 assert((CurContext->isDependentContext() || B.builtAll()) &&
7276 "omp teams distribute loop exprs were not built");
7277
Reid Kleckner87a31802018-03-12 21:43:02 +00007278 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007279
7280 DSAStack->setParentTeamsRegionLoc(StartLoc);
7281
David Majnemer9d168222016-08-05 17:44:54 +00007282 return OMPTeamsDistributeDirective::Create(
7283 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007284}
7285
Kelvin Li4e325f72016-10-25 12:50:55 +00007286StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7287 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7288 SourceLocation EndLoc,
7289 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7290 if (!AStmt)
7291 return StmtError();
7292
7293 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7294 // 1.2.2 OpenMP Language Terminology
7295 // Structured block - An executable statement with a single entry at the
7296 // top and a single exit at the bottom.
7297 // The point of exit cannot be a branch out of the structured block.
7298 // longjmp() and throw() must not violate the entry/exit criteria.
7299 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007300 for (int ThisCaptureLevel =
7301 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7302 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7303 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7304 // 1.2.2 OpenMP Language Terminology
7305 // Structured block - An executable statement with a single entry at the
7306 // top and a single exit at the bottom.
7307 // The point of exit cannot be a branch out of the structured block.
7308 // longjmp() and throw() must not violate the entry/exit criteria.
7309 CS->getCapturedDecl()->setNothrow();
7310 }
7311
Kelvin Li4e325f72016-10-25 12:50:55 +00007312
7313 OMPLoopDirective::HelperExprs B;
7314 // In presence of clause 'collapse' with number of loops, it will
7315 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007316 unsigned NestedLoopCount = CheckOpenMPLoop(
7317 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007318 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007319 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007320
7321 if (NestedLoopCount == 0)
7322 return StmtError();
7323
7324 assert((CurContext->isDependentContext() || B.builtAll()) &&
7325 "omp teams distribute simd loop exprs were not built");
7326
7327 if (!CurContext->isDependentContext()) {
7328 // Finalize the clauses that need pre-built expressions for CodeGen.
7329 for (auto C : Clauses) {
7330 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7331 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7332 B.NumIterations, *this, CurScope,
7333 DSAStack))
7334 return StmtError();
7335 }
7336 }
7337
7338 if (checkSimdlenSafelenSpecified(*this, Clauses))
7339 return StmtError();
7340
Reid Kleckner87a31802018-03-12 21:43:02 +00007341 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007342
7343 DSAStack->setParentTeamsRegionLoc(StartLoc);
7344
Kelvin Li4e325f72016-10-25 12:50:55 +00007345 return OMPTeamsDistributeSimdDirective::Create(
7346 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7347}
7348
Kelvin Li579e41c2016-11-30 23:51:03 +00007349StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7350 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7351 SourceLocation EndLoc,
7352 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7353 if (!AStmt)
7354 return StmtError();
7355
7356 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7357 // 1.2.2 OpenMP Language Terminology
7358 // Structured block - An executable statement with a single entry at the
7359 // top and a single exit at the bottom.
7360 // The point of exit cannot be a branch out of the structured block.
7361 // longjmp() and throw() must not violate the entry/exit criteria.
7362 CS->getCapturedDecl()->setNothrow();
7363
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007364 for (int ThisCaptureLevel =
7365 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7366 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7367 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7368 // 1.2.2 OpenMP Language Terminology
7369 // Structured block - An executable statement with a single entry at the
7370 // top and a single exit at the bottom.
7371 // The point of exit cannot be a branch out of the structured block.
7372 // longjmp() and throw() must not violate the entry/exit criteria.
7373 CS->getCapturedDecl()->setNothrow();
7374 }
7375
Kelvin Li579e41c2016-11-30 23:51:03 +00007376 OMPLoopDirective::HelperExprs B;
7377 // In presence of clause 'collapse' with number of loops, it will
7378 // define the nested loops number.
7379 auto NestedLoopCount = CheckOpenMPLoop(
7380 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007381 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007382 VarsWithImplicitDSA, B);
7383
7384 if (NestedLoopCount == 0)
7385 return StmtError();
7386
7387 assert((CurContext->isDependentContext() || B.builtAll()) &&
7388 "omp for loop exprs were not built");
7389
7390 if (!CurContext->isDependentContext()) {
7391 // Finalize the clauses that need pre-built expressions for CodeGen.
7392 for (auto C : Clauses) {
7393 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7394 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7395 B.NumIterations, *this, CurScope,
7396 DSAStack))
7397 return StmtError();
7398 }
7399 }
7400
7401 if (checkSimdlenSafelenSpecified(*this, Clauses))
7402 return StmtError();
7403
Reid Kleckner87a31802018-03-12 21:43:02 +00007404 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007405
7406 DSAStack->setParentTeamsRegionLoc(StartLoc);
7407
Kelvin Li579e41c2016-11-30 23:51:03 +00007408 return OMPTeamsDistributeParallelForSimdDirective::Create(
7409 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7410}
7411
Kelvin Li7ade93f2016-12-09 03:24:30 +00007412StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7413 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7414 SourceLocation EndLoc,
7415 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7416 if (!AStmt)
7417 return StmtError();
7418
7419 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7420 // 1.2.2 OpenMP Language Terminology
7421 // Structured block - An executable statement with a single entry at the
7422 // top and a single exit at the bottom.
7423 // The point of exit cannot be a branch out of the structured block.
7424 // longjmp() and throw() must not violate the entry/exit criteria.
7425 CS->getCapturedDecl()->setNothrow();
7426
Carlo Bertolli62fae152017-11-20 20:46:39 +00007427 for (int ThisCaptureLevel =
7428 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7429 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7430 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7431 // 1.2.2 OpenMP Language Terminology
7432 // Structured block - An executable statement with a single entry at the
7433 // top and a single exit at the bottom.
7434 // The point of exit cannot be a branch out of the structured block.
7435 // longjmp() and throw() must not violate the entry/exit criteria.
7436 CS->getCapturedDecl()->setNothrow();
7437 }
7438
Kelvin Li7ade93f2016-12-09 03:24:30 +00007439 OMPLoopDirective::HelperExprs B;
7440 // In presence of clause 'collapse' with number of loops, it will
7441 // define the nested loops number.
7442 unsigned NestedLoopCount = CheckOpenMPLoop(
7443 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007444 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007445 VarsWithImplicitDSA, B);
7446
7447 if (NestedLoopCount == 0)
7448 return StmtError();
7449
7450 assert((CurContext->isDependentContext() || B.builtAll()) &&
7451 "omp for loop exprs were not built");
7452
Reid Kleckner87a31802018-03-12 21:43:02 +00007453 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007454
7455 DSAStack->setParentTeamsRegionLoc(StartLoc);
7456
Kelvin Li7ade93f2016-12-09 03:24:30 +00007457 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007458 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7459 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007460}
7461
Kelvin Libf594a52016-12-17 05:48:59 +00007462StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7463 Stmt *AStmt,
7464 SourceLocation StartLoc,
7465 SourceLocation EndLoc) {
7466 if (!AStmt)
7467 return StmtError();
7468
7469 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7470 // 1.2.2 OpenMP Language Terminology
7471 // Structured block - An executable statement with a single entry at the
7472 // top and a single exit at the bottom.
7473 // The point of exit cannot be a branch out of the structured block.
7474 // longjmp() and throw() must not violate the entry/exit criteria.
7475 CS->getCapturedDecl()->setNothrow();
7476
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007477 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7478 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7479 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7480 // 1.2.2 OpenMP Language Terminology
7481 // Structured block - An executable statement with a single entry at the
7482 // top and a single exit at the bottom.
7483 // The point of exit cannot be a branch out of the structured block.
7484 // longjmp() and throw() must not violate the entry/exit criteria.
7485 CS->getCapturedDecl()->setNothrow();
7486 }
Reid Kleckner87a31802018-03-12 21:43:02 +00007487 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00007488
7489 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7490 AStmt);
7491}
7492
Kelvin Li83c451e2016-12-25 04:52:54 +00007493StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7494 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7495 SourceLocation EndLoc,
7496 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7497 if (!AStmt)
7498 return StmtError();
7499
7500 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7501 // 1.2.2 OpenMP Language Terminology
7502 // Structured block - An executable statement with a single entry at the
7503 // top and a single exit at the bottom.
7504 // The point of exit cannot be a branch out of the structured block.
7505 // longjmp() and throw() must not violate the entry/exit criteria.
7506 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007507 for (int ThisCaptureLevel =
7508 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7509 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7510 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7511 // 1.2.2 OpenMP Language Terminology
7512 // Structured block - An executable statement with a single entry at the
7513 // top and a single exit at the bottom.
7514 // The point of exit cannot be a branch out of the structured block.
7515 // longjmp() and throw() must not violate the entry/exit criteria.
7516 CS->getCapturedDecl()->setNothrow();
7517 }
Kelvin Li83c451e2016-12-25 04:52:54 +00007518
7519 OMPLoopDirective::HelperExprs B;
7520 // In presence of clause 'collapse' with number of loops, it will
7521 // define the nested loops number.
7522 auto NestedLoopCount = CheckOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007523 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7524 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00007525 VarsWithImplicitDSA, B);
7526 if (NestedLoopCount == 0)
7527 return StmtError();
7528
7529 assert((CurContext->isDependentContext() || B.builtAll()) &&
7530 "omp target teams distribute loop exprs were not built");
7531
Reid Kleckner87a31802018-03-12 21:43:02 +00007532 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00007533 return OMPTargetTeamsDistributeDirective::Create(
7534 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7535}
7536
Kelvin Li80e8f562016-12-29 22:16:30 +00007537StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7538 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7539 SourceLocation EndLoc,
7540 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7541 if (!AStmt)
7542 return StmtError();
7543
7544 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7545 // 1.2.2 OpenMP Language Terminology
7546 // Structured block - An executable statement with a single entry at the
7547 // top and a single exit at the bottom.
7548 // The point of exit cannot be a branch out of the structured block.
7549 // longjmp() and throw() must not violate the entry/exit criteria.
7550 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00007551 for (int ThisCaptureLevel =
7552 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7553 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7554 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7555 // 1.2.2 OpenMP Language Terminology
7556 // Structured block - An executable statement with a single entry at the
7557 // top and a single exit at the bottom.
7558 // The point of exit cannot be a branch out of the structured block.
7559 // longjmp() and throw() must not violate the entry/exit criteria.
7560 CS->getCapturedDecl()->setNothrow();
7561 }
7562
Kelvin Li80e8f562016-12-29 22:16:30 +00007563 OMPLoopDirective::HelperExprs B;
7564 // In presence of clause 'collapse' with number of loops, it will
7565 // define the nested loops number.
7566 auto NestedLoopCount = CheckOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00007567 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7568 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00007569 VarsWithImplicitDSA, B);
7570 if (NestedLoopCount == 0)
7571 return StmtError();
7572
7573 assert((CurContext->isDependentContext() || B.builtAll()) &&
7574 "omp target teams distribute parallel for loop exprs were not built");
7575
Alexey Bataev647dd842018-01-15 20:59:40 +00007576 if (!CurContext->isDependentContext()) {
7577 // Finalize the clauses that need pre-built expressions for CodeGen.
7578 for (auto C : Clauses) {
7579 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7580 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7581 B.NumIterations, *this, CurScope,
7582 DSAStack))
7583 return StmtError();
7584 }
7585 }
7586
Reid Kleckner87a31802018-03-12 21:43:02 +00007587 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00007588 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007589 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7590 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007591}
7592
Kelvin Li1851df52017-01-03 05:23:48 +00007593StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7594 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7595 SourceLocation EndLoc,
7596 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7597 if (!AStmt)
7598 return StmtError();
7599
7600 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7601 // 1.2.2 OpenMP Language Terminology
7602 // Structured block - An executable statement with a single entry at the
7603 // top and a single exit at the bottom.
7604 // The point of exit cannot be a branch out of the structured block.
7605 // longjmp() and throw() must not violate the entry/exit criteria.
7606 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00007607 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7608 OMPD_target_teams_distribute_parallel_for_simd);
7609 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7610 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7611 // 1.2.2 OpenMP Language Terminology
7612 // Structured block - An executable statement with a single entry at the
7613 // top and a single exit at the bottom.
7614 // The point of exit cannot be a branch out of the structured block.
7615 // longjmp() and throw() must not violate the entry/exit criteria.
7616 CS->getCapturedDecl()->setNothrow();
7617 }
Kelvin Li1851df52017-01-03 05:23:48 +00007618
7619 OMPLoopDirective::HelperExprs B;
7620 // In presence of clause 'collapse' with number of loops, it will
7621 // define the nested loops number.
Alexey Bataev647dd842018-01-15 20:59:40 +00007622 auto NestedLoopCount =
7623 CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7624 getCollapseNumberExpr(Clauses),
7625 nullptr /*ordered not a clause on distribute*/, CS, *this,
7626 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00007627 if (NestedLoopCount == 0)
7628 return StmtError();
7629
7630 assert((CurContext->isDependentContext() || B.builtAll()) &&
7631 "omp target teams distribute parallel for simd loop exprs were not "
7632 "built");
7633
7634 if (!CurContext->isDependentContext()) {
7635 // Finalize the clauses that need pre-built expressions for CodeGen.
7636 for (auto C : Clauses) {
7637 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7638 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7639 B.NumIterations, *this, CurScope,
7640 DSAStack))
7641 return StmtError();
7642 }
7643 }
7644
Alexey Bataev438388c2017-11-22 18:34:02 +00007645 if (checkSimdlenSafelenSpecified(*this, Clauses))
7646 return StmtError();
7647
Reid Kleckner87a31802018-03-12 21:43:02 +00007648 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00007649 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7650 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7651}
7652
Kelvin Lida681182017-01-10 18:08:18 +00007653StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7654 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7655 SourceLocation EndLoc,
7656 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7657 if (!AStmt)
7658 return StmtError();
7659
7660 auto *CS = cast<CapturedStmt>(AStmt);
7661 // 1.2.2 OpenMP Language Terminology
7662 // Structured block - An executable statement with a single entry at the
7663 // top and a single exit at the bottom.
7664 // The point of exit cannot be a branch out of the structured block.
7665 // longjmp() and throw() must not violate the entry/exit criteria.
7666 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007667 for (int ThisCaptureLevel =
7668 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7669 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7670 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7671 // 1.2.2 OpenMP Language Terminology
7672 // Structured block - An executable statement with a single entry at the
7673 // top and a single exit at the bottom.
7674 // The point of exit cannot be a branch out of the structured block.
7675 // longjmp() and throw() must not violate the entry/exit criteria.
7676 CS->getCapturedDecl()->setNothrow();
7677 }
Kelvin Lida681182017-01-10 18:08:18 +00007678
7679 OMPLoopDirective::HelperExprs B;
7680 // In presence of clause 'collapse' with number of loops, it will
7681 // define the nested loops number.
7682 auto NestedLoopCount = CheckOpenMPLoop(
7683 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007684 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00007685 VarsWithImplicitDSA, B);
7686 if (NestedLoopCount == 0)
7687 return StmtError();
7688
7689 assert((CurContext->isDependentContext() || B.builtAll()) &&
7690 "omp target teams distribute simd loop exprs were not built");
7691
Alexey Bataev438388c2017-11-22 18:34:02 +00007692 if (!CurContext->isDependentContext()) {
7693 // Finalize the clauses that need pre-built expressions for CodeGen.
7694 for (auto C : Clauses) {
7695 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7696 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7697 B.NumIterations, *this, CurScope,
7698 DSAStack))
7699 return StmtError();
7700 }
7701 }
7702
7703 if (checkSimdlenSafelenSpecified(*this, Clauses))
7704 return StmtError();
7705
Reid Kleckner87a31802018-03-12 21:43:02 +00007706 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00007707 return OMPTargetTeamsDistributeSimdDirective::Create(
7708 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7709}
7710
Alexey Bataeved09d242014-05-28 05:53:51 +00007711OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007712 SourceLocation StartLoc,
7713 SourceLocation LParenLoc,
7714 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007715 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007716 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007717 case OMPC_final:
7718 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7719 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007720 case OMPC_num_threads:
7721 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7722 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007723 case OMPC_safelen:
7724 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7725 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007726 case OMPC_simdlen:
7727 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7728 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007729 case OMPC_collapse:
7730 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7731 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007732 case OMPC_ordered:
7733 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7734 break;
Michael Wonge710d542015-08-07 16:16:36 +00007735 case OMPC_device:
7736 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7737 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007738 case OMPC_num_teams:
7739 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7740 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007741 case OMPC_thread_limit:
7742 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7743 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007744 case OMPC_priority:
7745 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7746 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007747 case OMPC_grainsize:
7748 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7749 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007750 case OMPC_num_tasks:
7751 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7752 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007753 case OMPC_hint:
7754 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7755 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007756 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007757 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007758 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007759 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007760 case OMPC_private:
7761 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007762 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007763 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007764 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007765 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007766 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007767 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007768 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007769 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007770 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007771 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007772 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007773 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007774 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007775 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007776 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007777 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007778 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007779 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007780 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007781 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007782 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007783 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007784 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007785 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007786 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007787 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007788 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007789 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007790 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007791 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007792 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007793 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007794 llvm_unreachable("Clause is not allowed.");
7795 }
7796 return Res;
7797}
7798
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007799// An OpenMP directive such as 'target parallel' has two captured regions:
7800// for the 'target' and 'parallel' respectively. This function returns
7801// the region in which to capture expressions associated with a clause.
7802// A return value of OMPD_unknown signifies that the expression should not
7803// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007804static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7805 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7806 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007807 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007808 switch (CKind) {
7809 case OMPC_if:
7810 switch (DKind) {
7811 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007812 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007813 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007814 // If this clause applies to the nested 'parallel' region, capture within
7815 // the 'target' region, otherwise do not capture.
7816 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7817 CaptureRegion = OMPD_target;
7818 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007819 case OMPD_target_teams_distribute_parallel_for:
7820 case OMPD_target_teams_distribute_parallel_for_simd:
7821 // If this clause applies to the nested 'parallel' region, capture within
7822 // the 'teams' region, otherwise do not capture.
7823 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7824 CaptureRegion = OMPD_teams;
7825 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007826 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007827 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007828 CaptureRegion = OMPD_teams;
7829 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007830 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00007831 case OMPD_target_enter_data:
7832 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007833 CaptureRegion = OMPD_task;
7834 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007835 case OMPD_cancel:
7836 case OMPD_parallel:
7837 case OMPD_parallel_sections:
7838 case OMPD_parallel_for:
7839 case OMPD_parallel_for_simd:
7840 case OMPD_target:
7841 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007842 case OMPD_target_teams:
7843 case OMPD_target_teams_distribute:
7844 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007845 case OMPD_distribute_parallel_for:
7846 case OMPD_distribute_parallel_for_simd:
7847 case OMPD_task:
7848 case OMPD_taskloop:
7849 case OMPD_taskloop_simd:
7850 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007851 // Do not capture if-clause expressions.
7852 break;
7853 case OMPD_threadprivate:
7854 case OMPD_taskyield:
7855 case OMPD_barrier:
7856 case OMPD_taskwait:
7857 case OMPD_cancellation_point:
7858 case OMPD_flush:
7859 case OMPD_declare_reduction:
7860 case OMPD_declare_simd:
7861 case OMPD_declare_target:
7862 case OMPD_end_declare_target:
7863 case OMPD_teams:
7864 case OMPD_simd:
7865 case OMPD_for:
7866 case OMPD_for_simd:
7867 case OMPD_sections:
7868 case OMPD_section:
7869 case OMPD_single:
7870 case OMPD_master:
7871 case OMPD_critical:
7872 case OMPD_taskgroup:
7873 case OMPD_distribute:
7874 case OMPD_ordered:
7875 case OMPD_atomic:
7876 case OMPD_distribute_simd:
7877 case OMPD_teams_distribute:
7878 case OMPD_teams_distribute_simd:
7879 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7880 case OMPD_unknown:
7881 llvm_unreachable("Unknown OpenMP directive");
7882 }
7883 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007884 case OMPC_num_threads:
7885 switch (DKind) {
7886 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007887 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007888 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007889 CaptureRegion = OMPD_target;
7890 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007891 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007892 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00007893 case OMPD_target_teams_distribute_parallel_for:
7894 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007895 CaptureRegion = OMPD_teams;
7896 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007897 case OMPD_parallel:
7898 case OMPD_parallel_sections:
7899 case OMPD_parallel_for:
7900 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007901 case OMPD_distribute_parallel_for:
7902 case OMPD_distribute_parallel_for_simd:
7903 // Do not capture num_threads-clause expressions.
7904 break;
7905 case OMPD_target_data:
7906 case OMPD_target_enter_data:
7907 case OMPD_target_exit_data:
7908 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007909 case OMPD_target:
7910 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007911 case OMPD_target_teams:
7912 case OMPD_target_teams_distribute:
7913 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007914 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007915 case OMPD_task:
7916 case OMPD_taskloop:
7917 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007918 case OMPD_threadprivate:
7919 case OMPD_taskyield:
7920 case OMPD_barrier:
7921 case OMPD_taskwait:
7922 case OMPD_cancellation_point:
7923 case OMPD_flush:
7924 case OMPD_declare_reduction:
7925 case OMPD_declare_simd:
7926 case OMPD_declare_target:
7927 case OMPD_end_declare_target:
7928 case OMPD_teams:
7929 case OMPD_simd:
7930 case OMPD_for:
7931 case OMPD_for_simd:
7932 case OMPD_sections:
7933 case OMPD_section:
7934 case OMPD_single:
7935 case OMPD_master:
7936 case OMPD_critical:
7937 case OMPD_taskgroup:
7938 case OMPD_distribute:
7939 case OMPD_ordered:
7940 case OMPD_atomic:
7941 case OMPD_distribute_simd:
7942 case OMPD_teams_distribute:
7943 case OMPD_teams_distribute_simd:
7944 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7945 case OMPD_unknown:
7946 llvm_unreachable("Unknown OpenMP directive");
7947 }
7948 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007949 case OMPC_num_teams:
7950 switch (DKind) {
7951 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007952 case OMPD_target_teams_distribute:
7953 case OMPD_target_teams_distribute_simd:
7954 case OMPD_target_teams_distribute_parallel_for:
7955 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007956 CaptureRegion = OMPD_target;
7957 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007958 case OMPD_teams_distribute_parallel_for:
7959 case OMPD_teams_distribute_parallel_for_simd:
7960 case OMPD_teams:
7961 case OMPD_teams_distribute:
7962 case OMPD_teams_distribute_simd:
7963 // Do not capture num_teams-clause expressions.
7964 break;
7965 case OMPD_distribute_parallel_for:
7966 case OMPD_distribute_parallel_for_simd:
7967 case OMPD_task:
7968 case OMPD_taskloop:
7969 case OMPD_taskloop_simd:
7970 case OMPD_target_data:
7971 case OMPD_target_enter_data:
7972 case OMPD_target_exit_data:
7973 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007974 case OMPD_cancel:
7975 case OMPD_parallel:
7976 case OMPD_parallel_sections:
7977 case OMPD_parallel_for:
7978 case OMPD_parallel_for_simd:
7979 case OMPD_target:
7980 case OMPD_target_simd:
7981 case OMPD_target_parallel:
7982 case OMPD_target_parallel_for:
7983 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007984 case OMPD_threadprivate:
7985 case OMPD_taskyield:
7986 case OMPD_barrier:
7987 case OMPD_taskwait:
7988 case OMPD_cancellation_point:
7989 case OMPD_flush:
7990 case OMPD_declare_reduction:
7991 case OMPD_declare_simd:
7992 case OMPD_declare_target:
7993 case OMPD_end_declare_target:
7994 case OMPD_simd:
7995 case OMPD_for:
7996 case OMPD_for_simd:
7997 case OMPD_sections:
7998 case OMPD_section:
7999 case OMPD_single:
8000 case OMPD_master:
8001 case OMPD_critical:
8002 case OMPD_taskgroup:
8003 case OMPD_distribute:
8004 case OMPD_ordered:
8005 case OMPD_atomic:
8006 case OMPD_distribute_simd:
8007 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8008 case OMPD_unknown:
8009 llvm_unreachable("Unknown OpenMP directive");
8010 }
8011 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008012 case OMPC_thread_limit:
8013 switch (DKind) {
8014 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008015 case OMPD_target_teams_distribute:
8016 case OMPD_target_teams_distribute_simd:
8017 case OMPD_target_teams_distribute_parallel_for:
8018 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008019 CaptureRegion = OMPD_target;
8020 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008021 case OMPD_teams_distribute_parallel_for:
8022 case OMPD_teams_distribute_parallel_for_simd:
8023 case OMPD_teams:
8024 case OMPD_teams_distribute:
8025 case OMPD_teams_distribute_simd:
8026 // Do not capture thread_limit-clause expressions.
8027 break;
8028 case OMPD_distribute_parallel_for:
8029 case OMPD_distribute_parallel_for_simd:
8030 case OMPD_task:
8031 case OMPD_taskloop:
8032 case OMPD_taskloop_simd:
8033 case OMPD_target_data:
8034 case OMPD_target_enter_data:
8035 case OMPD_target_exit_data:
8036 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008037 case OMPD_cancel:
8038 case OMPD_parallel:
8039 case OMPD_parallel_sections:
8040 case OMPD_parallel_for:
8041 case OMPD_parallel_for_simd:
8042 case OMPD_target:
8043 case OMPD_target_simd:
8044 case OMPD_target_parallel:
8045 case OMPD_target_parallel_for:
8046 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008047 case OMPD_threadprivate:
8048 case OMPD_taskyield:
8049 case OMPD_barrier:
8050 case OMPD_taskwait:
8051 case OMPD_cancellation_point:
8052 case OMPD_flush:
8053 case OMPD_declare_reduction:
8054 case OMPD_declare_simd:
8055 case OMPD_declare_target:
8056 case OMPD_end_declare_target:
8057 case OMPD_simd:
8058 case OMPD_for:
8059 case OMPD_for_simd:
8060 case OMPD_sections:
8061 case OMPD_section:
8062 case OMPD_single:
8063 case OMPD_master:
8064 case OMPD_critical:
8065 case OMPD_taskgroup:
8066 case OMPD_distribute:
8067 case OMPD_ordered:
8068 case OMPD_atomic:
8069 case OMPD_distribute_simd:
8070 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8071 case OMPD_unknown:
8072 llvm_unreachable("Unknown OpenMP directive");
8073 }
8074 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008075 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008076 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008077 case OMPD_parallel_for:
8078 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008079 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008080 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008081 case OMPD_teams_distribute_parallel_for:
8082 case OMPD_teams_distribute_parallel_for_simd:
8083 case OMPD_target_parallel_for:
8084 case OMPD_target_parallel_for_simd:
8085 case OMPD_target_teams_distribute_parallel_for:
8086 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008087 CaptureRegion = OMPD_parallel;
8088 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008089 case OMPD_for:
8090 case OMPD_for_simd:
8091 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008092 break;
8093 case OMPD_task:
8094 case OMPD_taskloop:
8095 case OMPD_taskloop_simd:
8096 case OMPD_target_data:
8097 case OMPD_target_enter_data:
8098 case OMPD_target_exit_data:
8099 case OMPD_target_update:
8100 case OMPD_teams:
8101 case OMPD_teams_distribute:
8102 case OMPD_teams_distribute_simd:
8103 case OMPD_target_teams_distribute:
8104 case OMPD_target_teams_distribute_simd:
8105 case OMPD_target:
8106 case OMPD_target_simd:
8107 case OMPD_target_parallel:
8108 case OMPD_cancel:
8109 case OMPD_parallel:
8110 case OMPD_parallel_sections:
8111 case OMPD_threadprivate:
8112 case OMPD_taskyield:
8113 case OMPD_barrier:
8114 case OMPD_taskwait:
8115 case OMPD_cancellation_point:
8116 case OMPD_flush:
8117 case OMPD_declare_reduction:
8118 case OMPD_declare_simd:
8119 case OMPD_declare_target:
8120 case OMPD_end_declare_target:
8121 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008122 case OMPD_sections:
8123 case OMPD_section:
8124 case OMPD_single:
8125 case OMPD_master:
8126 case OMPD_critical:
8127 case OMPD_taskgroup:
8128 case OMPD_distribute:
8129 case OMPD_ordered:
8130 case OMPD_atomic:
8131 case OMPD_distribute_simd:
8132 case OMPD_target_teams:
8133 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8134 case OMPD_unknown:
8135 llvm_unreachable("Unknown OpenMP directive");
8136 }
8137 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008138 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008139 switch (DKind) {
8140 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008141 case OMPD_teams_distribute_parallel_for_simd:
8142 case OMPD_teams_distribute:
8143 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008144 case OMPD_target_teams_distribute_parallel_for:
8145 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008146 case OMPD_target_teams_distribute:
8147 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008148 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008149 break;
8150 case OMPD_distribute_parallel_for:
8151 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008152 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008153 case OMPD_distribute_simd:
8154 // Do not capture thread_limit-clause expressions.
8155 break;
8156 case OMPD_parallel_for:
8157 case OMPD_parallel_for_simd:
8158 case OMPD_target_parallel_for_simd:
8159 case OMPD_target_parallel_for:
8160 case OMPD_task:
8161 case OMPD_taskloop:
8162 case OMPD_taskloop_simd:
8163 case OMPD_target_data:
8164 case OMPD_target_enter_data:
8165 case OMPD_target_exit_data:
8166 case OMPD_target_update:
8167 case OMPD_teams:
8168 case OMPD_target:
8169 case OMPD_target_simd:
8170 case OMPD_target_parallel:
8171 case OMPD_cancel:
8172 case OMPD_parallel:
8173 case OMPD_parallel_sections:
8174 case OMPD_threadprivate:
8175 case OMPD_taskyield:
8176 case OMPD_barrier:
8177 case OMPD_taskwait:
8178 case OMPD_cancellation_point:
8179 case OMPD_flush:
8180 case OMPD_declare_reduction:
8181 case OMPD_declare_simd:
8182 case OMPD_declare_target:
8183 case OMPD_end_declare_target:
8184 case OMPD_simd:
8185 case OMPD_for:
8186 case OMPD_for_simd:
8187 case OMPD_sections:
8188 case OMPD_section:
8189 case OMPD_single:
8190 case OMPD_master:
8191 case OMPD_critical:
8192 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008193 case OMPD_ordered:
8194 case OMPD_atomic:
8195 case OMPD_target_teams:
8196 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8197 case OMPD_unknown:
8198 llvm_unreachable("Unknown OpenMP directive");
8199 }
8200 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008201 case OMPC_device:
8202 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008203 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008204 case OMPD_target_enter_data:
8205 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008206 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008207 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008208 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008209 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008210 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008211 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008212 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008213 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008214 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008215 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008216 CaptureRegion = OMPD_task;
8217 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008218 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008219 // Do not capture device-clause expressions.
8220 break;
8221 case OMPD_teams_distribute_parallel_for:
8222 case OMPD_teams_distribute_parallel_for_simd:
8223 case OMPD_teams:
8224 case OMPD_teams_distribute:
8225 case OMPD_teams_distribute_simd:
8226 case OMPD_distribute_parallel_for:
8227 case OMPD_distribute_parallel_for_simd:
8228 case OMPD_task:
8229 case OMPD_taskloop:
8230 case OMPD_taskloop_simd:
8231 case OMPD_cancel:
8232 case OMPD_parallel:
8233 case OMPD_parallel_sections:
8234 case OMPD_parallel_for:
8235 case OMPD_parallel_for_simd:
8236 case OMPD_threadprivate:
8237 case OMPD_taskyield:
8238 case OMPD_barrier:
8239 case OMPD_taskwait:
8240 case OMPD_cancellation_point:
8241 case OMPD_flush:
8242 case OMPD_declare_reduction:
8243 case OMPD_declare_simd:
8244 case OMPD_declare_target:
8245 case OMPD_end_declare_target:
8246 case OMPD_simd:
8247 case OMPD_for:
8248 case OMPD_for_simd:
8249 case OMPD_sections:
8250 case OMPD_section:
8251 case OMPD_single:
8252 case OMPD_master:
8253 case OMPD_critical:
8254 case OMPD_taskgroup:
8255 case OMPD_distribute:
8256 case OMPD_ordered:
8257 case OMPD_atomic:
8258 case OMPD_distribute_simd:
8259 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8260 case OMPD_unknown:
8261 llvm_unreachable("Unknown OpenMP directive");
8262 }
8263 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008264 case OMPC_firstprivate:
8265 case OMPC_lastprivate:
8266 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008267 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008268 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008269 case OMPC_linear:
8270 case OMPC_default:
8271 case OMPC_proc_bind:
8272 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008273 case OMPC_safelen:
8274 case OMPC_simdlen:
8275 case OMPC_collapse:
8276 case OMPC_private:
8277 case OMPC_shared:
8278 case OMPC_aligned:
8279 case OMPC_copyin:
8280 case OMPC_copyprivate:
8281 case OMPC_ordered:
8282 case OMPC_nowait:
8283 case OMPC_untied:
8284 case OMPC_mergeable:
8285 case OMPC_threadprivate:
8286 case OMPC_flush:
8287 case OMPC_read:
8288 case OMPC_write:
8289 case OMPC_update:
8290 case OMPC_capture:
8291 case OMPC_seq_cst:
8292 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008293 case OMPC_threads:
8294 case OMPC_simd:
8295 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008296 case OMPC_priority:
8297 case OMPC_grainsize:
8298 case OMPC_nogroup:
8299 case OMPC_num_tasks:
8300 case OMPC_hint:
8301 case OMPC_defaultmap:
8302 case OMPC_unknown:
8303 case OMPC_uniform:
8304 case OMPC_to:
8305 case OMPC_from:
8306 case OMPC_use_device_ptr:
8307 case OMPC_is_device_ptr:
8308 llvm_unreachable("Unexpected OpenMP clause.");
8309 }
8310 return CaptureRegion;
8311}
8312
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008313OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8314 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008315 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008316 SourceLocation NameModifierLoc,
8317 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008318 SourceLocation EndLoc) {
8319 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008320 Stmt *HelperValStmt = nullptr;
8321 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008322 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8323 !Condition->isInstantiationDependent() &&
8324 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008325 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008326 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008327 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008328
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008329 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008330
8331 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8332 CaptureRegion =
8333 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008334 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008335 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008336 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8337 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8338 HelperValStmt = buildPreInits(Context, Captures);
8339 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008340 }
8341
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008342 return new (Context)
8343 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8344 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008345}
8346
Alexey Bataev3778b602014-07-17 07:32:53 +00008347OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8348 SourceLocation StartLoc,
8349 SourceLocation LParenLoc,
8350 SourceLocation EndLoc) {
8351 Expr *ValExpr = Condition;
8352 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8353 !Condition->isInstantiationDependent() &&
8354 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008355 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008356 if (Val.isInvalid())
8357 return nullptr;
8358
Richard Smith03a4aa32016-06-23 19:02:52 +00008359 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008360 }
8361
8362 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8363}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008364ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8365 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008366 if (!Op)
8367 return ExprError();
8368
8369 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8370 public:
8371 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008372 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008373 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8374 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008375 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8376 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008377 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8378 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008379 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8380 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008381 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8382 QualType T,
8383 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008384 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8385 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008386 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8387 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008388 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008389 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008390 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008391 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8392 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008393 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8394 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008395 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8396 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008397 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008398 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008399 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008400 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8401 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008402 llvm_unreachable("conversion functions are permitted");
8403 }
8404 } ConvertDiagnoser;
8405 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8406}
8407
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008408static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008409 OpenMPClauseKind CKind,
8410 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008411 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8412 !ValExpr->isInstantiationDependent()) {
8413 SourceLocation Loc = ValExpr->getExprLoc();
8414 ExprResult Value =
8415 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8416 if (Value.isInvalid())
8417 return false;
8418
8419 ValExpr = Value.get();
8420 // The expression must evaluate to a non-negative integer value.
8421 llvm::APSInt Result;
8422 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008423 Result.isSigned() &&
8424 !((!StrictlyPositive && Result.isNonNegative()) ||
8425 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008426 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008427 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8428 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008429 return false;
8430 }
8431 }
8432 return true;
8433}
8434
Alexey Bataev568a8332014-03-06 06:15:19 +00008435OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8436 SourceLocation StartLoc,
8437 SourceLocation LParenLoc,
8438 SourceLocation EndLoc) {
8439 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008440 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008441
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008442 // OpenMP [2.5, Restrictions]
8443 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008444 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8445 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008446 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008447
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008448 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008449 OpenMPDirectiveKind CaptureRegion =
8450 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8451 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008452 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008453 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8454 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8455 HelperValStmt = buildPreInits(Context, Captures);
8456 }
8457
8458 return new (Context) OMPNumThreadsClause(
8459 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008460}
8461
Alexey Bataev62c87d22014-03-21 04:51:18 +00008462ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008463 OpenMPClauseKind CKind,
8464 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008465 if (!E)
8466 return ExprError();
8467 if (E->isValueDependent() || E->isTypeDependent() ||
8468 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008469 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008470 llvm::APSInt Result;
8471 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8472 if (ICE.isInvalid())
8473 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008474 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8475 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008476 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008477 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8478 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008479 return ExprError();
8480 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008481 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8482 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8483 << E->getSourceRange();
8484 return ExprError();
8485 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008486 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8487 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008488 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008489 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008490 return ICE;
8491}
8492
8493OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8494 SourceLocation LParenLoc,
8495 SourceLocation EndLoc) {
8496 // OpenMP [2.8.1, simd construct, Description]
8497 // The parameter of the safelen clause must be a constant
8498 // positive integer expression.
8499 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8500 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008501 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008502 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008503 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008504}
8505
Alexey Bataev66b15b52015-08-21 11:14:16 +00008506OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8507 SourceLocation LParenLoc,
8508 SourceLocation EndLoc) {
8509 // OpenMP [2.8.1, simd construct, Description]
8510 // The parameter of the simdlen clause must be a constant
8511 // positive integer expression.
8512 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8513 if (Simdlen.isInvalid())
8514 return nullptr;
8515 return new (Context)
8516 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8517}
8518
Alexander Musman64d33f12014-06-04 07:53:32 +00008519OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8520 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008521 SourceLocation LParenLoc,
8522 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008523 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008524 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008525 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008526 // The parameter of the collapse clause must be a constant
8527 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008528 ExprResult NumForLoopsResult =
8529 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8530 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008531 return nullptr;
8532 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008533 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008534}
8535
Alexey Bataev10e775f2015-07-30 11:36:16 +00008536OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8537 SourceLocation EndLoc,
8538 SourceLocation LParenLoc,
8539 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008540 // OpenMP [2.7.1, loop construct, Description]
8541 // OpenMP [2.8.1, simd construct, Description]
8542 // OpenMP [2.9.6, distribute construct, Description]
8543 // The parameter of the ordered clause must be a constant
8544 // positive integer expression if any.
8545 if (NumForLoops && LParenLoc.isValid()) {
8546 ExprResult NumForLoopsResult =
8547 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8548 if (NumForLoopsResult.isInvalid())
8549 return nullptr;
8550 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008551 } else
8552 NumForLoops = nullptr;
8553 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008554 return new (Context)
8555 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8556}
8557
Alexey Bataeved09d242014-05-28 05:53:51 +00008558OMPClause *Sema::ActOnOpenMPSimpleClause(
8559 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8560 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008561 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008562 switch (Kind) {
8563 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008564 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008565 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8566 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008567 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008568 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008569 Res = ActOnOpenMPProcBindClause(
8570 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8571 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008572 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008573 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008574 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008575 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008576 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008577 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008578 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008579 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008580 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008581 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008582 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008583 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008584 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008585 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008586 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008587 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008588 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008589 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008590 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008591 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008592 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008593 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008594 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008595 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008596 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008597 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008598 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008599 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008600 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008601 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008602 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008603 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008604 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008605 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008606 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008607 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008608 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008609 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008610 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008611 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008612 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008613 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008614 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008615 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008616 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008617 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008618 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008619 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008620 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008621 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008622 llvm_unreachable("Clause is not allowed.");
8623 }
8624 return Res;
8625}
8626
Alexey Bataev6402bca2015-12-28 07:25:51 +00008627static std::string
8628getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8629 ArrayRef<unsigned> Exclude = llvm::None) {
8630 std::string Values;
8631 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8632 unsigned Skipped = Exclude.size();
8633 auto S = Exclude.begin(), E = Exclude.end();
8634 for (unsigned i = First; i < Last; ++i) {
8635 if (std::find(S, E, i) != E) {
8636 --Skipped;
8637 continue;
8638 }
8639 Values += "'";
8640 Values += getOpenMPSimpleClauseTypeName(K, i);
8641 Values += "'";
8642 if (i == Bound - Skipped)
8643 Values += " or ";
8644 else if (i != Bound + 1 - Skipped)
8645 Values += ", ";
8646 }
8647 return Values;
8648}
8649
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008650OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8651 SourceLocation KindKwLoc,
8652 SourceLocation StartLoc,
8653 SourceLocation LParenLoc,
8654 SourceLocation EndLoc) {
8655 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008656 static_assert(OMPC_DEFAULT_unknown > 0,
8657 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008658 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008659 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8660 /*Last=*/OMPC_DEFAULT_unknown)
8661 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008662 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008663 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008664 switch (Kind) {
8665 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008666 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008667 break;
8668 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008669 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008670 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008671 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008672 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008673 break;
8674 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008675 return new (Context)
8676 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008677}
8678
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008679OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8680 SourceLocation KindKwLoc,
8681 SourceLocation StartLoc,
8682 SourceLocation LParenLoc,
8683 SourceLocation EndLoc) {
8684 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008685 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008686 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8687 /*Last=*/OMPC_PROC_BIND_unknown)
8688 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008689 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008690 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008691 return new (Context)
8692 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008693}
8694
Alexey Bataev56dafe82014-06-20 07:16:17 +00008695OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008696 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008697 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008698 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008699 SourceLocation EndLoc) {
8700 OMPClause *Res = nullptr;
8701 switch (Kind) {
8702 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008703 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8704 assert(Argument.size() == NumberOfElements &&
8705 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008706 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008707 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8708 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8709 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8710 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8711 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008712 break;
8713 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008714 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8715 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8716 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8717 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008718 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008719 case OMPC_dist_schedule:
8720 Res = ActOnOpenMPDistScheduleClause(
8721 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8722 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8723 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008724 case OMPC_defaultmap:
8725 enum { Modifier, DefaultmapKind };
8726 Res = ActOnOpenMPDefaultmapClause(
8727 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8728 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008729 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8730 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008731 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008732 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008733 case OMPC_num_threads:
8734 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008735 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008736 case OMPC_collapse:
8737 case OMPC_default:
8738 case OMPC_proc_bind:
8739 case OMPC_private:
8740 case OMPC_firstprivate:
8741 case OMPC_lastprivate:
8742 case OMPC_shared:
8743 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008744 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008745 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008746 case OMPC_linear:
8747 case OMPC_aligned:
8748 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008749 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008750 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008751 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008752 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008753 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008754 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008755 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008756 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008757 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008758 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008759 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008760 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008761 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008762 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008763 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008764 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008765 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008766 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008767 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008768 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008769 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008770 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008771 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008772 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008773 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008774 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008775 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008776 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008777 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008778 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008779 llvm_unreachable("Clause is not allowed.");
8780 }
8781 return Res;
8782}
8783
Alexey Bataev6402bca2015-12-28 07:25:51 +00008784static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8785 OpenMPScheduleClauseModifier M2,
8786 SourceLocation M1Loc, SourceLocation M2Loc) {
8787 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8788 SmallVector<unsigned, 2> Excluded;
8789 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8790 Excluded.push_back(M2);
8791 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8792 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8793 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8794 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8795 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8796 << getListOfPossibleValues(OMPC_schedule,
8797 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8798 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8799 Excluded)
8800 << getOpenMPClauseName(OMPC_schedule);
8801 return true;
8802 }
8803 return false;
8804}
8805
Alexey Bataev56dafe82014-06-20 07:16:17 +00008806OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008807 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008808 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008809 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8810 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8811 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8812 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8813 return nullptr;
8814 // OpenMP, 2.7.1, Loop Construct, Restrictions
8815 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8816 // but not both.
8817 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8818 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8819 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8820 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8821 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8822 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8823 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8824 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8825 return nullptr;
8826 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008827 if (Kind == OMPC_SCHEDULE_unknown) {
8828 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008829 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8830 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8831 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8832 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8833 Exclude);
8834 } else {
8835 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8836 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008837 }
8838 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8839 << Values << getOpenMPClauseName(OMPC_schedule);
8840 return nullptr;
8841 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008842 // OpenMP, 2.7.1, Loop Construct, Restrictions
8843 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8844 // schedule(guided).
8845 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8846 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8847 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8848 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8849 diag::err_omp_schedule_nonmonotonic_static);
8850 return nullptr;
8851 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008852 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008853 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008854 if (ChunkSize) {
8855 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8856 !ChunkSize->isInstantiationDependent() &&
8857 !ChunkSize->containsUnexpandedParameterPack()) {
8858 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8859 ExprResult Val =
8860 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8861 if (Val.isInvalid())
8862 return nullptr;
8863
8864 ValExpr = Val.get();
8865
8866 // OpenMP [2.7.1, Restrictions]
8867 // chunk_size must be a loop invariant integer expression with a positive
8868 // value.
8869 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008870 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8871 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8872 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008873 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008874 return nullptr;
8875 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008876 } else if (getOpenMPCaptureRegionForClause(
8877 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8878 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008879 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008880 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008881 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8882 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8883 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008884 }
8885 }
8886 }
8887
Alexey Bataev6402bca2015-12-28 07:25:51 +00008888 return new (Context)
8889 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008890 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008891}
8892
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008893OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8894 SourceLocation StartLoc,
8895 SourceLocation EndLoc) {
8896 OMPClause *Res = nullptr;
8897 switch (Kind) {
8898 case OMPC_ordered:
8899 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8900 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008901 case OMPC_nowait:
8902 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8903 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008904 case OMPC_untied:
8905 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8906 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008907 case OMPC_mergeable:
8908 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8909 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008910 case OMPC_read:
8911 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8912 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008913 case OMPC_write:
8914 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8915 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008916 case OMPC_update:
8917 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8918 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008919 case OMPC_capture:
8920 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8921 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008922 case OMPC_seq_cst:
8923 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8924 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008925 case OMPC_threads:
8926 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8927 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008928 case OMPC_simd:
8929 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8930 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008931 case OMPC_nogroup:
8932 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8933 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008934 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008935 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008936 case OMPC_num_threads:
8937 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008938 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008939 case OMPC_collapse:
8940 case OMPC_schedule:
8941 case OMPC_private:
8942 case OMPC_firstprivate:
8943 case OMPC_lastprivate:
8944 case OMPC_shared:
8945 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008946 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008947 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008948 case OMPC_linear:
8949 case OMPC_aligned:
8950 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008951 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008952 case OMPC_default:
8953 case OMPC_proc_bind:
8954 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008955 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008956 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008957 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008958 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008959 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008960 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008961 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008962 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008963 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008964 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008965 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008966 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008967 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008968 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008969 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008970 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008971 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008972 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008973 llvm_unreachable("Clause is not allowed.");
8974 }
8975 return Res;
8976}
8977
Alexey Bataev236070f2014-06-20 11:19:47 +00008978OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8979 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008980 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008981 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8982}
8983
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008984OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8985 SourceLocation EndLoc) {
8986 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8987}
8988
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008989OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8990 SourceLocation EndLoc) {
8991 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8992}
8993
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008994OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8995 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008996 return new (Context) OMPReadClause(StartLoc, EndLoc);
8997}
8998
Alexey Bataevdea47612014-07-23 07:46:59 +00008999OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9000 SourceLocation EndLoc) {
9001 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9002}
9003
Alexey Bataev67a4f222014-07-23 10:25:33 +00009004OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9005 SourceLocation EndLoc) {
9006 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9007}
9008
Alexey Bataev459dec02014-07-24 06:46:57 +00009009OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9010 SourceLocation EndLoc) {
9011 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9012}
9013
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009014OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9015 SourceLocation EndLoc) {
9016 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9017}
9018
Alexey Bataev346265e2015-09-25 10:37:12 +00009019OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9020 SourceLocation EndLoc) {
9021 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9022}
9023
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009024OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9025 SourceLocation EndLoc) {
9026 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9027}
9028
Alexey Bataevb825de12015-12-07 10:51:44 +00009029OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9030 SourceLocation EndLoc) {
9031 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9032}
9033
Alexey Bataevc5e02582014-06-16 07:08:35 +00009034OMPClause *Sema::ActOnOpenMPVarListClause(
9035 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9036 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9037 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009038 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00009039 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9040 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9041 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009042 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009043 switch (Kind) {
9044 case OMPC_private:
9045 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9046 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009047 case OMPC_firstprivate:
9048 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9049 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009050 case OMPC_lastprivate:
9051 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9052 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009053 case OMPC_shared:
9054 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9055 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009056 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009057 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9058 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009059 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009060 case OMPC_task_reduction:
9061 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9062 EndLoc, ReductionIdScopeSpec,
9063 ReductionId);
9064 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009065 case OMPC_in_reduction:
9066 Res =
9067 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9068 EndLoc, ReductionIdScopeSpec, ReductionId);
9069 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009070 case OMPC_linear:
9071 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009072 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009073 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009074 case OMPC_aligned:
9075 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9076 ColonLoc, EndLoc);
9077 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009078 case OMPC_copyin:
9079 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9080 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009081 case OMPC_copyprivate:
9082 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9083 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009084 case OMPC_flush:
9085 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9086 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009087 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009088 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009089 StartLoc, LParenLoc, EndLoc);
9090 break;
9091 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00009092 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9093 DepLinMapLoc, ColonLoc, VarList, StartLoc,
9094 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009095 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009096 case OMPC_to:
9097 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9098 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009099 case OMPC_from:
9100 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9101 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009102 case OMPC_use_device_ptr:
9103 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9104 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009105 case OMPC_is_device_ptr:
9106 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9107 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009108 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009109 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009110 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009111 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009112 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009113 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009114 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009115 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009116 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009117 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009118 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009119 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009120 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009121 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009122 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009123 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009124 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009125 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009126 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009127 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009128 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009129 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009130 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009131 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009132 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009133 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009134 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009135 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009136 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009137 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009138 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009139 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009140 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009141 llvm_unreachable("Clause is not allowed.");
9142 }
9143 return Res;
9144}
9145
Alexey Bataev90c228f2016-02-08 09:29:13 +00009146ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009147 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009148 ExprResult Res = BuildDeclRefExpr(
9149 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9150 if (!Res.isUsable())
9151 return ExprError();
9152 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9153 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9154 if (!Res.isUsable())
9155 return ExprError();
9156 }
9157 if (VK != VK_LValue && Res.get()->isGLValue()) {
9158 Res = DefaultLvalueConversion(Res.get());
9159 if (!Res.isUsable())
9160 return ExprError();
9161 }
9162 return Res;
9163}
9164
Alexey Bataev60da77e2016-02-29 05:54:20 +00009165static std::pair<ValueDecl *, bool>
9166getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9167 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009168 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9169 RefExpr->containsUnexpandedParameterPack())
9170 return std::make_pair(nullptr, true);
9171
Alexey Bataevd985eda2016-02-10 11:29:16 +00009172 // OpenMP [3.1, C/C++]
9173 // A list item is a variable name.
9174 // OpenMP [2.9.3.3, Restrictions, p.1]
9175 // A variable that is part of another variable (as an array or
9176 // structure element) cannot appear in a private clause.
9177 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009178 enum {
9179 NoArrayExpr = -1,
9180 ArraySubscript = 0,
9181 OMPArraySection = 1
9182 } IsArrayExpr = NoArrayExpr;
9183 if (AllowArraySection) {
9184 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9185 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9186 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9187 Base = TempASE->getBase()->IgnoreParenImpCasts();
9188 RefExpr = Base;
9189 IsArrayExpr = ArraySubscript;
9190 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9191 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9192 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9193 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9194 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9195 Base = TempASE->getBase()->IgnoreParenImpCasts();
9196 RefExpr = Base;
9197 IsArrayExpr = OMPArraySection;
9198 }
9199 }
9200 ELoc = RefExpr->getExprLoc();
9201 ERange = RefExpr->getSourceRange();
9202 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009203 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9204 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9205 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9206 (S.getCurrentThisType().isNull() || !ME ||
9207 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9208 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009209 if (IsArrayExpr != NoArrayExpr)
9210 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9211 << ERange;
9212 else {
9213 S.Diag(ELoc,
9214 AllowArraySection
9215 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9216 : diag::err_omp_expected_var_name_member_expr)
9217 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9218 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009219 return std::make_pair(nullptr, false);
9220 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009221 return std::make_pair(
9222 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009223}
9224
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009225OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9226 SourceLocation StartLoc,
9227 SourceLocation LParenLoc,
9228 SourceLocation EndLoc) {
9229 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009230 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00009231 for (auto &RefExpr : VarList) {
9232 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009233 SourceLocation ELoc;
9234 SourceRange ERange;
9235 Expr *SimpleRefExpr = RefExpr;
9236 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009237 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009238 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009239 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009240 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009241 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009242 ValueDecl *D = Res.first;
9243 if (!D)
9244 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009245
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009246 QualType Type = D->getType();
9247 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009248
9249 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9250 // A variable that appears in a private clause must not have an incomplete
9251 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009252 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009253 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009254 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009255
Alexey Bataev758e55e2013-09-06 18:03:48 +00009256 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9257 // in a Construct]
9258 // Variables with the predetermined data-sharing attributes may not be
9259 // listed in data-sharing attributes clauses, except for the cases
9260 // listed below. For these exceptions only, listing a predetermined
9261 // variable in a data-sharing attribute clause is allowed and overrides
9262 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009263 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009264 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009265 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9266 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009267 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009268 continue;
9269 }
9270
Kelvin Libf594a52016-12-17 05:48:59 +00009271 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009272 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009273 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009274 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009275 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9276 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009277 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009278 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009279 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009280 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009281 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009282 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009283 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009284 continue;
9285 }
9286
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009287 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9288 // A list item cannot appear in both a map clause and a data-sharing
9289 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009290 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Alexey Bataev647dd842018-01-15 20:59:40 +00009291 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009292 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009293 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009294 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009295 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009296 CurrDir == OMPD_target_parallel_for_simd ||
9297 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009298 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009299 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009300 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009301 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9302 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9303 ConflictKind = WhereFoundClauseKind;
9304 return true;
9305 })) {
9306 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009307 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009308 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009309 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009310 ReportOriginalDSA(*this, DSAStack, D, DVar);
9311 continue;
9312 }
9313 }
9314
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009315 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9316 // A variable of class type (or array thereof) that appears in a private
9317 // clause requires an accessible, unambiguous default constructor for the
9318 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009319 // Generate helper private variable and initialize it with the default
9320 // value. The address of the original variable is replaced by the address of
9321 // the new private variable in CodeGen. This new variable is not added to
9322 // IdResolver, so the code in the OpenMP region uses original variable for
9323 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009324 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009325 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9326 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009327 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009328 if (VDPrivate->isInvalidDecl())
9329 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009330 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009331 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009332
Alexey Bataev90c228f2016-02-08 09:29:13 +00009333 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009334 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009335 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009336 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009337 Vars.push_back((VD || CurContext->isDependentContext())
9338 ? RefExpr->IgnoreParens()
9339 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009340 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009341 }
9342
Alexey Bataeved09d242014-05-28 05:53:51 +00009343 if (Vars.empty())
9344 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009345
Alexey Bataev03b340a2014-10-21 03:16:40 +00009346 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9347 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009348}
9349
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009350namespace {
9351class DiagsUninitializedSeveretyRAII {
9352private:
9353 DiagnosticsEngine &Diags;
9354 SourceLocation SavedLoc;
9355 bool IsIgnored;
9356
9357public:
9358 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9359 bool IsIgnored)
9360 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9361 if (!IsIgnored) {
9362 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9363 /*Map*/ diag::Severity::Ignored, Loc);
9364 }
9365 }
9366 ~DiagsUninitializedSeveretyRAII() {
9367 if (!IsIgnored)
9368 Diags.popMappings(SavedLoc);
9369 }
9370};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009371}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009372
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009373OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9374 SourceLocation StartLoc,
9375 SourceLocation LParenLoc,
9376 SourceLocation EndLoc) {
9377 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009378 SmallVector<Expr *, 8> PrivateCopies;
9379 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009380 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009381 bool IsImplicitClause =
9382 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9383 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9384
Alexey Bataeved09d242014-05-28 05:53:51 +00009385 for (auto &RefExpr : VarList) {
9386 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009387 SourceLocation ELoc;
9388 SourceRange ERange;
9389 Expr *SimpleRefExpr = RefExpr;
9390 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009391 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009392 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009393 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009394 PrivateCopies.push_back(nullptr);
9395 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009396 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009397 ValueDecl *D = Res.first;
9398 if (!D)
9399 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009400
Alexey Bataev60da77e2016-02-29 05:54:20 +00009401 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009402 QualType Type = D->getType();
9403 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009404
9405 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9406 // A variable that appears in a private clause must not have an incomplete
9407 // type or a reference type.
9408 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009409 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009410 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009411 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009412
9413 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9414 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009415 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009416 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009417 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009418
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009419 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009420 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009421 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009422 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009423 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009424 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009425 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009426 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9427 // A list item that specifies a given variable may not appear in more
9428 // than one clause on the same directive, except that a variable may be
9429 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009430 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9431 // A list item may appear in a firstprivate or lastprivate clause but not
9432 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009433 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009434 (isOpenMPDistributeDirective(CurrDir) ||
9435 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009436 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009437 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009438 << getOpenMPClauseName(DVar.CKind)
9439 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009440 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009441 continue;
9442 }
9443
9444 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9445 // in a Construct]
9446 // Variables with the predetermined data-sharing attributes may not be
9447 // listed in data-sharing attributes clauses, except for the cases
9448 // listed below. For these exceptions only, listing a predetermined
9449 // variable in a data-sharing attribute clause is allowed and overrides
9450 // the variable's predetermined data-sharing attributes.
9451 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9452 // in a Construct, C/C++, p.2]
9453 // Variables with const-qualified type having no mutable member may be
9454 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009455 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009456 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9457 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009458 << getOpenMPClauseName(DVar.CKind)
9459 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009460 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009461 continue;
9462 }
9463
9464 // OpenMP [2.9.3.4, Restrictions, p.2]
9465 // A list item that is private within a parallel region must not appear
9466 // in a firstprivate clause on a worksharing construct if any of the
9467 // worksharing regions arising from the worksharing construct ever bind
9468 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009469 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9470 // A list item that is private within a teams region must not appear in a
9471 // firstprivate clause on a distribute construct if any of the distribute
9472 // regions arising from the distribute construct ever bind to any of the
9473 // teams regions arising from the teams construct.
9474 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9475 // A list item that appears in a reduction clause of a teams construct
9476 // must not appear in a firstprivate clause on a distribute construct if
9477 // any of the distribute regions arising from the distribute construct
9478 // ever bind to any of the teams regions arising from the teams construct.
9479 if ((isOpenMPWorksharingDirective(CurrDir) ||
9480 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009481 !isOpenMPParallelDirective(CurrDir) &&
9482 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009483 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009484 if (DVar.CKind != OMPC_shared &&
9485 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009486 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009487 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009488 Diag(ELoc, diag::err_omp_required_access)
9489 << getOpenMPClauseName(OMPC_firstprivate)
9490 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009491 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009492 continue;
9493 }
9494 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009495 // OpenMP [2.9.3.4, Restrictions, p.3]
9496 // A list item that appears in a reduction clause of a parallel construct
9497 // must not appear in a firstprivate clause on a worksharing or task
9498 // construct if any of the worksharing or task regions arising from the
9499 // worksharing or task construct ever bind to any of the parallel regions
9500 // arising from the parallel construct.
9501 // OpenMP [2.9.3.4, Restrictions, p.4]
9502 // A list item that appears in a reduction clause in worksharing
9503 // construct must not appear in a firstprivate clause in a task construct
9504 // encountered during execution of any of the worksharing regions arising
9505 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009506 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009507 DVar = DSAStack->hasInnermostDSA(
9508 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9509 [](OpenMPDirectiveKind K) -> bool {
9510 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009511 isOpenMPWorksharingDirective(K) ||
9512 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009513 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009514 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009515 if (DVar.CKind == OMPC_reduction &&
9516 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009517 isOpenMPWorksharingDirective(DVar.DKind) ||
9518 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009519 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9520 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009521 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009522 continue;
9523 }
9524 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009525
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009526 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9527 // A list item cannot appear in both a map clause and a data-sharing
9528 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009529 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009530 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009531 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009532 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009533 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9534 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9535 ConflictKind = WhereFoundClauseKind;
9536 return true;
9537 })) {
9538 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009539 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009540 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009541 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9542 ReportOriginalDSA(*this, DSAStack, D, DVar);
9543 continue;
9544 }
9545 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009546 }
9547
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009548 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009549 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009550 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009551 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9552 << getOpenMPClauseName(OMPC_firstprivate) << Type
9553 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9554 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009555 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009556 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009557 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009558 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009559 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009560 continue;
9561 }
9562
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009563 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009564 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9565 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009566 // Generate helper private variable and initialize it with the value of the
9567 // original variable. The address of the original variable is replaced by
9568 // the address of the new private variable in the CodeGen. This new variable
9569 // is not added to IdResolver, so the code in the OpenMP region uses
9570 // original variable for proper diagnostics and variable capturing.
9571 Expr *VDInitRefExpr = nullptr;
9572 // For arrays generate initializer for single element and replace it by the
9573 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009574 if (Type->isArrayType()) {
9575 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009576 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009577 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009578 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009579 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009580 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009581 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009582 InitializedEntity Entity =
9583 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009584 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9585
9586 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9587 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9588 if (Result.isInvalid())
9589 VDPrivate->setInvalidDecl();
9590 else
9591 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009592 // Remove temp variable declaration.
9593 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009594 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009595 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9596 ".firstprivate.temp");
9597 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9598 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009599 AddInitializerToDecl(VDPrivate,
9600 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009601 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009602 }
9603 if (VDPrivate->isInvalidDecl()) {
9604 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009605 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009606 diag::note_omp_task_predetermined_firstprivate_here);
9607 }
9608 continue;
9609 }
9610 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009611 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009612 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9613 RefExpr->getExprLoc());
9614 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009615 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009616 if (TopDVar.CKind == OMPC_lastprivate)
9617 Ref = TopDVar.PrivateCopy;
9618 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009619 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009620 if (!IsOpenMPCapturedDecl(D))
9621 ExprCaptures.push_back(Ref->getDecl());
9622 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009623 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009624 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009625 Vars.push_back((VD || CurContext->isDependentContext())
9626 ? RefExpr->IgnoreParens()
9627 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009628 PrivateCopies.push_back(VDPrivateRefExpr);
9629 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009630 }
9631
Alexey Bataeved09d242014-05-28 05:53:51 +00009632 if (Vars.empty())
9633 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009634
9635 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009636 Vars, PrivateCopies, Inits,
9637 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009638}
9639
Alexander Musman1bb328c2014-06-04 13:06:39 +00009640OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9641 SourceLocation StartLoc,
9642 SourceLocation LParenLoc,
9643 SourceLocation EndLoc) {
9644 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009645 SmallVector<Expr *, 8> SrcExprs;
9646 SmallVector<Expr *, 8> DstExprs;
9647 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009648 SmallVector<Decl *, 4> ExprCaptures;
9649 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009650 for (auto &RefExpr : VarList) {
9651 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009652 SourceLocation ELoc;
9653 SourceRange ERange;
9654 Expr *SimpleRefExpr = RefExpr;
9655 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009656 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009657 // It will be analyzed later.
9658 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009659 SrcExprs.push_back(nullptr);
9660 DstExprs.push_back(nullptr);
9661 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009662 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009663 ValueDecl *D = Res.first;
9664 if (!D)
9665 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009666
Alexey Bataev74caaf22016-02-20 04:09:36 +00009667 QualType Type = D->getType();
9668 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009669
9670 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9671 // A variable that appears in a lastprivate clause must not have an
9672 // incomplete type or a reference type.
9673 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009674 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009675 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009676 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009677
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009678 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009679 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9680 // in a Construct]
9681 // Variables with the predetermined data-sharing attributes may not be
9682 // listed in data-sharing attributes clauses, except for the cases
9683 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009684 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9685 // A list item may appear in a firstprivate or lastprivate clause but not
9686 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009687 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009688 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009689 (isOpenMPDistributeDirective(CurrDir) ||
9690 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009691 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9692 Diag(ELoc, diag::err_omp_wrong_dsa)
9693 << getOpenMPClauseName(DVar.CKind)
9694 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009695 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009696 continue;
9697 }
9698
Alexey Bataevf29276e2014-06-18 04:14:57 +00009699 // OpenMP [2.14.3.5, Restrictions, p.2]
9700 // A list item that is private within a parallel region, or that appears in
9701 // the reduction clause of a parallel construct, must not appear in a
9702 // lastprivate clause on a worksharing construct if any of the corresponding
9703 // worksharing regions ever binds to any of the corresponding parallel
9704 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009705 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009706 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009707 !isOpenMPParallelDirective(CurrDir) &&
9708 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009709 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009710 if (DVar.CKind != OMPC_shared) {
9711 Diag(ELoc, diag::err_omp_required_access)
9712 << getOpenMPClauseName(OMPC_lastprivate)
9713 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009714 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009715 continue;
9716 }
9717 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009718
Alexander Musman1bb328c2014-06-04 13:06:39 +00009719 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009720 // A variable of class type (or array thereof) that appears in a
9721 // lastprivate clause requires an accessible, unambiguous default
9722 // constructor for the class type, unless the list item is also specified
9723 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009724 // A variable of class type (or array thereof) that appears in a
9725 // lastprivate clause requires an accessible, unambiguous copy assignment
9726 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009727 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009728 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009729 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009730 D->hasAttrs() ? &D->getAttrs() : nullptr);
9731 auto *PseudoSrcExpr =
9732 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009733 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009734 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009735 D->hasAttrs() ? &D->getAttrs() : nullptr);
9736 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009737 // For arrays generate assignment operation for single element and replace
9738 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009739 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009740 PseudoDstExpr, PseudoSrcExpr);
9741 if (AssignmentOp.isInvalid())
9742 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009743 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009744 /*DiscardedValue=*/true);
9745 if (AssignmentOp.isInvalid())
9746 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009747
Alexey Bataev74caaf22016-02-20 04:09:36 +00009748 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009749 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009750 if (TopDVar.CKind == OMPC_firstprivate)
9751 Ref = TopDVar.PrivateCopy;
9752 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009753 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009754 if (!IsOpenMPCapturedDecl(D))
9755 ExprCaptures.push_back(Ref->getDecl());
9756 }
9757 if (TopDVar.CKind == OMPC_firstprivate ||
9758 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009759 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009760 ExprResult RefRes = DefaultLvalueConversion(Ref);
9761 if (!RefRes.isUsable())
9762 continue;
9763 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009764 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9765 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009766 if (!PostUpdateRes.isUsable())
9767 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009768 ExprPostUpdates.push_back(
9769 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009770 }
9771 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009772 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009773 Vars.push_back((VD || CurContext->isDependentContext())
9774 ? RefExpr->IgnoreParens()
9775 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009776 SrcExprs.push_back(PseudoSrcExpr);
9777 DstExprs.push_back(PseudoDstExpr);
9778 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009779 }
9780
9781 if (Vars.empty())
9782 return nullptr;
9783
9784 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009785 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009786 buildPreInits(Context, ExprCaptures),
9787 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009788}
9789
Alexey Bataev758e55e2013-09-06 18:03:48 +00009790OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9791 SourceLocation StartLoc,
9792 SourceLocation LParenLoc,
9793 SourceLocation EndLoc) {
9794 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009795 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009796 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009797 SourceLocation ELoc;
9798 SourceRange ERange;
9799 Expr *SimpleRefExpr = RefExpr;
9800 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009801 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009802 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009803 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009804 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009805 ValueDecl *D = Res.first;
9806 if (!D)
9807 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009808
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009809 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009810 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9811 // in a Construct]
9812 // Variables with the predetermined data-sharing attributes may not be
9813 // listed in data-sharing attributes clauses, except for the cases
9814 // listed below. For these exceptions only, listing a predetermined
9815 // variable in a data-sharing attribute clause is allowed and overrides
9816 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009817 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009818 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9819 DVar.RefExpr) {
9820 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9821 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009822 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009823 continue;
9824 }
9825
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009826 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009827 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009828 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009829 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009830 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9831 ? RefExpr->IgnoreParens()
9832 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009833 }
9834
Alexey Bataeved09d242014-05-28 05:53:51 +00009835 if (Vars.empty())
9836 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009837
9838 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9839}
9840
Alexey Bataevc5e02582014-06-16 07:08:35 +00009841namespace {
9842class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9843 DSAStackTy *Stack;
9844
9845public:
9846 bool VisitDeclRefExpr(DeclRefExpr *E) {
9847 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009848 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009849 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9850 return false;
9851 if (DVar.CKind != OMPC_unknown)
9852 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009853 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9854 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009855 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009856 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009857 return true;
9858 return false;
9859 }
9860 return false;
9861 }
9862 bool VisitStmt(Stmt *S) {
9863 for (auto Child : S->children()) {
9864 if (Child && Visit(Child))
9865 return true;
9866 }
9867 return false;
9868 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009869 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009870};
Alexey Bataev23b69422014-06-18 07:08:49 +00009871} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009872
Alexey Bataev60da77e2016-02-29 05:54:20 +00009873namespace {
9874// Transform MemberExpression for specified FieldDecl of current class to
9875// DeclRefExpr to specified OMPCapturedExprDecl.
9876class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9877 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9878 ValueDecl *Field;
9879 DeclRefExpr *CapturedExpr;
9880
9881public:
9882 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9883 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9884
9885 ExprResult TransformMemberExpr(MemberExpr *E) {
9886 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9887 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009888 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009889 return CapturedExpr;
9890 }
9891 return BaseTransform::TransformMemberExpr(E);
9892 }
9893 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9894};
9895} // namespace
9896
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009897template <typename T>
9898static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9899 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9900 for (auto &Set : Lookups) {
9901 for (auto *D : Set) {
9902 if (auto Res = Gen(cast<ValueDecl>(D)))
9903 return Res;
9904 }
9905 }
9906 return T();
9907}
9908
9909static ExprResult
9910buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9911 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9912 const DeclarationNameInfo &ReductionId, QualType Ty,
9913 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9914 if (ReductionIdScopeSpec.isInvalid())
9915 return ExprError();
9916 SmallVector<UnresolvedSet<8>, 4> Lookups;
9917 if (S) {
9918 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9919 Lookup.suppressDiagnostics();
9920 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9921 auto *D = Lookup.getRepresentativeDecl();
9922 do {
9923 S = S->getParent();
9924 } while (S && !S->isDeclScope(D));
9925 if (S)
9926 S = S->getParent();
9927 Lookups.push_back(UnresolvedSet<8>());
9928 Lookups.back().append(Lookup.begin(), Lookup.end());
9929 Lookup.clear();
9930 }
9931 } else if (auto *ULE =
9932 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9933 Lookups.push_back(UnresolvedSet<8>());
9934 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009935 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009936 if (D == PrevD)
9937 Lookups.push_back(UnresolvedSet<8>());
9938 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9939 Lookups.back().addDecl(DRD);
9940 PrevD = D;
9941 }
9942 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009943 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9944 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009945 Ty->containsUnexpandedParameterPack() ||
9946 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9947 return !D->isInvalidDecl() &&
9948 (D->getType()->isDependentType() ||
9949 D->getType()->isInstantiationDependentType() ||
9950 D->getType()->containsUnexpandedParameterPack());
9951 })) {
9952 UnresolvedSet<8> ResSet;
9953 for (auto &Set : Lookups) {
9954 ResSet.append(Set.begin(), Set.end());
9955 // The last item marks the end of all declarations at the specified scope.
9956 ResSet.addDecl(Set[Set.size() - 1]);
9957 }
9958 return UnresolvedLookupExpr::Create(
9959 SemaRef.Context, /*NamingClass=*/nullptr,
9960 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9961 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9962 }
9963 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9964 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9965 if (!D->isInvalidDecl() &&
9966 SemaRef.Context.hasSameType(D->getType(), Ty))
9967 return D;
9968 return nullptr;
9969 }))
9970 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9971 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9972 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9973 if (!D->isInvalidDecl() &&
9974 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9975 !Ty.isMoreQualifiedThan(D->getType()))
9976 return D;
9977 return nullptr;
9978 })) {
9979 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9980 /*DetectVirtual=*/false);
9981 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9982 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9983 VD->getType().getUnqualifiedType()))) {
9984 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9985 /*DiagID=*/0) !=
9986 Sema::AR_inaccessible) {
9987 SemaRef.BuildBasePathArray(Paths, BasePath);
9988 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9989 }
9990 }
9991 }
9992 }
9993 if (ReductionIdScopeSpec.isSet()) {
9994 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9995 return ExprError();
9996 }
9997 return ExprEmpty();
9998}
9999
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010000namespace {
10001/// Data for the reduction-based clauses.
10002struct ReductionData {
10003 /// List of original reduction items.
10004 SmallVector<Expr *, 8> Vars;
10005 /// List of private copies of the reduction items.
10006 SmallVector<Expr *, 8> Privates;
10007 /// LHS expressions for the reduction_op expressions.
10008 SmallVector<Expr *, 8> LHSs;
10009 /// RHS expressions for the reduction_op expressions.
10010 SmallVector<Expr *, 8> RHSs;
10011 /// Reduction operation expression.
10012 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010013 /// Taskgroup descriptors for the corresponding reduction items in
10014 /// in_reduction clauses.
10015 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010016 /// List of captures for clause.
10017 SmallVector<Decl *, 4> ExprCaptures;
10018 /// List of postupdate expressions.
10019 SmallVector<Expr *, 4> ExprPostUpdates;
10020 ReductionData() = delete;
10021 /// Reserves required memory for the reduction data.
10022 ReductionData(unsigned Size) {
10023 Vars.reserve(Size);
10024 Privates.reserve(Size);
10025 LHSs.reserve(Size);
10026 RHSs.reserve(Size);
10027 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010028 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010029 ExprCaptures.reserve(Size);
10030 ExprPostUpdates.reserve(Size);
10031 }
10032 /// Stores reduction item and reduction operation only (required for dependent
10033 /// reduction item).
10034 void push(Expr *Item, Expr *ReductionOp) {
10035 Vars.emplace_back(Item);
10036 Privates.emplace_back(nullptr);
10037 LHSs.emplace_back(nullptr);
10038 RHSs.emplace_back(nullptr);
10039 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010040 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010041 }
10042 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010043 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10044 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010045 Vars.emplace_back(Item);
10046 Privates.emplace_back(Private);
10047 LHSs.emplace_back(LHS);
10048 RHSs.emplace_back(RHS);
10049 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010050 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010051 }
10052};
10053} // namespace
10054
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010055static bool CheckOMPArraySectionConstantForReduction(
10056 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10057 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10058 const Expr *Length = OASE->getLength();
10059 if (Length == nullptr) {
10060 // For array sections of the form [1:] or [:], we would need to analyze
10061 // the lower bound...
10062 if (OASE->getColonLoc().isValid())
10063 return false;
10064
10065 // This is an array subscript which has implicit length 1!
10066 SingleElement = true;
10067 ArraySizes.push_back(llvm::APSInt::get(1));
10068 } else {
10069 llvm::APSInt ConstantLengthValue;
10070 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10071 return false;
10072
10073 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10074 ArraySizes.push_back(ConstantLengthValue);
10075 }
10076
10077 // Get the base of this array section and walk up from there.
10078 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10079
10080 // We require length = 1 for all array sections except the right-most to
10081 // guarantee that the memory region is contiguous and has no holes in it.
10082 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10083 Length = TempOASE->getLength();
10084 if (Length == nullptr) {
10085 // For array sections of the form [1:] or [:], we would need to analyze
10086 // the lower bound...
10087 if (OASE->getColonLoc().isValid())
10088 return false;
10089
10090 // This is an array subscript which has implicit length 1!
10091 ArraySizes.push_back(llvm::APSInt::get(1));
10092 } else {
10093 llvm::APSInt ConstantLengthValue;
10094 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10095 ConstantLengthValue.getSExtValue() != 1)
10096 return false;
10097
10098 ArraySizes.push_back(ConstantLengthValue);
10099 }
10100 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10101 }
10102
10103 // If we have a single element, we don't need to add the implicit lengths.
10104 if (!SingleElement) {
10105 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10106 // Has implicit length 1!
10107 ArraySizes.push_back(llvm::APSInt::get(1));
10108 Base = TempASE->getBase()->IgnoreParenImpCasts();
10109 }
10110 }
10111
10112 // This array section can be privatized as a single value or as a constant
10113 // sized array.
10114 return true;
10115}
10116
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010117static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010118 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10119 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10120 SourceLocation ColonLoc, SourceLocation EndLoc,
10121 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010122 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010123 auto DN = ReductionId.getName();
10124 auto OOK = DN.getCXXOverloadedOperator();
10125 BinaryOperatorKind BOK = BO_Comma;
10126
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010127 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010128 // OpenMP [2.14.3.6, reduction clause]
10129 // C
10130 // reduction-identifier is either an identifier or one of the following
10131 // operators: +, -, *, &, |, ^, && and ||
10132 // C++
10133 // reduction-identifier is either an id-expression or one of the following
10134 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010135 switch (OOK) {
10136 case OO_Plus:
10137 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010138 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010139 break;
10140 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010141 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010142 break;
10143 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010144 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010145 break;
10146 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010147 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010148 break;
10149 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010150 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010151 break;
10152 case OO_AmpAmp:
10153 BOK = BO_LAnd;
10154 break;
10155 case OO_PipePipe:
10156 BOK = BO_LOr;
10157 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010158 case OO_New:
10159 case OO_Delete:
10160 case OO_Array_New:
10161 case OO_Array_Delete:
10162 case OO_Slash:
10163 case OO_Percent:
10164 case OO_Tilde:
10165 case OO_Exclaim:
10166 case OO_Equal:
10167 case OO_Less:
10168 case OO_Greater:
10169 case OO_LessEqual:
10170 case OO_GreaterEqual:
10171 case OO_PlusEqual:
10172 case OO_MinusEqual:
10173 case OO_StarEqual:
10174 case OO_SlashEqual:
10175 case OO_PercentEqual:
10176 case OO_CaretEqual:
10177 case OO_AmpEqual:
10178 case OO_PipeEqual:
10179 case OO_LessLess:
10180 case OO_GreaterGreater:
10181 case OO_LessLessEqual:
10182 case OO_GreaterGreaterEqual:
10183 case OO_EqualEqual:
10184 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010185 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010186 case OO_PlusPlus:
10187 case OO_MinusMinus:
10188 case OO_Comma:
10189 case OO_ArrowStar:
10190 case OO_Arrow:
10191 case OO_Call:
10192 case OO_Subscript:
10193 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010194 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010195 case NUM_OVERLOADED_OPERATORS:
10196 llvm_unreachable("Unexpected reduction identifier");
10197 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010198 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010199 if (II->isStr("max"))
10200 BOK = BO_GT;
10201 else if (II->isStr("min"))
10202 BOK = BO_LT;
10203 }
10204 break;
10205 }
10206 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010207 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010208 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010209 else
10210 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010211 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010212
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010213 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10214 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010215 for (auto RefExpr : VarList) {
10216 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010217 // OpenMP [2.1, C/C++]
10218 // A list item is a variable or array section, subject to the restrictions
10219 // specified in Section 2.4 on page 42 and in each of the sections
10220 // describing clauses and directives for which a list appears.
10221 // OpenMP [2.14.3.3, Restrictions, p.1]
10222 // A variable that is part of another variable (as an array or
10223 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010224 if (!FirstIter && IR != ER)
10225 ++IR;
10226 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010227 SourceLocation ELoc;
10228 SourceRange ERange;
10229 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010230 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010231 /*AllowArraySection=*/true);
10232 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010233 // Try to find 'declare reduction' corresponding construct before using
10234 // builtin/overloaded operators.
10235 QualType Type = Context.DependentTy;
10236 CXXCastPath BasePath;
10237 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010238 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010239 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010240 Expr *ReductionOp = nullptr;
10241 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010242 (DeclareReductionRef.isUnset() ||
10243 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010244 ReductionOp = DeclareReductionRef.get();
10245 // It will be analyzed later.
10246 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010247 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010248 ValueDecl *D = Res.first;
10249 if (!D)
10250 continue;
10251
Alexey Bataev88202be2017-07-27 13:20:36 +000010252 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010253 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010254 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10255 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10256 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +000010257 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010258 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010259 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10260 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10261 Type = ATy->getElementType();
10262 else
10263 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010264 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010265 } else
10266 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10267 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010268
Alexey Bataevc5e02582014-06-16 07:08:35 +000010269 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10270 // A variable that appears in a private clause must not have an incomplete
10271 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010272 if (S.RequireCompleteType(ELoc, Type,
10273 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010274 continue;
10275 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010276 // A list item that appears in a reduction clause must not be
10277 // const-qualified.
10278 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010279 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010280 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010281 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10282 VarDecl::DeclarationOnly;
10283 S.Diag(D->getLocation(),
10284 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010285 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010286 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010287 continue;
10288 }
10289 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10290 // If a list-item is a reference type then it must bind to the same object
10291 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010292 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010293 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010294 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010295 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010296 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010297 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10298 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010299 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010300 continue;
10301 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010302 }
10303 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010304
Alexey Bataevc5e02582014-06-16 07:08:35 +000010305 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10306 // in a Construct]
10307 // Variables with the predetermined data-sharing attributes may not be
10308 // listed in data-sharing attributes clauses, except for the cases
10309 // listed below. For these exceptions only, listing a predetermined
10310 // variable in a data-sharing attribute clause is allowed and overrides
10311 // the variable's predetermined data-sharing attributes.
10312 // OpenMP [2.14.3.6, Restrictions, p.3]
10313 // Any number of reduction clauses can be specified on the directive,
10314 // but a list item can appear only once in the reduction clauses for that
10315 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010316 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010317 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010318 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010319 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010320 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010321 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010322 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010323 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010324 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010325 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010326 << getOpenMPClauseName(DVar.CKind)
10327 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010328 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010329 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010330 }
10331
10332 // OpenMP [2.14.3.6, Restrictions, p.1]
10333 // A list item that appears in a reduction clause of a worksharing
10334 // construct must be shared in the parallel regions to which any of the
10335 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010336 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010337 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010338 !isOpenMPParallelDirective(CurrDir) &&
10339 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010340 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010341 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010342 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010343 << getOpenMPClauseName(OMPC_reduction)
10344 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010345 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010346 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010347 }
10348 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010349
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010350 // Try to find 'declare reduction' corresponding construct before using
10351 // builtin/overloaded operators.
10352 CXXCastPath BasePath;
10353 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010354 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010355 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10356 if (DeclareReductionRef.isInvalid())
10357 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010358 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010359 (DeclareReductionRef.isUnset() ||
10360 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010361 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010362 continue;
10363 }
10364 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10365 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010366 S.Diag(ReductionId.getLocStart(),
10367 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010368 << Type << ReductionIdRange;
10369 continue;
10370 }
10371
10372 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10373 // The type of a list item that appears in a reduction clause must be valid
10374 // for the reduction-identifier. For a max or min reduction in C, the type
10375 // of the list item must be an allowed arithmetic data type: char, int,
10376 // float, double, or _Bool, possibly modified with long, short, signed, or
10377 // unsigned. For a max or min reduction in C++, the type of the list item
10378 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10379 // double, or bool, possibly modified with long, short, signed, or unsigned.
10380 if (DeclareReductionRef.isUnset()) {
10381 if ((BOK == BO_GT || BOK == BO_LT) &&
10382 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010383 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10384 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010385 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010386 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010387 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10388 VarDecl::DeclarationOnly;
10389 S.Diag(D->getLocation(),
10390 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010391 << D;
10392 }
10393 continue;
10394 }
10395 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010396 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010397 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10398 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010399 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010400 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10401 VarDecl::DeclarationOnly;
10402 S.Diag(D->getLocation(),
10403 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010404 << D;
10405 }
10406 continue;
10407 }
10408 }
10409
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010410 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010411 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010412 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010413 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010414 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010415 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010416
10417 // Try if we can determine constant lengths for all array sections and avoid
10418 // the VLA.
10419 bool ConstantLengthOASE = false;
10420 if (OASE) {
10421 bool SingleElement;
10422 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10423 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10424 Context, OASE, SingleElement, ArraySizes);
10425
10426 // If we don't have a single element, we must emit a constant array type.
10427 if (ConstantLengthOASE && !SingleElement) {
10428 for (auto &Size : ArraySizes) {
10429 PrivateTy = Context.getConstantArrayType(
10430 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10431 }
10432 }
10433 }
10434
10435 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010436 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010437 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010438 if (!Context.getTargetInfo().isVLASupported() &&
10439 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10440 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10441 S.Diag(ELoc, diag::note_vla_unsupported);
10442 continue;
10443 }
David Majnemer9d168222016-08-05 17:44:54 +000010444 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010445 // Create pseudo array type for private copy. The size for this array will
10446 // be generated during codegen.
10447 // For array subscripts or single variables Private Ty is the same as Type
10448 // (type of the variable or single array element).
10449 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010450 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010451 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010452 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010453 } else if (!ASE && !OASE &&
10454 Context.getAsArrayType(D->getType().getNonReferenceType()))
10455 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010456 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010457 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010458 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010459 // Add initializer for private variable.
10460 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010461 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10462 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010463 if (DeclareReductionRef.isUsable()) {
10464 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10465 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10466 if (DRD->getInitializer()) {
10467 Init = DRDRef;
10468 RHSVD->setInit(DRDRef);
10469 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010470 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010471 } else {
10472 switch (BOK) {
10473 case BO_Add:
10474 case BO_Xor:
10475 case BO_Or:
10476 case BO_LOr:
10477 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10478 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010479 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010480 break;
10481 case BO_Mul:
10482 case BO_LAnd:
10483 if (Type->isScalarType() || Type->isAnyComplexType()) {
10484 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010485 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010486 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010487 break;
10488 case BO_And: {
10489 // '&' reduction op - initializer is '~0'.
10490 QualType OrigType = Type;
10491 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10492 Type = ComplexTy->getElementType();
10493 if (Type->isRealFloatingType()) {
10494 llvm::APFloat InitValue =
10495 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10496 /*isIEEE=*/true);
10497 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10498 Type, ELoc);
10499 } else if (Type->isScalarType()) {
10500 auto Size = Context.getTypeSize(Type);
10501 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10502 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10503 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10504 }
10505 if (Init && OrigType->isAnyComplexType()) {
10506 // Init = 0xFFFF + 0xFFFFi;
10507 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010508 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010509 }
10510 Type = OrigType;
10511 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010512 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010513 case BO_LT:
10514 case BO_GT: {
10515 // 'min' reduction op - initializer is 'Largest representable number in
10516 // the reduction list item type'.
10517 // 'max' reduction op - initializer is 'Least representable number in
10518 // the reduction list item type'.
10519 if (Type->isIntegerType() || Type->isPointerType()) {
10520 bool IsSigned = Type->hasSignedIntegerRepresentation();
10521 auto Size = Context.getTypeSize(Type);
10522 QualType IntTy =
10523 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10524 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010525 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10526 : llvm::APInt::getMinValue(Size)
10527 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10528 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010529 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10530 if (Type->isPointerType()) {
10531 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010532 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010533 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010534 if (CastExpr.isInvalid())
10535 continue;
10536 Init = CastExpr.get();
10537 }
10538 } else if (Type->isRealFloatingType()) {
10539 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10540 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10541 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10542 Type, ELoc);
10543 }
10544 break;
10545 }
10546 case BO_PtrMemD:
10547 case BO_PtrMemI:
10548 case BO_MulAssign:
10549 case BO_Div:
10550 case BO_Rem:
10551 case BO_Sub:
10552 case BO_Shl:
10553 case BO_Shr:
10554 case BO_LE:
10555 case BO_GE:
10556 case BO_EQ:
10557 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000010558 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010559 case BO_AndAssign:
10560 case BO_XorAssign:
10561 case BO_OrAssign:
10562 case BO_Assign:
10563 case BO_AddAssign:
10564 case BO_SubAssign:
10565 case BO_DivAssign:
10566 case BO_RemAssign:
10567 case BO_ShlAssign:
10568 case BO_ShrAssign:
10569 case BO_Comma:
10570 llvm_unreachable("Unexpected reduction operation");
10571 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010572 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010573 if (Init && DeclareReductionRef.isUnset())
10574 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10575 else if (!Init)
10576 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010577 if (RHSVD->isInvalidDecl())
10578 continue;
10579 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010580 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10581 << Type << ReductionIdRange;
10582 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10583 VarDecl::DeclarationOnly;
10584 S.Diag(D->getLocation(),
10585 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010586 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010587 continue;
10588 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010589 // Store initializer for single element in private copy. Will be used during
10590 // codegen.
10591 PrivateVD->setInit(RHSVD->getInit());
10592 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010593 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010594 ExprResult ReductionOp;
10595 if (DeclareReductionRef.isUsable()) {
10596 QualType RedTy = DeclareReductionRef.get()->getType();
10597 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010598 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10599 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010600 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010601 LHS = S.DefaultLvalueConversion(LHS.get());
10602 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010603 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10604 CK_UncheckedDerivedToBase, LHS.get(),
10605 &BasePath, LHS.get()->getValueKind());
10606 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10607 CK_UncheckedDerivedToBase, RHS.get(),
10608 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010609 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010610 FunctionProtoType::ExtProtoInfo EPI;
10611 QualType Params[] = {PtrRedTy, PtrRedTy};
10612 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10613 auto *OVE = new (Context) OpaqueValueExpr(
10614 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010615 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010616 Expr *Args[] = {LHS.get(), RHS.get()};
10617 ReductionOp = new (Context)
10618 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10619 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010620 ReductionOp = S.BuildBinOp(
10621 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010622 if (ReductionOp.isUsable()) {
10623 if (BOK != BO_LT && BOK != BO_GT) {
10624 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010625 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10626 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010627 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010628 auto *ConditionalOp = new (Context)
10629 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10630 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010631 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010632 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10633 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010634 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010635 if (ReductionOp.isUsable())
10636 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010637 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010638 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010639 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010640 }
10641
Alexey Bataevfa312f32017-07-21 18:48:21 +000010642 // OpenMP [2.15.4.6, Restrictions, p.2]
10643 // A list item that appears in an in_reduction clause of a task construct
10644 // must appear in a task_reduction clause of a construct associated with a
10645 // taskgroup region that includes the participating task in its taskgroup
10646 // set. The construct associated with the innermost region that meets this
10647 // condition must specify the same reduction-identifier as the in_reduction
10648 // clause.
10649 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010650 SourceRange ParentSR;
10651 BinaryOperatorKind ParentBOK;
10652 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010653 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010654 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010655 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10656 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010657 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010658 Stack->getTopMostTaskgroupReductionData(
10659 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010660 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10661 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10662 if (!IsParentBOK && !IsParentReductionOp) {
10663 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10664 continue;
10665 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010666 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10667 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10668 IsParentReductionOp) {
10669 bool EmitError = true;
10670 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10671 llvm::FoldingSetNodeID RedId, ParentRedId;
10672 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10673 DeclareReductionRef.get()->Profile(RedId, Context,
10674 /*Canonical=*/true);
10675 EmitError = RedId != ParentRedId;
10676 }
10677 if (EmitError) {
10678 S.Diag(ReductionId.getLocStart(),
10679 diag::err_omp_reduction_identifier_mismatch)
10680 << ReductionIdRange << RefExpr->getSourceRange();
10681 S.Diag(ParentSR.getBegin(),
10682 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010683 << ParentSR
10684 << (IsParentBOK ? ParentBOKDSA.RefExpr
10685 : ParentReductionOpDSA.RefExpr)
10686 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010687 continue;
10688 }
10689 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010690 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10691 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010692 }
10693
Alexey Bataev60da77e2016-02-29 05:54:20 +000010694 DeclRefExpr *Ref = nullptr;
10695 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010696 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010697 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010698 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010699 VarsExpr =
10700 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10701 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010702 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010703 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010704 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010705 if (!S.IsOpenMPCapturedDecl(D)) {
10706 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010707 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010708 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010709 if (!RefRes.isUsable())
10710 continue;
10711 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010712 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10713 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010714 if (!PostUpdateRes.isUsable())
10715 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010716 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10717 Stack->getCurrentDirective() == OMPD_taskgroup) {
10718 S.Diag(RefExpr->getExprLoc(),
10719 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010720 << RefExpr->getSourceRange();
10721 continue;
10722 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010723 RD.ExprPostUpdates.emplace_back(
10724 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010725 }
10726 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010727 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010728 // All reduction items are still marked as reduction (to do not increase
10729 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010730 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010731 if (CurrDir == OMPD_taskgroup) {
10732 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010733 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10734 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010735 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010736 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010737 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010738 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10739 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010740 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010741 return RD.Vars.empty();
10742}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010743
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010744OMPClause *Sema::ActOnOpenMPReductionClause(
10745 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10746 SourceLocation ColonLoc, SourceLocation EndLoc,
10747 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10748 ArrayRef<Expr *> UnresolvedReductions) {
10749 ReductionData RD(VarList.size());
10750
Alexey Bataev169d96a2017-07-18 20:17:46 +000010751 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10752 StartLoc, LParenLoc, ColonLoc, EndLoc,
10753 ReductionIdScopeSpec, ReductionId,
10754 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010755 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010756
Alexey Bataevc5e02582014-06-16 07:08:35 +000010757 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010758 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10759 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10760 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10761 buildPreInits(Context, RD.ExprCaptures),
10762 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010763}
10764
Alexey Bataev169d96a2017-07-18 20:17:46 +000010765OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10766 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10767 SourceLocation ColonLoc, SourceLocation EndLoc,
10768 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10769 ArrayRef<Expr *> UnresolvedReductions) {
10770 ReductionData RD(VarList.size());
10771
10772 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10773 VarList, StartLoc, LParenLoc, ColonLoc,
10774 EndLoc, ReductionIdScopeSpec, ReductionId,
10775 UnresolvedReductions, RD))
10776 return nullptr;
10777
10778 return OMPTaskReductionClause::Create(
10779 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10780 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10781 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10782 buildPreInits(Context, RD.ExprCaptures),
10783 buildPostUpdate(*this, RD.ExprPostUpdates));
10784}
10785
Alexey Bataevfa312f32017-07-21 18:48:21 +000010786OMPClause *Sema::ActOnOpenMPInReductionClause(
10787 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10788 SourceLocation ColonLoc, SourceLocation EndLoc,
10789 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10790 ArrayRef<Expr *> UnresolvedReductions) {
10791 ReductionData RD(VarList.size());
10792
10793 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10794 StartLoc, LParenLoc, ColonLoc, EndLoc,
10795 ReductionIdScopeSpec, ReductionId,
10796 UnresolvedReductions, RD))
10797 return nullptr;
10798
10799 return OMPInReductionClause::Create(
10800 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10801 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010802 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010803 buildPreInits(Context, RD.ExprCaptures),
10804 buildPostUpdate(*this, RD.ExprPostUpdates));
10805}
10806
Alexey Bataevecba70f2016-04-12 11:02:11 +000010807bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10808 SourceLocation LinLoc) {
10809 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10810 LinKind == OMPC_LINEAR_unknown) {
10811 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10812 return true;
10813 }
10814 return false;
10815}
10816
10817bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10818 OpenMPLinearClauseKind LinKind,
10819 QualType Type) {
10820 auto *VD = dyn_cast_or_null<VarDecl>(D);
10821 // A variable must not have an incomplete type or a reference type.
10822 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10823 return true;
10824 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10825 !Type->isReferenceType()) {
10826 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10827 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10828 return true;
10829 }
10830 Type = Type.getNonReferenceType();
10831
10832 // A list item must not be const-qualified.
10833 if (Type.isConstant(Context)) {
10834 Diag(ELoc, diag::err_omp_const_variable)
10835 << getOpenMPClauseName(OMPC_linear);
10836 if (D) {
10837 bool IsDecl =
10838 !VD ||
10839 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10840 Diag(D->getLocation(),
10841 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10842 << D;
10843 }
10844 return true;
10845 }
10846
10847 // A list item must be of integral or pointer type.
10848 Type = Type.getUnqualifiedType().getCanonicalType();
10849 const auto *Ty = Type.getTypePtrOrNull();
10850 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10851 !Ty->isPointerType())) {
10852 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10853 if (D) {
10854 bool IsDecl =
10855 !VD ||
10856 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10857 Diag(D->getLocation(),
10858 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10859 << D;
10860 }
10861 return true;
10862 }
10863 return false;
10864}
10865
Alexey Bataev182227b2015-08-20 10:54:39 +000010866OMPClause *Sema::ActOnOpenMPLinearClause(
10867 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10868 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10869 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010870 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010871 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010872 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010873 SmallVector<Decl *, 4> ExprCaptures;
10874 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010875 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010876 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010877 for (auto &RefExpr : VarList) {
10878 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010879 SourceLocation ELoc;
10880 SourceRange ERange;
10881 Expr *SimpleRefExpr = RefExpr;
10882 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10883 /*AllowArraySection=*/false);
10884 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010885 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010886 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010887 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010888 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010889 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010890 ValueDecl *D = Res.first;
10891 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010892 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010893
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010894 QualType Type = D->getType();
10895 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010896
10897 // OpenMP [2.14.3.7, linear clause]
10898 // A list-item cannot appear in more than one linear clause.
10899 // A list-item that appears in a linear clause cannot appear in any
10900 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010901 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010902 if (DVar.RefExpr) {
10903 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10904 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010905 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010906 continue;
10907 }
10908
Alexey Bataevecba70f2016-04-12 11:02:11 +000010909 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010910 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010911 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010912
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010913 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010914 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10915 D->hasAttrs() ? &D->getAttrs() : nullptr);
10916 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010917 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010918 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010919 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010920 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010921 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010922 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10923 if (!IsOpenMPCapturedDecl(D)) {
10924 ExprCaptures.push_back(Ref->getDecl());
10925 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10926 ExprResult RefRes = DefaultLvalueConversion(Ref);
10927 if (!RefRes.isUsable())
10928 continue;
10929 ExprResult PostUpdateRes =
10930 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10931 SimpleRefExpr, RefRes.get());
10932 if (!PostUpdateRes.isUsable())
10933 continue;
10934 ExprPostUpdates.push_back(
10935 IgnoredValueConversions(PostUpdateRes.get()).get());
10936 }
10937 }
10938 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010939 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010940 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010941 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010942 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010943 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010944 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010945 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10946
10947 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010948 Vars.push_back((VD || CurContext->isDependentContext())
10949 ? RefExpr->IgnoreParens()
10950 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010951 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010952 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010953 }
10954
10955 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010956 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010957
10958 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010959 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010960 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10961 !Step->isInstantiationDependent() &&
10962 !Step->containsUnexpandedParameterPack()) {
10963 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010964 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010965 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010966 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010967 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010968
Alexander Musman3276a272015-03-21 10:12:56 +000010969 // Build var to save the step value.
10970 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010971 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010972 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010973 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010974 ExprResult CalcStep =
10975 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010976 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010977
Alexander Musman8dba6642014-04-22 13:09:42 +000010978 // Warn about zero linear step (it would be probably better specified as
10979 // making corresponding variables 'const').
10980 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010981 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10982 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010983 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10984 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010985 if (!IsConstant && CalcStep.isUsable()) {
10986 // Calculate the step beforehand instead of doing this on each iteration.
10987 // (This is not used if the number of iterations may be kfold-ed).
10988 CalcStepExpr = CalcStep.get();
10989 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010990 }
10991
Alexey Bataev182227b2015-08-20 10:54:39 +000010992 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10993 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010994 StepExpr, CalcStepExpr,
10995 buildPreInits(Context, ExprCaptures),
10996 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010997}
10998
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010999static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11000 Expr *NumIterations, Sema &SemaRef,
11001 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011002 // Walk the vars and build update/final expressions for the CodeGen.
11003 SmallVector<Expr *, 8> Updates;
11004 SmallVector<Expr *, 8> Finals;
11005 Expr *Step = Clause.getStep();
11006 Expr *CalcStep = Clause.getCalcStep();
11007 // OpenMP [2.14.3.7, linear clause]
11008 // If linear-step is not specified it is assumed to be 1.
11009 if (Step == nullptr)
11010 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011011 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000011012 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011013 }
Alexander Musman3276a272015-03-21 10:12:56 +000011014 bool HasErrors = false;
11015 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011016 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011017 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000011018 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011019 SourceLocation ELoc;
11020 SourceRange ERange;
11021 Expr *SimpleRefExpr = RefExpr;
11022 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
11023 /*AllowArraySection=*/false);
11024 ValueDecl *D = Res.first;
11025 if (Res.second || !D) {
11026 Updates.push_back(nullptr);
11027 Finals.push_back(nullptr);
11028 HasErrors = true;
11029 continue;
11030 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011031 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011032 // OpenMP [2.15.11, distribute simd Construct]
11033 // A list item may not appear in a linear clause, unless it is the loop
11034 // iteration variable.
11035 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11036 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11037 SemaRef.Diag(ELoc,
11038 diag::err_omp_linear_distribute_var_non_loop_iteration);
11039 Updates.push_back(nullptr);
11040 Finals.push_back(nullptr);
11041 HasErrors = true;
11042 continue;
11043 }
Alexander Musman3276a272015-03-21 10:12:56 +000011044 Expr *InitExpr = *CurInit;
11045
11046 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011047 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011048 Expr *CapturedRef;
11049 if (LinKind == OMPC_LINEAR_uval)
11050 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11051 else
11052 CapturedRef =
11053 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11054 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11055 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011056
11057 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011058 ExprResult Update;
11059 if (!Info.first) {
11060 Update =
11061 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11062 InitExpr, IV, Step, /* Subtract */ false);
11063 } else
11064 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011065 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11066 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011067
11068 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011069 ExprResult Final;
11070 if (!Info.first) {
11071 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11072 InitExpr, NumIterations, Step,
11073 /* Subtract */ false);
11074 } else
11075 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011076 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11077 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011078
Alexander Musman3276a272015-03-21 10:12:56 +000011079 if (!Update.isUsable() || !Final.isUsable()) {
11080 Updates.push_back(nullptr);
11081 Finals.push_back(nullptr);
11082 HasErrors = true;
11083 } else {
11084 Updates.push_back(Update.get());
11085 Finals.push_back(Final.get());
11086 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011087 ++CurInit;
11088 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011089 }
11090 Clause.setUpdates(Updates);
11091 Clause.setFinals(Finals);
11092 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011093}
11094
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011095OMPClause *Sema::ActOnOpenMPAlignedClause(
11096 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11097 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11098
11099 SmallVector<Expr *, 8> Vars;
11100 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011101 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11102 SourceLocation ELoc;
11103 SourceRange ERange;
11104 Expr *SimpleRefExpr = RefExpr;
11105 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11106 /*AllowArraySection=*/false);
11107 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011108 // It will be analyzed later.
11109 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011110 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011111 ValueDecl *D = Res.first;
11112 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011113 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011114
Alexey Bataev1efd1662016-03-29 10:59:56 +000011115 QualType QType = D->getType();
11116 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011117
11118 // OpenMP [2.8.1, simd construct, Restrictions]
11119 // The type of list items appearing in the aligned clause must be
11120 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011121 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011122 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011123 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011124 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011125 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011126 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011127 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011128 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011129 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011130 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011131 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011132 continue;
11133 }
11134
11135 // OpenMP [2.8.1, simd construct, Restrictions]
11136 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000011137 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011138 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011139 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11140 << getOpenMPClauseName(OMPC_aligned);
11141 continue;
11142 }
11143
Alexey Bataev1efd1662016-03-29 10:59:56 +000011144 DeclRefExpr *Ref = nullptr;
11145 if (!VD && IsOpenMPCapturedDecl(D))
11146 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11147 Vars.push_back(DefaultFunctionArrayConversion(
11148 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11149 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011150 }
11151
11152 // OpenMP [2.8.1, simd construct, Description]
11153 // The parameter of the aligned clause, alignment, must be a constant
11154 // positive integer expression.
11155 // If no optional parameter is specified, implementation-defined default
11156 // alignments for SIMD instructions on the target platforms are assumed.
11157 if (Alignment != nullptr) {
11158 ExprResult AlignResult =
11159 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11160 if (AlignResult.isInvalid())
11161 return nullptr;
11162 Alignment = AlignResult.get();
11163 }
11164 if (Vars.empty())
11165 return nullptr;
11166
11167 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11168 EndLoc, Vars, Alignment);
11169}
11170
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011171OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11172 SourceLocation StartLoc,
11173 SourceLocation LParenLoc,
11174 SourceLocation EndLoc) {
11175 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011176 SmallVector<Expr *, 8> SrcExprs;
11177 SmallVector<Expr *, 8> DstExprs;
11178 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000011179 for (auto &RefExpr : VarList) {
11180 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11181 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011182 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011183 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011184 SrcExprs.push_back(nullptr);
11185 DstExprs.push_back(nullptr);
11186 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011187 continue;
11188 }
11189
Alexey Bataeved09d242014-05-28 05:53:51 +000011190 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011191 // OpenMP [2.1, C/C++]
11192 // A list item is a variable name.
11193 // OpenMP [2.14.4.1, Restrictions, p.1]
11194 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000011195 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011196 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011197 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11198 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011199 continue;
11200 }
11201
11202 Decl *D = DE->getDecl();
11203 VarDecl *VD = cast<VarDecl>(D);
11204
11205 QualType Type = VD->getType();
11206 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11207 // It will be analyzed later.
11208 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011209 SrcExprs.push_back(nullptr);
11210 DstExprs.push_back(nullptr);
11211 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011212 continue;
11213 }
11214
11215 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11216 // A list item that appears in a copyin clause must be threadprivate.
11217 if (!DSAStack->isThreadPrivate(VD)) {
11218 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011219 << getOpenMPClauseName(OMPC_copyin)
11220 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011221 continue;
11222 }
11223
11224 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11225 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011226 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011227 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011228 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011229 auto *SrcVD =
11230 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11231 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000011232 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011233 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11234 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011235 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11236 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011237 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011238 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011239 // For arrays generate assignment operation for single element and replace
11240 // it by the original array element in CodeGen.
11241 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11242 PseudoDstExpr, PseudoSrcExpr);
11243 if (AssignmentOp.isInvalid())
11244 continue;
11245 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11246 /*DiscardedValue=*/true);
11247 if (AssignmentOp.isInvalid())
11248 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011249
11250 DSAStack->addDSA(VD, DE, OMPC_copyin);
11251 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011252 SrcExprs.push_back(PseudoSrcExpr);
11253 DstExprs.push_back(PseudoDstExpr);
11254 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011255 }
11256
Alexey Bataeved09d242014-05-28 05:53:51 +000011257 if (Vars.empty())
11258 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011259
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011260 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11261 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011262}
11263
Alexey Bataevbae9a792014-06-27 10:37:06 +000011264OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11265 SourceLocation StartLoc,
11266 SourceLocation LParenLoc,
11267 SourceLocation EndLoc) {
11268 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011269 SmallVector<Expr *, 8> SrcExprs;
11270 SmallVector<Expr *, 8> DstExprs;
11271 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011272 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011273 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11274 SourceLocation ELoc;
11275 SourceRange ERange;
11276 Expr *SimpleRefExpr = RefExpr;
11277 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11278 /*AllowArraySection=*/false);
11279 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011280 // It will be analyzed later.
11281 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011282 SrcExprs.push_back(nullptr);
11283 DstExprs.push_back(nullptr);
11284 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011285 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011286 ValueDecl *D = Res.first;
11287 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011288 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011289
Alexey Bataeve122da12016-03-17 10:50:17 +000011290 QualType Type = D->getType();
11291 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011292
11293 // OpenMP [2.14.4.2, Restrictions, p.2]
11294 // A list item that appears in a copyprivate clause may not appear in a
11295 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011296 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11297 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011298 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11299 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011300 Diag(ELoc, diag::err_omp_wrong_dsa)
11301 << getOpenMPClauseName(DVar.CKind)
11302 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011303 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011304 continue;
11305 }
11306
11307 // OpenMP [2.11.4.2, Restrictions, p.1]
11308 // All list items that appear in a copyprivate clause must be either
11309 // threadprivate or private in the enclosing context.
11310 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011311 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011312 if (DVar.CKind == OMPC_shared) {
11313 Diag(ELoc, diag::err_omp_required_access)
11314 << getOpenMPClauseName(OMPC_copyprivate)
11315 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011316 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011317 continue;
11318 }
11319 }
11320 }
11321
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011322 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011323 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011324 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011325 << getOpenMPClauseName(OMPC_copyprivate) << Type
11326 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011327 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011328 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011329 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011330 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011331 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011332 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011333 continue;
11334 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011335
Alexey Bataevbae9a792014-06-27 10:37:06 +000011336 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11337 // A variable of class type (or array thereof) that appears in a
11338 // copyin clause requires an accessible, unambiguous copy assignment
11339 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011340 Type = Context.getBaseElementType(Type.getNonReferenceType())
11341 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011342 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011343 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11344 D->hasAttrs() ? &D->getAttrs() : nullptr);
11345 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011346 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011347 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11348 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011349 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011350 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011351 PseudoDstExpr, PseudoSrcExpr);
11352 if (AssignmentOp.isInvalid())
11353 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011354 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011355 /*DiscardedValue=*/true);
11356 if (AssignmentOp.isInvalid())
11357 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011358
11359 // No need to mark vars as copyprivate, they are already threadprivate or
11360 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011361 assert(VD || IsOpenMPCapturedDecl(D));
11362 Vars.push_back(
11363 VD ? RefExpr->IgnoreParens()
11364 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011365 SrcExprs.push_back(PseudoSrcExpr);
11366 DstExprs.push_back(PseudoDstExpr);
11367 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011368 }
11369
11370 if (Vars.empty())
11371 return nullptr;
11372
Alexey Bataeva63048e2015-03-23 06:18:07 +000011373 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11374 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011375}
11376
Alexey Bataev6125da92014-07-21 11:26:11 +000011377OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11378 SourceLocation StartLoc,
11379 SourceLocation LParenLoc,
11380 SourceLocation EndLoc) {
11381 if (VarList.empty())
11382 return nullptr;
11383
11384 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11385}
Alexey Bataevdea47612014-07-23 07:46:59 +000011386
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011387OMPClause *
11388Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11389 SourceLocation DepLoc, SourceLocation ColonLoc,
11390 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11391 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011392 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011393 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011394 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011395 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011396 return nullptr;
11397 }
11398 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011399 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11400 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011401 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011402 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011403 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11404 /*Last=*/OMPC_DEPEND_unknown, Except)
11405 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011406 return nullptr;
11407 }
11408 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011409 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011410 llvm::APSInt DepCounter(/*BitWidth=*/32);
11411 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11412 if (DepKind == OMPC_DEPEND_sink) {
11413 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11414 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11415 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011416 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011417 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011418 for (auto &RefExpr : VarList) {
11419 assert(RefExpr && "NULL expr in OpenMP shared clause.");
11420 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11421 // It will be analyzed later.
11422 Vars.push_back(RefExpr);
11423 continue;
11424 }
11425
11426 SourceLocation ELoc = RefExpr->getExprLoc();
11427 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11428 if (DepKind == OMPC_DEPEND_sink) {
11429 if (DSAStack->getParentOrderedRegionParam() &&
11430 DepCounter >= TotalDepCount) {
11431 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11432 continue;
11433 }
11434 ++DepCounter;
11435 // OpenMP [2.13.9, Summary]
11436 // depend(dependence-type : vec), where dependence-type is:
11437 // 'sink' and where vec is the iteration vector, which has the form:
11438 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11439 // where n is the value specified by the ordered clause in the loop
11440 // directive, xi denotes the loop iteration variable of the i-th nested
11441 // loop associated with the loop directive, and di is a constant
11442 // non-negative integer.
11443 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011444 // It will be analyzed later.
11445 Vars.push_back(RefExpr);
11446 continue;
11447 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011448 SimpleExpr = SimpleExpr->IgnoreImplicit();
11449 OverloadedOperatorKind OOK = OO_None;
11450 SourceLocation OOLoc;
11451 Expr *LHS = SimpleExpr;
11452 Expr *RHS = nullptr;
11453 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11454 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11455 OOLoc = BO->getOperatorLoc();
11456 LHS = BO->getLHS()->IgnoreParenImpCasts();
11457 RHS = BO->getRHS()->IgnoreParenImpCasts();
11458 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11459 OOK = OCE->getOperator();
11460 OOLoc = OCE->getOperatorLoc();
11461 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11462 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11463 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11464 OOK = MCE->getMethodDecl()
11465 ->getNameInfo()
11466 .getName()
11467 .getCXXOverloadedOperator();
11468 OOLoc = MCE->getCallee()->getExprLoc();
11469 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11470 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011471 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011472 SourceLocation ELoc;
11473 SourceRange ERange;
11474 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11475 /*AllowArraySection=*/false);
11476 if (Res.second) {
11477 // It will be analyzed later.
11478 Vars.push_back(RefExpr);
11479 }
11480 ValueDecl *D = Res.first;
11481 if (!D)
11482 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011483
Alexey Bataev17daedf2018-02-15 22:42:57 +000011484 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11485 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11486 continue;
11487 }
11488 if (RHS) {
11489 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11490 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11491 if (RHSRes.isInvalid())
11492 continue;
11493 }
11494 if (!CurContext->isDependentContext() &&
11495 DSAStack->getParentOrderedRegionParam() &&
11496 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11497 ValueDecl *VD =
11498 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
11499 if (VD) {
11500 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11501 << 1 << VD;
11502 } else {
11503 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11504 }
11505 continue;
11506 }
11507 OpsOffs.push_back({RHS, OOK});
11508 } else {
11509 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11510 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11511 (ASE &&
11512 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
11513 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11514 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11515 << RefExpr->getSourceRange();
11516 continue;
11517 }
11518 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11519 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11520 ExprResult Res =
11521 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
11522 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11523 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11524 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11525 << RefExpr->getSourceRange();
11526 continue;
11527 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011528 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011529 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011530 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011531
11532 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11533 TotalDepCount > VarList.size() &&
11534 DSAStack->getParentOrderedRegionParam() &&
11535 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11536 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
11537 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11538 }
11539 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11540 Vars.empty())
11541 return nullptr;
11542
Alexey Bataev8b427062016-05-25 12:36:08 +000011543 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11544 DepKind, DepLoc, ColonLoc, Vars);
Alexey Bataev17daedf2018-02-15 22:42:57 +000011545 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
11546 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000011547 DSAStack->addDoacrossDependClause(C, OpsOffs);
11548 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011549}
Michael Wonge710d542015-08-07 16:16:36 +000011550
11551OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11552 SourceLocation LParenLoc,
11553 SourceLocation EndLoc) {
11554 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011555 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011556
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011557 // OpenMP [2.9.1, Restrictions]
11558 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011559 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11560 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011561 return nullptr;
11562
Alexey Bataev931e19b2017-10-02 16:32:39 +000011563 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011564 OpenMPDirectiveKind CaptureRegion =
11565 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11566 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011567 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev931e19b2017-10-02 16:32:39 +000011568 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11569 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11570 HelperValStmt = buildPreInits(Context, Captures);
11571 }
11572
Alexey Bataev8451efa2018-01-15 19:06:12 +000011573 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11574 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011575}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011576
Kelvin Li0bff7af2015-11-23 05:32:03 +000011577static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000011578 DSAStackTy *Stack, QualType QTy,
11579 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000011580 NamedDecl *ND;
11581 if (QTy->isIncompleteType(&ND)) {
11582 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11583 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011584 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000011585 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
11586 !QTy.isTrivialType(SemaRef.Context))
11587 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011588 return true;
11589}
11590
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011591/// \brief Return true if it can be proven that the provided array expression
11592/// (array section or array subscript) does NOT specify the whole size of the
11593/// array whose base type is \a BaseQTy.
11594static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11595 const Expr *E,
11596 QualType BaseQTy) {
11597 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11598
11599 // If this is an array subscript, it refers to the whole size if the size of
11600 // the dimension is constant and equals 1. Also, an array section assumes the
11601 // format of an array subscript if no colon is used.
11602 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11603 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11604 return ATy->getSize().getSExtValue() != 1;
11605 // Size can't be evaluated statically.
11606 return false;
11607 }
11608
11609 assert(OASE && "Expecting array section if not an array subscript.");
11610 auto *LowerBound = OASE->getLowerBound();
11611 auto *Length = OASE->getLength();
11612
11613 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011614 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011615 if (LowerBound) {
11616 llvm::APSInt ConstLowerBound;
11617 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11618 return false; // Can't get the integer value as a constant.
11619 if (ConstLowerBound.getSExtValue())
11620 return true;
11621 }
11622
11623 // If we don't have a length we covering the whole dimension.
11624 if (!Length)
11625 return false;
11626
11627 // If the base is a pointer, we don't have a way to get the size of the
11628 // pointee.
11629 if (BaseQTy->isPointerType())
11630 return false;
11631
11632 // We can only check if the length is the same as the size of the dimension
11633 // if we have a constant array.
11634 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11635 if (!CATy)
11636 return false;
11637
11638 llvm::APSInt ConstLength;
11639 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11640 return false; // Can't get the integer value as a constant.
11641
11642 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11643}
11644
11645// Return true if it can be proven that the provided array expression (array
11646// section or array subscript) does NOT specify a single element of the array
11647// whose base type is \a BaseQTy.
11648static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011649 const Expr *E,
11650 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011651 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11652
11653 // An array subscript always refer to a single element. Also, an array section
11654 // assumes the format of an array subscript if no colon is used.
11655 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11656 return false;
11657
11658 assert(OASE && "Expecting array section if not an array subscript.");
11659 auto *Length = OASE->getLength();
11660
11661 // If we don't have a length we have to check if the array has unitary size
11662 // for this dimension. Also, we should always expect a length if the base type
11663 // is pointer.
11664 if (!Length) {
11665 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11666 return ATy->getSize().getSExtValue() != 1;
11667 // We cannot assume anything.
11668 return false;
11669 }
11670
11671 // Check if the length evaluates to 1.
11672 llvm::APSInt ConstLength;
11673 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11674 return false; // Can't get the integer value as a constant.
11675
11676 return ConstLength.getSExtValue() != 1;
11677}
11678
Samuel Antao661c0902016-05-26 17:39:58 +000011679// Return the expression of the base of the mappable expression or null if it
11680// cannot be determined and do all the necessary checks to see if the expression
11681// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011682// components of the expression.
11683static Expr *CheckMapClauseExpressionBase(
11684 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011685 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011686 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011687 SourceLocation ELoc = E->getExprLoc();
11688 SourceRange ERange = E->getSourceRange();
11689
11690 // The base of elements of list in a map clause have to be either:
11691 // - a reference to variable or field.
11692 // - a member expression.
11693 // - an array expression.
11694 //
11695 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11696 // reference to 'r'.
11697 //
11698 // If we have:
11699 //
11700 // struct SS {
11701 // Bla S;
11702 // foo() {
11703 // #pragma omp target map (S.Arr[:12]);
11704 // }
11705 // }
11706 //
11707 // We want to retrieve the member expression 'this->S';
11708
11709 Expr *RelevantExpr = nullptr;
11710
Samuel Antao5de996e2016-01-22 20:21:36 +000011711 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11712 // If a list item is an array section, it must specify contiguous storage.
11713 //
11714 // For this restriction it is sufficient that we make sure only references
11715 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011716 // exist except in the rightmost expression (unless they cover the whole
11717 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011718 //
11719 // r.ArrS[3:5].Arr[6:7]
11720 //
11721 // r.ArrS[3:5].x
11722 //
11723 // but these would be valid:
11724 // r.ArrS[3].Arr[6:7]
11725 //
11726 // r.ArrS[3].x
11727
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011728 bool AllowUnitySizeArraySection = true;
11729 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011730
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011731 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011732 E = E->IgnoreParenImpCasts();
11733
11734 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11735 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011736 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011737
11738 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011739
11740 // If we got a reference to a declaration, we should not expect any array
11741 // section before that.
11742 AllowUnitySizeArraySection = false;
11743 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011744
11745 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011746 CurComponents.emplace_back(CurE, CurE->getDecl());
11747 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011748 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11749
11750 if (isa<CXXThisExpr>(BaseE))
11751 // We found a base expression: this->Val.
11752 RelevantExpr = CurE;
11753 else
11754 E = BaseE;
11755
11756 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011757 if (!NoDiagnose) {
11758 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11759 << CurE->getSourceRange();
11760 return nullptr;
11761 }
11762 if (RelevantExpr)
11763 return nullptr;
11764 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011765 }
11766
11767 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11768
11769 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11770 // A bit-field cannot appear in a map clause.
11771 //
11772 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011773 if (!NoDiagnose) {
11774 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11775 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11776 return nullptr;
11777 }
11778 if (RelevantExpr)
11779 return nullptr;
11780 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011781 }
11782
11783 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11784 // If the type of a list item is a reference to a type T then the type
11785 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011786 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011787
11788 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11789 // A list item cannot be a variable that is a member of a structure with
11790 // a union type.
11791 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011792 if (auto *RT = CurType->getAs<RecordType>()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011793 if (RT->isUnionType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011794 if (!NoDiagnose) {
11795 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11796 << CurE->getSourceRange();
11797 return nullptr;
11798 }
11799 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011800 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011801 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011802
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011803 // If we got a member expression, we should not expect any array section
11804 // before that:
11805 //
11806 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11807 // If a list item is an element of a structure, only the rightmost symbol
11808 // of the variable reference can be an array section.
11809 //
11810 AllowUnitySizeArraySection = false;
11811 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011812
11813 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011814 CurComponents.emplace_back(CurE, FD);
11815 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011816 E = CurE->getBase()->IgnoreParenImpCasts();
11817
11818 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011819 if (!NoDiagnose) {
11820 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11821 << 0 << CurE->getSourceRange();
11822 return nullptr;
11823 }
11824 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011825 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011826
11827 // If we got an array subscript that express the whole dimension we
11828 // can have any array expressions before. If it only expressing part of
11829 // the dimension, we can only have unitary-size array expressions.
11830 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11831 E->getType()))
11832 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011833
11834 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011835 CurComponents.emplace_back(CurE, nullptr);
11836 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011837 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011838 E = CurE->getBase()->IgnoreParenImpCasts();
11839
Alexey Bataev27041fa2017-12-05 15:22:49 +000011840 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011841 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11842
Samuel Antao5de996e2016-01-22 20:21:36 +000011843 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11844 // If the type of a list item is a reference to a type T then the type
11845 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011846 if (CurType->isReferenceType())
11847 CurType = CurType->getPointeeType();
11848
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011849 bool IsPointer = CurType->isAnyPointerType();
11850
11851 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011852 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11853 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011854 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011855 }
11856
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011857 bool NotWhole =
11858 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11859 bool NotUnity =
11860 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11861
Samuel Antaodab51bb2016-07-18 23:22:11 +000011862 if (AllowWholeSizeArraySection) {
11863 // Any array section is currently allowed. Allowing a whole size array
11864 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011865 //
11866 // If this array section refers to the whole dimension we can still
11867 // accept other array sections before this one, except if the base is a
11868 // pointer. Otherwise, only unitary sections are accepted.
11869 if (NotWhole || IsPointer)
11870 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011871 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011872 // A unity or whole array section is not allowed and that is not
11873 // compatible with the properties of the current array section.
11874 SemaRef.Diag(
11875 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11876 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011877 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011878 }
Samuel Antao90927002016-04-26 14:54:23 +000011879
11880 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011881 CurComponents.emplace_back(CurE, nullptr);
11882 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011883 if (!NoDiagnose) {
11884 // If nothing else worked, this is not a valid map clause expression.
11885 SemaRef.Diag(
11886 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11887 << ERange;
11888 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011889 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011890 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011891 }
11892
11893 return RelevantExpr;
11894}
11895
11896// Return true if expression E associated with value VD has conflicts with other
11897// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011898static bool CheckMapConflicts(
11899 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11900 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011901 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11902 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011903 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011904 SourceLocation ELoc = E->getExprLoc();
11905 SourceRange ERange = E->getSourceRange();
11906
11907 // In order to easily check the conflicts we need to match each component of
11908 // the expression under test with the components of the expressions that are
11909 // already in the stack.
11910
Samuel Antao5de996e2016-01-22 20:21:36 +000011911 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011912 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011913 "Map clause expression with unexpected base!");
11914
11915 // Variables to help detecting enclosing problems in data environment nests.
11916 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011917 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011918
Samuel Antao90927002016-04-26 14:54:23 +000011919 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11920 VD, CurrentRegionOnly,
11921 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011922 StackComponents,
11923 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011924
Samuel Antao5de996e2016-01-22 20:21:36 +000011925 assert(!StackComponents.empty() &&
11926 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011927 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011928 "Map clause expression with unexpected base!");
11929
Samuel Antao90927002016-04-26 14:54:23 +000011930 // The whole expression in the stack.
11931 auto *RE = StackComponents.front().getAssociatedExpression();
11932
Samuel Antao5de996e2016-01-22 20:21:36 +000011933 // Expressions must start from the same base. Here we detect at which
11934 // point both expressions diverge from each other and see if we can
11935 // detect if the memory referred to both expressions is contiguous and
11936 // do not overlap.
11937 auto CI = CurComponents.rbegin();
11938 auto CE = CurComponents.rend();
11939 auto SI = StackComponents.rbegin();
11940 auto SE = StackComponents.rend();
11941 for (; CI != CE && SI != SE; ++CI, ++SI) {
11942
11943 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11944 // At most one list item can be an array item derived from a given
11945 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011946 if (CurrentRegionOnly &&
11947 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11948 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11949 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11950 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11951 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011952 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011953 << CI->getAssociatedExpression()->getSourceRange();
11954 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11955 diag::note_used_here)
11956 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011957 return true;
11958 }
11959
11960 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011961 if (CI->getAssociatedExpression()->getStmtClass() !=
11962 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011963 break;
11964
11965 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011966 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011967 break;
11968 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011969 // Check if the extra components of the expressions in the enclosing
11970 // data environment are redundant for the current base declaration.
11971 // If they are, the maps completely overlap, which is legal.
11972 for (; SI != SE; ++SI) {
11973 QualType Type;
11974 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011975 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011976 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011977 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11978 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011979 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11980 Type =
11981 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11982 }
11983 if (Type.isNull() || Type->isAnyPointerType() ||
11984 CheckArrayExpressionDoesNotReferToWholeSize(
11985 SemaRef, SI->getAssociatedExpression(), Type))
11986 break;
11987 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011988
11989 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11990 // List items of map clauses in the same construct must not share
11991 // original storage.
11992 //
11993 // If the expressions are exactly the same or one is a subset of the
11994 // other, it means they are sharing storage.
11995 if (CI == CE && SI == SE) {
11996 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011997 if (CKind == OMPC_map)
11998 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11999 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012000 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012001 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12002 << ERange;
12003 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012004 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12005 << RE->getSourceRange();
12006 return true;
12007 } else {
12008 // If we find the same expression in the enclosing data environment,
12009 // that is legal.
12010 IsEnclosedByDataEnvironmentExpr = true;
12011 return false;
12012 }
12013 }
12014
Samuel Antao90927002016-04-26 14:54:23 +000012015 QualType DerivedType =
12016 std::prev(CI)->getAssociatedDeclaration()->getType();
12017 SourceLocation DerivedLoc =
12018 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012019
12020 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12021 // If the type of a list item is a reference to a type T then the type
12022 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012023 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012024
12025 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12026 // A variable for which the type is pointer and an array section
12027 // derived from that variable must not appear as list items of map
12028 // clauses of the same construct.
12029 //
12030 // Also, cover one of the cases in:
12031 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12032 // If any part of the original storage of a list item has corresponding
12033 // storage in the device data environment, all of the original storage
12034 // must have corresponding storage in the device data environment.
12035 //
12036 if (DerivedType->isAnyPointerType()) {
12037 if (CI == CE || SI == SE) {
12038 SemaRef.Diag(
12039 DerivedLoc,
12040 diag::err_omp_pointer_mapped_along_with_derived_section)
12041 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012042 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12043 << RE->getSourceRange();
12044 return true;
12045 } else if (CI->getAssociatedExpression()->getStmtClass() !=
12046 SI->getAssociatedExpression()->getStmtClass() ||
12047 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12048 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012049 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012050 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012051 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012052 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12053 << RE->getSourceRange();
12054 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012055 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012056 }
12057
12058 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12059 // List items of map clauses in the same construct must not share
12060 // original storage.
12061 //
12062 // An expression is a subset of the other.
12063 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000012064 if (CKind == OMPC_map)
12065 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12066 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012067 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012068 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12069 << ERange;
12070 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012071 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12072 << RE->getSourceRange();
12073 return true;
12074 }
12075
12076 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012077 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012078 if (!CurrentRegionOnly && SI != SE)
12079 EnclosingExpr = RE;
12080
12081 // The current expression is a subset of the expression in the data
12082 // environment.
12083 IsEnclosedByDataEnvironmentExpr |=
12084 (!CurrentRegionOnly && CI != CE && SI == SE);
12085
12086 return false;
12087 });
12088
12089 if (CurrentRegionOnly)
12090 return FoundError;
12091
12092 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12093 // If any part of the original storage of a list item has corresponding
12094 // storage in the device data environment, all of the original storage must
12095 // have corresponding storage in the device data environment.
12096 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12097 // If a list item is an element of a structure, and a different element of
12098 // the structure has a corresponding list item in the device data environment
12099 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012100 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012101 // data environment prior to the task encountering the construct.
12102 //
12103 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12104 SemaRef.Diag(ELoc,
12105 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12106 << ERange;
12107 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12108 << EnclosingExpr->getSourceRange();
12109 return true;
12110 }
12111
12112 return FoundError;
12113}
12114
Samuel Antao661c0902016-05-26 17:39:58 +000012115namespace {
12116// Utility struct that gathers all the related lists associated with a mappable
12117// expression.
12118struct MappableVarListInfo final {
12119 // The list of expressions.
12120 ArrayRef<Expr *> VarList;
12121 // The list of processed expressions.
12122 SmallVector<Expr *, 16> ProcessedVarList;
12123 // The mappble components for each expression.
12124 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12125 // The base declaration of the variable.
12126 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12127
12128 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12129 // We have a list of components and base declarations for each entry in the
12130 // variable list.
12131 VarComponents.reserve(VarList.size());
12132 VarBaseDeclarations.reserve(VarList.size());
12133 }
12134};
12135}
12136
12137// Check the validity of the provided variable list for the provided clause kind
12138// \a CKind. In the check process the valid expressions, and mappable expression
12139// components and variables are extracted and used to fill \a Vars,
12140// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12141// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12142static void
12143checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12144 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12145 SourceLocation StartLoc,
12146 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12147 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012148 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12149 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012150 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012151
Samuel Antao90927002016-04-26 14:54:23 +000012152 // Keep track of the mappable components and base declarations in this clause.
12153 // Each entry in the list is going to have a list of components associated. We
12154 // record each set of the components so that we can build the clause later on.
12155 // In the end we should have the same amount of declarations and component
12156 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012157
Samuel Antao661c0902016-05-26 17:39:58 +000012158 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012159 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012160 SourceLocation ELoc = RE->getExprLoc();
12161
Kelvin Li0bff7af2015-11-23 05:32:03 +000012162 auto *VE = RE->IgnoreParenLValueCasts();
12163
12164 if (VE->isValueDependent() || VE->isTypeDependent() ||
12165 VE->isInstantiationDependent() ||
12166 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012167 // We can only analyze this information once the missing information is
12168 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012169 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012170 continue;
12171 }
12172
12173 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012174
Samuel Antao5de996e2016-01-22 20:21:36 +000012175 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012176 SemaRef.Diag(ELoc,
12177 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012178 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012179 continue;
12180 }
12181
Samuel Antao90927002016-04-26 14:54:23 +000012182 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12183 ValueDecl *CurDeclaration = nullptr;
12184
12185 // Obtain the array or member expression bases if required. Also, fill the
12186 // components array with all the components identified in the process.
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012187 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12188 CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012189 if (!BE)
12190 continue;
12191
Samuel Antao90927002016-04-26 14:54:23 +000012192 assert(!CurComponents.empty() &&
12193 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012194
Samuel Antao90927002016-04-26 14:54:23 +000012195 // For the following checks, we rely on the base declaration which is
12196 // expected to be associated with the last component. The declaration is
12197 // expected to be a variable or a field (if 'this' is being mapped).
12198 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12199 assert(CurDeclaration && "Null decl on map clause.");
12200 assert(
12201 CurDeclaration->isCanonicalDecl() &&
12202 "Expecting components to have associated only canonical declarations.");
12203
12204 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12205 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012206
12207 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012208 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012209
12210 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012211 // threadprivate variables cannot appear in a map clause.
12212 // OpenMP 4.5 [2.10.5, target update Construct]
12213 // threadprivate variables cannot appear in a from clause.
12214 if (VD && DSAS->isThreadPrivate(VD)) {
12215 auto DVar = DSAS->getTopDSA(VD, false);
12216 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12217 << getOpenMPClauseName(CKind);
12218 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012219 continue;
12220 }
12221
Samuel Antao5de996e2016-01-22 20:21:36 +000012222 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12223 // A list item cannot appear in both a map clause and a data-sharing
12224 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000012225
Samuel Antao5de996e2016-01-22 20:21:36 +000012226 // Check conflicts with other map clause expressions. We check the conflicts
12227 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000012228 // environment, because the restrictions are different. We only have to
12229 // check conflicts across regions for the map clauses.
12230 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12231 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012232 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012233 if (CKind == OMPC_map &&
12234 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12235 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012236 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012237
Samuel Antao661c0902016-05-26 17:39:58 +000012238 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000012239 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12240 // If the type of a list item is a reference to a type T then the type will
12241 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012242 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012243
Samuel Antao661c0902016-05-26 17:39:58 +000012244 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12245 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000012246 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000012247 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000012248 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12249 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000012250 continue;
12251
Samuel Antao661c0902016-05-26 17:39:58 +000012252 if (CKind == OMPC_map) {
12253 // target enter data
12254 // OpenMP [2.10.2, Restrictions, p. 99]
12255 // A map-type must be specified in all map clauses and must be either
12256 // to or alloc.
12257 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12258 if (DKind == OMPD_target_enter_data &&
12259 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12260 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12261 << (IsMapTypeImplicit ? 1 : 0)
12262 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12263 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012264 continue;
12265 }
Samuel Antao661c0902016-05-26 17:39:58 +000012266
12267 // target exit_data
12268 // OpenMP [2.10.3, Restrictions, p. 102]
12269 // A map-type must be specified in all map clauses and must be either
12270 // from, release, or delete.
12271 if (DKind == OMPD_target_exit_data &&
12272 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12273 MapType == OMPC_MAP_delete)) {
12274 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12275 << (IsMapTypeImplicit ? 1 : 0)
12276 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12277 << getOpenMPDirectiveName(DKind);
12278 continue;
12279 }
12280
12281 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12282 // A list item cannot appear in both a map clause and a data-sharing
12283 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000012284 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000012285 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000012286 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000012287 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12288 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000012289 auto DVar = DSAS->getTopDSA(VD, false);
12290 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012291 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012292 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012293 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012294 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12295 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12296 continue;
12297 }
12298 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012299 }
12300
Samuel Antao90927002016-04-26 14:54:23 +000012301 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012302 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012303
12304 // Store the components in the stack so that they can be used to check
12305 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012306 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12307 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012308
12309 // Save the components and declaration to create the clause. For purposes of
12310 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012311 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012312 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12313 MVLI.VarComponents.back().append(CurComponents.begin(),
12314 CurComponents.end());
12315 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12316 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012317 }
Samuel Antao661c0902016-05-26 17:39:58 +000012318}
12319
12320OMPClause *
12321Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12322 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12323 SourceLocation MapLoc, SourceLocation ColonLoc,
12324 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12325 SourceLocation LParenLoc, SourceLocation EndLoc) {
12326 MappableVarListInfo MVLI(VarList);
12327 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12328 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012329
Samuel Antao5de996e2016-01-22 20:21:36 +000012330 // We need to produce a map clause even if we don't have variables so that
12331 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012332 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12333 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12334 MVLI.VarComponents, MapTypeModifier, MapType,
12335 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012336}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012337
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012338QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12339 TypeResult ParsedType) {
12340 assert(ParsedType.isUsable());
12341
12342 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12343 if (ReductionType.isNull())
12344 return QualType();
12345
12346 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12347 // A type name in a declare reduction directive cannot be a function type, an
12348 // array type, a reference type, or a type qualified with const, volatile or
12349 // restrict.
12350 if (ReductionType.hasQualifiers()) {
12351 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12352 return QualType();
12353 }
12354
12355 if (ReductionType->isFunctionType()) {
12356 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12357 return QualType();
12358 }
12359 if (ReductionType->isReferenceType()) {
12360 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12361 return QualType();
12362 }
12363 if (ReductionType->isArrayType()) {
12364 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12365 return QualType();
12366 }
12367 return ReductionType;
12368}
12369
12370Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12371 Scope *S, DeclContext *DC, DeclarationName Name,
12372 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12373 AccessSpecifier AS, Decl *PrevDeclInScope) {
12374 SmallVector<Decl *, 8> Decls;
12375 Decls.reserve(ReductionTypes.size());
12376
12377 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012378 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012379 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12380 // A reduction-identifier may not be re-declared in the current scope for the
12381 // same type or for a type that is compatible according to the base language
12382 // rules.
12383 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12384 OMPDeclareReductionDecl *PrevDRD = nullptr;
12385 bool InCompoundScope = true;
12386 if (S != nullptr) {
12387 // Find previous declaration with the same name not referenced in other
12388 // declarations.
12389 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12390 InCompoundScope =
12391 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12392 LookupName(Lookup, S);
12393 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12394 /*AllowInlineNamespace=*/false);
12395 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12396 auto Filter = Lookup.makeFilter();
12397 while (Filter.hasNext()) {
12398 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12399 if (InCompoundScope) {
12400 auto I = UsedAsPrevious.find(PrevDecl);
12401 if (I == UsedAsPrevious.end())
12402 UsedAsPrevious[PrevDecl] = false;
12403 if (auto *D = PrevDecl->getPrevDeclInScope())
12404 UsedAsPrevious[D] = true;
12405 }
12406 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12407 PrevDecl->getLocation();
12408 }
12409 Filter.done();
12410 if (InCompoundScope) {
12411 for (auto &PrevData : UsedAsPrevious) {
12412 if (!PrevData.second) {
12413 PrevDRD = PrevData.first;
12414 break;
12415 }
12416 }
12417 }
12418 } else if (PrevDeclInScope != nullptr) {
12419 auto *PrevDRDInScope = PrevDRD =
12420 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12421 do {
12422 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12423 PrevDRDInScope->getLocation();
12424 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12425 } while (PrevDRDInScope != nullptr);
12426 }
12427 for (auto &TyData : ReductionTypes) {
12428 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12429 bool Invalid = false;
12430 if (I != PreviousRedeclTypes.end()) {
12431 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12432 << TyData.first;
12433 Diag(I->second, diag::note_previous_definition);
12434 Invalid = true;
12435 }
12436 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12437 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12438 Name, TyData.first, PrevDRD);
12439 DC->addDecl(DRD);
12440 DRD->setAccess(AS);
12441 Decls.push_back(DRD);
12442 if (Invalid)
12443 DRD->setInvalidDecl();
12444 else
12445 PrevDRD = DRD;
12446 }
12447
12448 return DeclGroupPtrTy::make(
12449 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12450}
12451
12452void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12453 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12454
12455 // Enter new function scope.
12456 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012457 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012458 getCurFunction()->setHasOMPDeclareReductionCombiner();
12459
12460 if (S != nullptr)
12461 PushDeclContext(S, DRD);
12462 else
12463 CurContext = DRD;
12464
Faisal Valid143a0c2017-04-01 21:30:49 +000012465 PushExpressionEvaluationContext(
12466 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012467
12468 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012469 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12470 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12471 // uses semantics of argument handles by value, but it should be passed by
12472 // reference. C lang does not support references, so pass all parameters as
12473 // pointers.
12474 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012475 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012476 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012477 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12478 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12479 // uses semantics of argument handles by value, but it should be passed by
12480 // reference. C lang does not support references, so pass all parameters as
12481 // pointers.
12482 // Create 'T omp_out;' variable.
12483 auto *OmpOutParm =
12484 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12485 if (S != nullptr) {
12486 PushOnScopeChains(OmpInParm, S);
12487 PushOnScopeChains(OmpOutParm, S);
12488 } else {
12489 DRD->addDecl(OmpInParm);
12490 DRD->addDecl(OmpOutParm);
12491 }
12492}
12493
12494void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12495 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12496 DiscardCleanupsInEvaluationContext();
12497 PopExpressionEvaluationContext();
12498
12499 PopDeclContext();
12500 PopFunctionScopeInfo();
12501
12502 if (Combiner != nullptr)
12503 DRD->setCombiner(Combiner);
12504 else
12505 DRD->setInvalidDecl();
12506}
12507
Alexey Bataev070f43a2017-09-06 14:49:58 +000012508VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012509 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12510
12511 // Enter new function scope.
12512 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012513 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012514
12515 if (S != nullptr)
12516 PushDeclContext(S, DRD);
12517 else
12518 CurContext = DRD;
12519
Faisal Valid143a0c2017-04-01 21:30:49 +000012520 PushExpressionEvaluationContext(
12521 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012522
12523 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012524 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12525 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12526 // uses semantics of argument handles by value, but it should be passed by
12527 // reference. C lang does not support references, so pass all parameters as
12528 // pointers.
12529 // Create 'T omp_priv;' variable.
12530 auto *OmpPrivParm =
12531 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012532 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12533 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12534 // uses semantics of argument handles by value, but it should be passed by
12535 // reference. C lang does not support references, so pass all parameters as
12536 // pointers.
12537 // Create 'T omp_orig;' variable.
12538 auto *OmpOrigParm =
12539 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012540 if (S != nullptr) {
12541 PushOnScopeChains(OmpPrivParm, S);
12542 PushOnScopeChains(OmpOrigParm, S);
12543 } else {
12544 DRD->addDecl(OmpPrivParm);
12545 DRD->addDecl(OmpOrigParm);
12546 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012547 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012548}
12549
Alexey Bataev070f43a2017-09-06 14:49:58 +000012550void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12551 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012552 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12553 DiscardCleanupsInEvaluationContext();
12554 PopExpressionEvaluationContext();
12555
12556 PopDeclContext();
12557 PopFunctionScopeInfo();
12558
Alexey Bataev070f43a2017-09-06 14:49:58 +000012559 if (Initializer != nullptr) {
12560 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12561 } else if (OmpPrivParm->hasInit()) {
12562 DRD->setInitializer(OmpPrivParm->getInit(),
12563 OmpPrivParm->isDirectInit()
12564 ? OMPDeclareReductionDecl::DirectInit
12565 : OMPDeclareReductionDecl::CopyInit);
12566 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012567 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012568 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012569}
12570
12571Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12572 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12573 for (auto *D : DeclReductions.get()) {
12574 if (IsValid) {
12575 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12576 if (S != nullptr)
12577 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12578 } else
12579 D->setInvalidDecl();
12580 }
12581 return DeclReductions;
12582}
12583
David Majnemer9d168222016-08-05 17:44:54 +000012584OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012585 SourceLocation StartLoc,
12586 SourceLocation LParenLoc,
12587 SourceLocation EndLoc) {
12588 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012589 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012590
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012591 // OpenMP [teams Constrcut, Restrictions]
12592 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012593 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12594 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012595 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012596
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012597 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012598 OpenMPDirectiveKind CaptureRegion =
12599 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12600 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012601 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012602 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12603 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12604 HelperValStmt = buildPreInits(Context, Captures);
12605 }
12606
12607 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12608 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012609}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012610
12611OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12612 SourceLocation StartLoc,
12613 SourceLocation LParenLoc,
12614 SourceLocation EndLoc) {
12615 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012616 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012617
12618 // OpenMP [teams Constrcut, Restrictions]
12619 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012620 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12621 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012622 return nullptr;
12623
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012624 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012625 OpenMPDirectiveKind CaptureRegion =
12626 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12627 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012628 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012629 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12630 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12631 HelperValStmt = buildPreInits(Context, Captures);
12632 }
12633
12634 return new (Context) OMPThreadLimitClause(
12635 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012636}
Alexey Bataeva0569352015-12-01 10:17:31 +000012637
12638OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12639 SourceLocation StartLoc,
12640 SourceLocation LParenLoc,
12641 SourceLocation EndLoc) {
12642 Expr *ValExpr = Priority;
12643
12644 // OpenMP [2.9.1, task Constrcut]
12645 // The priority-value is a non-negative numerical scalar expression.
12646 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12647 /*StrictlyPositive=*/false))
12648 return nullptr;
12649
12650 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12651}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012652
12653OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12654 SourceLocation StartLoc,
12655 SourceLocation LParenLoc,
12656 SourceLocation EndLoc) {
12657 Expr *ValExpr = Grainsize;
12658
12659 // OpenMP [2.9.2, taskloop Constrcut]
12660 // The parameter of the grainsize clause must be a positive integer
12661 // expression.
12662 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12663 /*StrictlyPositive=*/true))
12664 return nullptr;
12665
12666 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12667}
Alexey Bataev382967a2015-12-08 12:06:20 +000012668
12669OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12670 SourceLocation StartLoc,
12671 SourceLocation LParenLoc,
12672 SourceLocation EndLoc) {
12673 Expr *ValExpr = NumTasks;
12674
12675 // OpenMP [2.9.2, taskloop Constrcut]
12676 // The parameter of the num_tasks clause must be a positive integer
12677 // expression.
12678 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12679 /*StrictlyPositive=*/true))
12680 return nullptr;
12681
12682 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12683}
12684
Alexey Bataev28c75412015-12-15 08:19:24 +000012685OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12686 SourceLocation LParenLoc,
12687 SourceLocation EndLoc) {
12688 // OpenMP [2.13.2, critical construct, Description]
12689 // ... where hint-expression is an integer constant expression that evaluates
12690 // to a valid lock hint.
12691 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12692 if (HintExpr.isInvalid())
12693 return nullptr;
12694 return new (Context)
12695 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12696}
12697
Carlo Bertollib4adf552016-01-15 18:50:31 +000012698OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12699 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12700 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12701 SourceLocation EndLoc) {
12702 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12703 std::string Values;
12704 Values += "'";
12705 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12706 Values += "'";
12707 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12708 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12709 return nullptr;
12710 }
12711 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012712 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012713 if (ChunkSize) {
12714 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12715 !ChunkSize->isInstantiationDependent() &&
12716 !ChunkSize->containsUnexpandedParameterPack()) {
12717 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12718 ExprResult Val =
12719 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12720 if (Val.isInvalid())
12721 return nullptr;
12722
12723 ValExpr = Val.get();
12724
12725 // OpenMP [2.7.1, Restrictions]
12726 // chunk_size must be a loop invariant integer expression with a positive
12727 // value.
12728 llvm::APSInt Result;
12729 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12730 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12731 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12732 << "dist_schedule" << ChunkSize->getSourceRange();
12733 return nullptr;
12734 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012735 } else if (getOpenMPCaptureRegionForClause(
12736 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12737 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012738 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012739 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000012740 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12741 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12742 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012743 }
12744 }
12745 }
12746
12747 return new (Context)
12748 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012749 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012750}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012751
12752OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12753 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12754 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12755 SourceLocation KindLoc, SourceLocation EndLoc) {
12756 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012757 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012758 std::string Value;
12759 SourceLocation Loc;
12760 Value += "'";
12761 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12762 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012763 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012764 Loc = MLoc;
12765 } else {
12766 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012767 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012768 Loc = KindLoc;
12769 }
12770 Value += "'";
12771 Diag(Loc, diag::err_omp_unexpected_clause_value)
12772 << Value << getOpenMPClauseName(OMPC_defaultmap);
12773 return nullptr;
12774 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012775 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012776
12777 return new (Context)
12778 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12779}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012780
12781bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12782 DeclContext *CurLexicalContext = getCurLexicalContext();
12783 if (!CurLexicalContext->isFileContext() &&
12784 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012785 !CurLexicalContext->isExternCXXContext() &&
12786 !isa<CXXRecordDecl>(CurLexicalContext) &&
12787 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12788 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12789 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012790 Diag(Loc, diag::err_omp_region_not_file_context);
12791 return false;
12792 }
12793 if (IsInOpenMPDeclareTargetContext) {
12794 Diag(Loc, diag::err_omp_enclosed_declare_target);
12795 return false;
12796 }
12797
12798 IsInOpenMPDeclareTargetContext = true;
12799 return true;
12800}
12801
12802void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12803 assert(IsInOpenMPDeclareTargetContext &&
12804 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12805
12806 IsInOpenMPDeclareTargetContext = false;
12807}
12808
David Majnemer9d168222016-08-05 17:44:54 +000012809void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12810 CXXScopeSpec &ScopeSpec,
12811 const DeclarationNameInfo &Id,
12812 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12813 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012814 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12815 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12816
12817 if (Lookup.isAmbiguous())
12818 return;
12819 Lookup.suppressDiagnostics();
12820
12821 if (!Lookup.isSingleResult()) {
12822 if (TypoCorrection Corrected =
12823 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12824 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12825 CTK_ErrorRecovery)) {
12826 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12827 << Id.getName());
12828 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12829 return;
12830 }
12831
12832 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12833 return;
12834 }
12835
12836 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12837 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12838 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12839 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12840
12841 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12842 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12843 ND->addAttr(A);
12844 if (ASTMutationListener *ML = Context.getASTMutationListener())
12845 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000012846 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012847 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12848 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12849 << Id.getName();
12850 }
12851 } else
12852 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12853}
12854
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012855static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12856 Sema &SemaRef, Decl *D) {
12857 if (!D)
12858 return;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012859 const Decl *LD = nullptr;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012860 if (isa<TagDecl>(D)) {
12861 LD = cast<TagDecl>(D)->getDefinition();
12862 } else if (isa<VarDecl>(D)) {
12863 LD = cast<VarDecl>(D)->getDefinition();
12864
12865 // If this is an implicit variable that is legal and we do not need to do
12866 // anything.
12867 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012868 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12869 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12870 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012871 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012872 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012873 return;
12874 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000012875 } else if (auto *F = dyn_cast<FunctionDecl>(D)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012876 const FunctionDecl *FD = nullptr;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012877 if (cast<FunctionDecl>(D)->hasBody(FD)) {
12878 LD = FD;
12879 // If the definition is associated with the current declaration in the
12880 // target region (it can be e.g. a lambda) that is legal and we do not
12881 // need to do anything else.
12882 if (LD == D) {
12883 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12884 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12885 D->addAttr(A);
12886 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12887 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12888 return;
12889 }
12890 } else if (F->isFunctionTemplateSpecialization() &&
12891 F->getTemplateSpecializationKind() ==
12892 TSK_ImplicitInstantiation) {
12893 // Check if the function is implicitly instantiated from the template
12894 // defined in the declare target region.
12895 const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
12896 if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
12897 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012898 }
12899 }
12900 if (!LD)
12901 LD = D;
12902 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12903 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12904 // Outlined declaration is not declared target.
12905 if (LD->isOutOfLine()) {
12906 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12907 SemaRef.Diag(SL, diag::note_used_here) << SR;
12908 } else {
Alexey Bataev8e39c342018-02-16 21:23:23 +000012909 const DeclContext *DC = LD->getDeclContext();
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012910 while (DC) {
12911 if (isa<FunctionDecl>(DC) &&
12912 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12913 break;
12914 DC = DC->getParent();
12915 }
12916 if (DC)
12917 return;
12918
12919 // Is not declared in target context.
12920 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12921 SemaRef.Diag(SL, diag::note_used_here) << SR;
12922 }
12923 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012924 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12925 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12926 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012927 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012928 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012929 }
12930}
12931
12932static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12933 Sema &SemaRef, DSAStackTy *Stack,
12934 ValueDecl *VD) {
12935 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12936 return true;
Alexey Bataev95c23e72018-02-27 21:31:11 +000012937 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
12938 /*FullCheck=*/false))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012939 return false;
12940 return true;
12941}
12942
Kelvin Li1ce87c72017-12-12 20:08:12 +000012943void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12944 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012945 if (!D || D->isInvalidDecl())
12946 return;
12947 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12948 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12949 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12950 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12951 if (DSAStack->isThreadPrivate(VD)) {
12952 Diag(SL, diag::err_omp_threadprivate_in_target);
12953 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12954 return;
12955 }
12956 }
12957 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12958 // Problem if any with var declared with incomplete type will be reported
12959 // as normal, so no need to check it here.
12960 if ((E || !VD->getType()->isIncompleteType()) &&
12961 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12962 // Mark decl as declared target to prevent further diagnostic.
Alexey Bataev8e39c342018-02-16 21:23:23 +000012963 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
12964 isa<FunctionTemplateDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012965 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12966 Context, OMPDeclareTargetDeclAttr::MT_To);
12967 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012968 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012969 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012970 }
12971 return;
12972 }
12973 }
Kelvin Li1ce87c72017-12-12 20:08:12 +000012974 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12975 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12976 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12977 OMPDeclareTargetDeclAttr::MT_Link)) {
12978 assert(IdLoc.isValid() && "Source location is expected");
12979 Diag(IdLoc, diag::err_omp_function_in_link_clause);
12980 Diag(FD->getLocation(), diag::note_defined_here) << FD;
12981 return;
12982 }
12983 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000012984 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
12985 if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12986 (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12987 OMPDeclareTargetDeclAttr::MT_Link)) {
12988 assert(IdLoc.isValid() && "Source location is expected");
12989 Diag(IdLoc, diag::err_omp_function_in_link_clause);
12990 Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
12991 return;
12992 }
12993 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012994 if (!E) {
12995 // Checking declaration inside declare target region.
12996 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
Alexey Bataev8e39c342018-02-16 21:23:23 +000012997 (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
12998 isa<FunctionTemplateDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012999 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13000 Context, OMPDeclareTargetDeclAttr::MT_To);
13001 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013002 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013003 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013004 }
13005 return;
13006 }
13007 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13008}
Samuel Antao661c0902016-05-26 17:39:58 +000013009
13010OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13011 SourceLocation StartLoc,
13012 SourceLocation LParenLoc,
13013 SourceLocation EndLoc) {
13014 MappableVarListInfo MVLI(VarList);
13015 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13016 if (MVLI.ProcessedVarList.empty())
13017 return nullptr;
13018
13019 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13020 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13021 MVLI.VarComponents);
13022}
Samuel Antaoec172c62016-05-26 17:49:04 +000013023
13024OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13025 SourceLocation StartLoc,
13026 SourceLocation LParenLoc,
13027 SourceLocation EndLoc) {
13028 MappableVarListInfo MVLI(VarList);
13029 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13030 if (MVLI.ProcessedVarList.empty())
13031 return nullptr;
13032
13033 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13034 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13035 MVLI.VarComponents);
13036}
Carlo Bertolli2404b172016-07-13 15:37:16 +000013037
13038OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13039 SourceLocation StartLoc,
13040 SourceLocation LParenLoc,
13041 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000013042 MappableVarListInfo MVLI(VarList);
13043 SmallVector<Expr *, 8> PrivateCopies;
13044 SmallVector<Expr *, 8> Inits;
13045
Carlo Bertolli2404b172016-07-13 15:37:16 +000013046 for (auto &RefExpr : VarList) {
13047 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13048 SourceLocation ELoc;
13049 SourceRange ERange;
13050 Expr *SimpleRefExpr = RefExpr;
13051 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13052 if (Res.second) {
13053 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000013054 MVLI.ProcessedVarList.push_back(RefExpr);
13055 PrivateCopies.push_back(nullptr);
13056 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013057 }
13058 ValueDecl *D = Res.first;
13059 if (!D)
13060 continue;
13061
13062 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000013063 Type = Type.getNonReferenceType().getUnqualifiedType();
13064
13065 auto *VD = dyn_cast<VarDecl>(D);
13066
13067 // Item should be a pointer or reference to pointer.
13068 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013069 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13070 << 0 << RefExpr->getSourceRange();
13071 continue;
13072 }
Samuel Antaocc10b852016-07-28 14:23:26 +000013073
13074 // Build the private variable and the expression that refers to it.
13075 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
13076 D->hasAttrs() ? &D->getAttrs() : nullptr);
13077 if (VDPrivate->isInvalidDecl())
13078 continue;
13079
13080 CurContext->addDecl(VDPrivate);
13081 auto VDPrivateRefExpr = buildDeclRefExpr(
13082 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13083
13084 // Add temporary variable to initialize the private copy of the pointer.
13085 auto *VDInit =
13086 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13087 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13088 RefExpr->getExprLoc());
13089 AddInitializerToDecl(VDPrivate,
13090 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013091 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013092
13093 // If required, build a capture to implement the privatization initialized
13094 // with the current list item value.
13095 DeclRefExpr *Ref = nullptr;
13096 if (!VD)
13097 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13098 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13099 PrivateCopies.push_back(VDPrivateRefExpr);
13100 Inits.push_back(VDInitRefExpr);
13101
13102 // We need to add a data sharing attribute for this variable to make sure it
13103 // is correctly captured. A variable that shows up in a use_device_ptr has
13104 // similar properties of a first private variable.
13105 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13106
13107 // Create a mappable component for the list item. List items in this clause
13108 // only need a component.
13109 MVLI.VarBaseDeclarations.push_back(D);
13110 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13111 MVLI.VarComponents.back().push_back(
13112 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013113 }
13114
Samuel Antaocc10b852016-07-28 14:23:26 +000013115 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013116 return nullptr;
13117
Samuel Antaocc10b852016-07-28 14:23:26 +000013118 return OMPUseDevicePtrClause::Create(
13119 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13120 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013121}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013122
13123OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13124 SourceLocation StartLoc,
13125 SourceLocation LParenLoc,
13126 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013127 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013128 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013129 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013130 SourceLocation ELoc;
13131 SourceRange ERange;
13132 Expr *SimpleRefExpr = RefExpr;
13133 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13134 if (Res.second) {
13135 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013136 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013137 }
13138 ValueDecl *D = Res.first;
13139 if (!D)
13140 continue;
13141
13142 QualType Type = D->getType();
13143 // item should be a pointer or array or reference to pointer or array
13144 if (!Type.getNonReferenceType()->isPointerType() &&
13145 !Type.getNonReferenceType()->isArrayType()) {
13146 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13147 << 0 << RefExpr->getSourceRange();
13148 continue;
13149 }
Samuel Antao6890b092016-07-28 14:25:09 +000013150
13151 // Check if the declaration in the clause does not show up in any data
13152 // sharing attribute.
13153 auto DVar = DSAStack->getTopDSA(D, false);
13154 if (isOpenMPPrivate(DVar.CKind)) {
13155 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13156 << getOpenMPClauseName(DVar.CKind)
13157 << getOpenMPClauseName(OMPC_is_device_ptr)
13158 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13159 ReportOriginalDSA(*this, DSAStack, D, DVar);
13160 continue;
13161 }
13162
13163 Expr *ConflictExpr;
13164 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013165 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013166 [&ConflictExpr](
13167 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13168 OpenMPClauseKind) -> bool {
13169 ConflictExpr = R.front().getAssociatedExpression();
13170 return true;
13171 })) {
13172 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13173 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13174 << ConflictExpr->getSourceRange();
13175 continue;
13176 }
13177
13178 // Store the components in the stack so that they can be used to check
13179 // against other clauses later on.
13180 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13181 DSAStack->addMappableExpressionComponents(
13182 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13183
13184 // Record the expression we've just processed.
13185 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13186
13187 // Create a mappable component for the list item. List items in this clause
13188 // only need a component. We use a null declaration to signal fields in
13189 // 'this'.
13190 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13191 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13192 "Unexpected device pointer expression!");
13193 MVLI.VarBaseDeclarations.push_back(
13194 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13195 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13196 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013197 }
13198
Samuel Antao6890b092016-07-28 14:25:09 +000013199 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013200 return nullptr;
13201
Samuel Antao6890b092016-07-28 14:25:09 +000013202 return OMPIsDevicePtrClause::Create(
13203 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13204 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013205}