blob: 76b7f3ab15ee51d413330ab2b23a591c50dffafb [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,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000806 StringRef Name, const AttrVec *Attrs = nullptr,
807 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000808 DeclContext *DC = SemaRef.CurContext;
809 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
810 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
811 VarDecl *Decl =
812 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
813 if (Attrs) {
814 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
815 I != E; ++I)
816 Decl->addAttr(*I);
817 }
818 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000819 if (OrigRef) {
820 Decl->addAttr(
821 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
822 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000823 return Decl;
824}
825
826static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
827 SourceLocation Loc,
828 bool RefersToCapture = false) {
829 D->setReferenced();
830 D->markUsed(S.Context);
831 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
832 SourceLocation(), D, RefersToCapture, Loc, Ty,
833 VK_LValue);
834}
835
836void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
837 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000838 D = getCanonicalDecl(D);
839 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000840 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000841 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000842 "Additional reduction info may be specified only for reduction items.");
843 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
844 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000845 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000846 "Additional reduction info may be specified only once for reduction "
847 "items.");
848 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000849 Expr *&TaskgroupReductionRef =
850 Stack.back().first.back().TaskgroupReductionRef;
851 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000852 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000853 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000854 TaskgroupReductionRef =
855 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000856 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000857}
858
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000859void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
860 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000861 D = getCanonicalDecl(D);
862 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000863 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000864 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000865 "Additional reduction info may be specified only for reduction items.");
866 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
867 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000868 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000869 "Additional reduction info may be specified only once for reduction "
870 "items.");
871 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000872 Expr *&TaskgroupReductionRef =
873 Stack.back().first.back().TaskgroupReductionRef;
874 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000875 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
876 ".task_red.");
877 TaskgroupReductionRef =
878 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000879 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000880}
881
Alexey Bataevf189cb72017-07-24 14:52:13 +0000882DSAStackTy::DSAVarData
883DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000884 BinaryOperatorKind &BOK,
885 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000887 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
888 if (Stack.back().first.empty())
889 return DSAVarData();
890 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000891 E = Stack.back().first.rend();
892 I != E; std::advance(I, 1)) {
893 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000894 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000895 continue;
896 auto &ReductionData = I->ReductionMap[D];
897 if (!ReductionData.ReductionOp ||
898 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000899 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000900 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000901 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000902 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
903 "expression for the descriptor is not "
904 "set.");
905 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000906 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
907 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000908 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000909 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000910}
911
Alexey Bataevf189cb72017-07-24 14:52:13 +0000912DSAStackTy::DSAVarData
913DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000914 const Expr *&ReductionRef,
915 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000916 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000917 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
918 if (Stack.back().first.empty())
919 return DSAVarData();
920 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000921 E = Stack.back().first.rend();
922 I != E; std::advance(I, 1)) {
923 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000924 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000925 continue;
926 auto &ReductionData = I->ReductionMap[D];
927 if (!ReductionData.ReductionOp ||
928 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000929 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000930 SR = ReductionData.ReductionRange;
931 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000932 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
933 "expression for the descriptor is not "
934 "set.");
935 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000936 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
937 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000938 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000939 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000940}
941
Alexey Bataeved09d242014-05-28 05:53:51 +0000942bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000943 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +0000944 if (!isStackEmpty()) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000945 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000946 Scope *TopScope = nullptr;
Alexey Bataev852525d2018-03-02 17:17:12 +0000947 while (I != E && !isParallelOrTaskRegion(I->Directive) &&
948 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000949 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000950 if (I == E)
951 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000952 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000953 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000954 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000955 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000956 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000957 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000958 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000959}
960
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000961DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
962 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000963 DSAVarData DVar;
964
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000965 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000966 auto TI = Threadprivates.find(D);
967 if (TI != Threadprivates.end()) {
968 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000969 DVar.CKind = OMPC_threadprivate;
970 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000971 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
972 DVar.RefExpr = buildDeclRefExpr(
973 SemaRef, VD, D->getType().getNonReferenceType(),
974 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
975 DVar.CKind = OMPC_threadprivate;
976 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +0000977 return DVar;
978 }
979 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
980 // in a Construct, C/C++, predetermined, p.1]
981 // Variables appearing in threadprivate directives are threadprivate.
982 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
983 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
984 SemaRef.getLangOpts().OpenMPUseTLS &&
985 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
986 (VD && VD->getStorageClass() == SC_Register &&
987 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
988 DVar.RefExpr = buildDeclRefExpr(
989 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
990 DVar.CKind = OMPC_threadprivate;
991 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
992 return DVar;
993 }
994 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
995 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
996 !isLoopControlVariable(D).first) {
997 auto IterTarget =
998 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
999 [](const SharingMapTy &Data) {
1000 return isOpenMPTargetExecutionDirective(Data.Directive);
1001 });
1002 if (IterTarget != Stack.back().first.rend()) {
1003 auto ParentIterTarget = std::next(IterTarget, 1);
1004 auto Iter = Stack.back().first.rbegin();
1005 while (Iter != ParentIterTarget) {
1006 if (isOpenMPLocal(VD, Iter)) {
1007 DVar.RefExpr =
1008 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1009 D->getLocation());
1010 DVar.CKind = OMPC_threadprivate;
1011 return DVar;
1012 }
1013 std::advance(Iter, 1);
1014 }
1015 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1016 auto DSAIter = IterTarget->SharingMap.find(D);
1017 if (DSAIter != IterTarget->SharingMap.end() &&
1018 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1019 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1020 DVar.CKind = OMPC_threadprivate;
1021 return DVar;
1022 } else if (!SemaRef.IsOpenMPCapturedByRef(
1023 D, std::distance(ParentIterTarget,
1024 Stack.back().first.rend()))) {
1025 DVar.RefExpr =
1026 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1027 IterTarget->ConstructLoc);
1028 DVar.CKind = OMPC_threadprivate;
1029 return DVar;
1030 }
1031 }
1032 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001033 }
1034
Alexey Bataev4b465392017-04-26 15:06:24 +00001035 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001036 // Not in OpenMP execution region and top scope was already checked.
1037 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001038
Alexey Bataev758e55e2013-09-06 18:03:48 +00001039 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001040 // in a Construct, C/C++, predetermined, p.4]
1041 // Static data members are shared.
1042 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1043 // in a Construct, C/C++, predetermined, p.7]
1044 // Variables with static storage duration that are declared in a scope
1045 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001046 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001047 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001048 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001049 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001050 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001051
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001052 DVar.CKind = OMPC_shared;
1053 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 }
1055
1056 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00001057 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1058 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001059 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1060 // in a Construct, C/C++, predetermined, p.6]
1061 // Variables with const qualified type having no mutable member are
1062 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001063 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001064 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001065 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1066 if (auto *CTD = CTSD->getSpecializedTemplate())
1067 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001068 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001069 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1070 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001071 // Variables with const-qualified type having no mutable member may be
1072 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001073 DSAVarData DVarTemp = hasDSA(
1074 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1075 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001076 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
Alexey Bataev9a757382018-02-16 19:16:54 +00001077 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001078
Alexey Bataev758e55e2013-09-06 18:03:48 +00001079 DVar.CKind = OMPC_shared;
1080 return DVar;
1081 }
1082
Alexey Bataev758e55e2013-09-06 18:03:48 +00001083 // Explicitly specified attributes and local variables with predetermined
1084 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001085 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001086 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001087 if (FromParent && I != EndI)
1088 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001089 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001090 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001091 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001092 DVar.CKind = I->SharingMap[D].Attributes;
1093 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001094 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001095 }
1096
1097 return DVar;
1098}
1099
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001100DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1101 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 if (isStackEmpty()) {
1103 StackTy::reverse_iterator I;
1104 return getDSA(I, D);
1105 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001106 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001107 auto StartI = Stack.back().first.rbegin();
1108 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001109 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001110 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001111 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001112}
1113
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001114DSAStackTy::DSAVarData
1115DSAStackTy::hasDSA(ValueDecl *D,
1116 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1117 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1118 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001119 if (isStackEmpty())
1120 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001121 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001122 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001123 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001124 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001125 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001126 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001127 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001128 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001129 auto NewI = I;
1130 DSAVarData DVar = getDSA(NewI, D);
1131 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001132 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001133 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001134 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001135}
1136
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001137DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1138 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1139 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1140 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001141 if (isStackEmpty())
1142 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001143 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001144 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001145 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001146 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001147 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001148 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001149 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001150 auto NewI = StartI;
1151 DSAVarData DVar = getDSA(NewI, D);
1152 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001153}
1154
Alexey Bataevaac108a2015-06-23 04:51:00 +00001155bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001156 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001157 unsigned Level, bool NotLastprivate) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001158 if (isStackEmpty())
1159 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001160 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001161 auto StartI = Stack.back().first.begin();
1162 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001163 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001164 return false;
1165 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001166 return (StartI->SharingMap.count(D) > 0) &&
1167 StartI->SharingMap[D].RefExpr.getPointer() &&
1168 CPred(StartI->SharingMap[D].Attributes) &&
1169 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001170}
1171
Samuel Antao4be30e92015-10-02 17:14:03 +00001172bool DSAStackTy::hasExplicitDirective(
1173 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1174 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001175 if (isStackEmpty())
1176 return false;
1177 auto StartI = Stack.back().first.begin();
1178 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001179 if (std::distance(StartI, EndI) <= (int)Level)
1180 return false;
1181 std::advance(StartI, Level);
1182 return DPred(StartI->Directive);
1183}
1184
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001185bool DSAStackTy::hasDirective(
1186 const llvm::function_ref<bool(OpenMPDirectiveKind,
1187 const DeclarationNameInfo &, SourceLocation)>
1188 &DPred,
1189 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001190 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001191 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001192 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001193 auto StartI = std::next(Stack.back().first.rbegin());
1194 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001195 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001196 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001197 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1198 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1199 return true;
1200 }
1201 return false;
1202}
1203
Alexey Bataev758e55e2013-09-06 18:03:48 +00001204void Sema::InitDataSharingAttributesStack() {
1205 VarDataSharingAttributesStack = new DSAStackTy(*this);
1206}
1207
1208#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1209
Alexey Bataev4b465392017-04-26 15:06:24 +00001210void Sema::pushOpenMPFunctionRegion() {
1211 DSAStack->pushFunction();
1212}
1213
1214void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1215 DSAStack->popFunction(OldFSI);
1216}
1217
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001218bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001219 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1220
1221 auto &Ctx = getASTContext();
1222 bool IsByRef = true;
1223
1224 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001225 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001226 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001227
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001228 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001229 // This table summarizes how a given variable should be passed to the device
1230 // given its type and the clauses where it appears. This table is based on
1231 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1232 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1233 //
1234 // =========================================================================
1235 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1236 // | |(tofrom:scalar)| | pvt | | | |
1237 // =========================================================================
1238 // | scl | | | | - | | bycopy|
1239 // | scl | | - | x | - | - | bycopy|
1240 // | scl | | x | - | - | - | null |
1241 // | scl | x | | | - | | byref |
1242 // | scl | x | - | x | - | - | bycopy|
1243 // | scl | x | x | - | - | - | null |
1244 // | scl | | - | - | - | x | byref |
1245 // | scl | x | - | - | - | x | byref |
1246 //
1247 // | agg | n.a. | | | - | | byref |
1248 // | agg | n.a. | - | x | - | - | byref |
1249 // | agg | n.a. | x | - | - | - | null |
1250 // | agg | n.a. | - | - | - | x | byref |
1251 // | agg | n.a. | - | - | - | x[] | byref |
1252 //
1253 // | ptr | n.a. | | | - | | bycopy|
1254 // | ptr | n.a. | - | x | - | - | bycopy|
1255 // | ptr | n.a. | x | - | - | - | null |
1256 // | ptr | n.a. | - | - | - | x | byref |
1257 // | ptr | n.a. | - | - | - | x[] | bycopy|
1258 // | ptr | n.a. | - | - | x | | bycopy|
1259 // | ptr | n.a. | - | - | x | x | bycopy|
1260 // | ptr | n.a. | - | - | x | x[] | bycopy|
1261 // =========================================================================
1262 // Legend:
1263 // scl - scalar
1264 // ptr - pointer
1265 // agg - aggregate
1266 // x - applies
1267 // - - invalid in this combination
1268 // [] - mapped with an array section
1269 // byref - should be mapped by reference
1270 // byval - should be mapped by value
1271 // null - initialize a local variable to null on the device
1272 //
1273 // Observations:
1274 // - All scalar declarations that show up in a map clause have to be passed
1275 // by reference, because they may have been mapped in the enclosing data
1276 // environment.
1277 // - If the scalar value does not fit the size of uintptr, it has to be
1278 // passed by reference, regardless the result in the table above.
1279 // - For pointers mapped by value that have either an implicit map or an
1280 // array section, the runtime library may pass the NULL value to the
1281 // device instead of the value passed to it by the compiler.
1282
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001283 if (Ty->isReferenceType())
1284 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001285
1286 // Locate map clauses and see if the variable being captured is referred to
1287 // in any of those clauses. Here we only care about variables, not fields,
1288 // because fields are part of aggregates.
1289 bool IsVariableUsedInMapClause = false;
1290 bool IsVariableAssociatedWithSection = false;
1291
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001292 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1293 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001294 MapExprComponents,
1295 OpenMPClauseKind WhereFoundClauseKind) {
1296 // Only the map clause information influences how a variable is
1297 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001298 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001299 if (WhereFoundClauseKind != OMPC_map)
1300 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001301
1302 auto EI = MapExprComponents.rbegin();
1303 auto EE = MapExprComponents.rend();
1304
1305 assert(EI != EE && "Invalid map expression!");
1306
1307 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1308 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1309
1310 ++EI;
1311 if (EI == EE)
1312 return false;
1313
1314 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1315 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1316 isa<MemberExpr>(EI->getAssociatedExpression())) {
1317 IsVariableAssociatedWithSection = true;
1318 // There is nothing more we need to know about this variable.
1319 return true;
1320 }
1321
1322 // Keep looking for more map info.
1323 return false;
1324 });
1325
1326 if (IsVariableUsedInMapClause) {
1327 // If variable is identified in a map clause it is always captured by
1328 // reference except if it is a pointer that is dereferenced somehow.
1329 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1330 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001331 // By default, all the data that has a scalar type is mapped by copy
1332 // (except for reduction variables).
1333 IsByRef =
1334 !Ty->isScalarType() ||
1335 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1336 DSAStack->hasExplicitDSA(
1337 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001338 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001339 }
1340
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001341 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001342 IsByRef =
1343 !DSAStack->hasExplicitDSA(
1344 D,
1345 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1346 Level, /*NotLastprivate=*/true) &&
1347 // If the variable is artificial and must be captured by value - try to
1348 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001349 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1350 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001351 }
1352
Samuel Antao86ace552016-04-27 22:40:57 +00001353 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001354 // and alignment, because the runtime library only deals with uintptr types.
1355 // If it does not fit the uintptr size, we need to pass the data by reference
1356 // instead.
1357 if (!IsByRef &&
1358 (Ctx.getTypeSizeInChars(Ty) >
1359 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001360 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001361 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001362 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001363
1364 return IsByRef;
1365}
1366
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001367unsigned Sema::getOpenMPNestingLevel() const {
1368 assert(getLangOpts().OpenMP);
1369 return DSAStack->getNestingLevel();
1370}
1371
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001372bool Sema::isInOpenMPTargetExecutionDirective() const {
1373 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1374 !DSAStack->isClauseParsingMode()) ||
1375 DSAStack->hasDirective(
1376 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1377 SourceLocation) -> bool {
1378 return isOpenMPTargetExecutionDirective(K);
1379 },
1380 false);
1381}
1382
Alexey Bataev90c228f2016-02-08 09:29:13 +00001383VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001384 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001385 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001386
1387 // If we are attempting to capture a global variable in a directive with
1388 // 'target' we return true so that this global is also mapped to the device.
1389 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001390 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001391 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) {
1392 // If the declaration is enclosed in a 'declare target' directive,
1393 // then it should not be captured.
1394 //
1395 for (const auto *Var = VD->getMostRecentDecl(); Var;
1396 Var = Var->getPreviousDecl())
1397 if (Var->hasAttr<OMPDeclareTargetDeclAttr>())
1398 return nullptr;
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001399 return VD;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001400 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001401
Alexey Bataev48977c32015-08-04 08:10:48 +00001402 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1403 (!DSAStack->isClauseParsingMode() ||
1404 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001405 auto &&Info = DSAStack->isLoopControlVariable(D);
1406 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001407 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001408 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001409 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001410 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001411 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001412 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001413 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001414 DVarPrivate = DSAStack->hasDSA(
1415 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1416 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001417 if (DVarPrivate.CKind != OMPC_unknown)
1418 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001419 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001420 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001421}
1422
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001423void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1424 unsigned Level) const {
1425 SmallVector<OpenMPDirectiveKind, 4> Regions;
1426 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1427 FunctionScopesIndex -= Regions.size();
1428}
1429
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001430bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001431 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1432 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001433 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1434 Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001435 (DSAStack->isClauseParsingMode() &&
1436 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001437 // Consider taskgroup reduction descriptor variable a private to avoid
1438 // possible capture in the region.
1439 (DSAStack->hasExplicitDirective(
1440 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1441 Level) &&
1442 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001443}
1444
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001445void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1446 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1447 D = getCanonicalDecl(D);
1448 OpenMPClauseKind OMPC = OMPC_unknown;
1449 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1450 const unsigned NewLevel = I - 1;
1451 if (DSAStack->hasExplicitDSA(D,
1452 [&OMPC](const OpenMPClauseKind K) {
1453 if (isOpenMPPrivate(K)) {
1454 OMPC = K;
1455 return true;
1456 }
1457 return false;
1458 },
1459 NewLevel))
1460 break;
1461 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1462 D, NewLevel,
1463 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1464 OpenMPClauseKind) { return true; })) {
1465 OMPC = OMPC_map;
1466 break;
1467 }
1468 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1469 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001470 OMPC = OMPC_map;
1471 if (D->getType()->isScalarType() &&
1472 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1473 DefaultMapAttributes::DMA_tofrom_scalar)
1474 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001475 break;
1476 }
1477 }
1478 if (OMPC != OMPC_unknown)
1479 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1480}
1481
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001482bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001483 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1484 // Return true if the current level is no longer enclosed in a target region.
1485
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001486 auto *VD = dyn_cast<VarDecl>(D);
1487 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001488 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1489 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001490}
1491
Alexey Bataeved09d242014-05-28 05:53:51 +00001492void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001493
1494void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1495 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001496 Scope *CurScope, SourceLocation Loc) {
1497 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001498 PushExpressionEvaluationContext(
1499 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001500}
1501
Alexey Bataevaac108a2015-06-23 04:51:00 +00001502void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1503 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001504}
1505
Alexey Bataevaac108a2015-06-23 04:51:00 +00001506void Sema::EndOpenMPClause() {
1507 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001508}
1509
Alexey Bataev758e55e2013-09-06 18:03:48 +00001510void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001511 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1512 // A variable of class type (or array thereof) that appears in a lastprivate
1513 // clause requires an accessible, unambiguous default constructor for the
1514 // class type, unless the list item is also specified in a firstprivate
1515 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001516 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001517 for (auto *C : D->clauses()) {
1518 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1519 SmallVector<Expr *, 8> PrivateCopies;
1520 for (auto *DE : Clause->varlists()) {
1521 if (DE->isValueDependent() || DE->isTypeDependent()) {
1522 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001523 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001524 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001525 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001526 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1527 QualType Type = VD->getType().getNonReferenceType();
1528 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001529 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001530 // Generate helper private variable and initialize it with the
1531 // default value. The address of the original variable is replaced
1532 // by the address of the new private variable in CodeGen. This new
1533 // variable is not added to IdResolver, so the code in the OpenMP
1534 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001535 auto *VDPrivate = buildVarDecl(
1536 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001537 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001538 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001539 if (VDPrivate->isInvalidDecl())
1540 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001541 PrivateCopies.push_back(buildDeclRefExpr(
1542 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001543 } else {
1544 // The variable is also a firstprivate, so initialization sequence
1545 // for private copy is generated already.
1546 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001547 }
1548 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001549 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001550 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001551 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001552 }
1553 }
1554 }
1555
Alexey Bataev758e55e2013-09-06 18:03:48 +00001556 DSAStack->pop();
1557 DiscardCleanupsInEvaluationContext();
1558 PopExpressionEvaluationContext();
1559}
1560
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001561static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1562 Expr *NumIterations, Sema &SemaRef,
1563 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001564
Alexey Bataeva769e072013-03-22 06:34:35 +00001565namespace {
1566
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001567class VarDeclFilterCCC : public CorrectionCandidateCallback {
1568private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001569 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001570
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001571public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001572 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001573 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001574 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001575 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001576 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001577 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1578 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001579 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001580 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001581 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001582};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001583
1584class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1585private:
1586 Sema &SemaRef;
1587
1588public:
1589 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1590 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1591 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001592 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001593 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1594 SemaRef.getCurScope());
1595 }
1596 return false;
1597 }
1598};
1599
Alexey Bataeved09d242014-05-28 05:53:51 +00001600} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001601
1602ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1603 CXXScopeSpec &ScopeSpec,
1604 const DeclarationNameInfo &Id) {
1605 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1606 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1607
1608 if (Lookup.isAmbiguous())
1609 return ExprError();
1610
1611 VarDecl *VD;
1612 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001613 if (TypoCorrection Corrected = CorrectTypo(
1614 Id, LookupOrdinaryName, CurScope, nullptr,
1615 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001616 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001617 PDiag(Lookup.empty()
1618 ? diag::err_undeclared_var_use_suggest
1619 : diag::err_omp_expected_var_arg_suggest)
1620 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001621 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001622 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001623 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1624 : diag::err_omp_expected_var_arg)
1625 << Id.getName();
1626 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001627 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001628 } else {
1629 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001630 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001631 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1632 return ExprError();
1633 }
1634 }
1635 Lookup.suppressDiagnostics();
1636
1637 // OpenMP [2.9.2, Syntax, C/C++]
1638 // Variables must be file-scope, namespace-scope, or static block-scope.
1639 if (!VD->hasGlobalStorage()) {
1640 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001641 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1642 bool IsDecl =
1643 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001644 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001645 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1646 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001647 return ExprError();
1648 }
1649
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001650 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001651 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001652 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1653 // A threadprivate directive for file-scope variables must appear outside
1654 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001655 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1656 !getCurLexicalContext()->isTranslationUnit()) {
1657 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001658 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1659 bool IsDecl =
1660 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1661 Diag(VD->getLocation(),
1662 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1663 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001664 return ExprError();
1665 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001666 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1667 // A threadprivate directive for static class member variables must appear
1668 // in the class definition, in the same scope in which the member
1669 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001670 if (CanonicalVD->isStaticDataMember() &&
1671 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1672 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001673 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1674 bool IsDecl =
1675 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1676 Diag(VD->getLocation(),
1677 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1678 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001679 return ExprError();
1680 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001681 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1682 // A threadprivate directive for namespace-scope variables must appear
1683 // outside any definition or declaration other than the namespace
1684 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001685 if (CanonicalVD->getDeclContext()->isNamespace() &&
1686 (!getCurLexicalContext()->isFileContext() ||
1687 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1688 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001689 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1690 bool IsDecl =
1691 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1692 Diag(VD->getLocation(),
1693 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1694 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001695 return ExprError();
1696 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001697 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1698 // A threadprivate directive for static block-scope variables must appear
1699 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001700 if (CanonicalVD->isStaticLocal() && CurScope &&
1701 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001702 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001703 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1704 bool IsDecl =
1705 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1706 Diag(VD->getLocation(),
1707 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1708 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001709 return ExprError();
1710 }
1711
1712 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1713 // A threadprivate directive must lexically precede all references to any
1714 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001715 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001716 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001717 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001718 return ExprError();
1719 }
1720
1721 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001722 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1723 SourceLocation(), VD,
1724 /*RefersToEnclosingVariableOrCapture=*/false,
1725 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001726}
1727
Alexey Bataeved09d242014-05-28 05:53:51 +00001728Sema::DeclGroupPtrTy
1729Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1730 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001731 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001732 CurContext->addDecl(D);
1733 return DeclGroupPtrTy::make(DeclGroupRef(D));
1734 }
David Blaikie0403cb12016-01-15 23:43:25 +00001735 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001736}
1737
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001738namespace {
1739class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1740 Sema &SemaRef;
1741
1742public:
1743 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001744 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001745 if (VD->hasLocalStorage()) {
1746 SemaRef.Diag(E->getLocStart(),
1747 diag::err_omp_local_var_in_threadprivate_init)
1748 << E->getSourceRange();
1749 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1750 << VD << VD->getSourceRange();
1751 return true;
1752 }
1753 }
1754 return false;
1755 }
1756 bool VisitStmt(const Stmt *S) {
1757 for (auto Child : S->children()) {
1758 if (Child && Visit(Child))
1759 return true;
1760 }
1761 return false;
1762 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001763 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001764};
1765} // namespace
1766
Alexey Bataeved09d242014-05-28 05:53:51 +00001767OMPThreadPrivateDecl *
1768Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001769 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001770 for (auto &RefExpr : VarList) {
1771 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001772 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1773 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001774
Alexey Bataev376b4a42016-02-09 09:41:09 +00001775 // Mark variable as used.
1776 VD->setReferenced();
1777 VD->markUsed(Context);
1778
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001779 QualType QType = VD->getType();
1780 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1781 // It will be analyzed later.
1782 Vars.push_back(DE);
1783 continue;
1784 }
1785
Alexey Bataeva769e072013-03-22 06:34:35 +00001786 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1787 // A threadprivate variable must not have an incomplete type.
1788 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001789 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001790 continue;
1791 }
1792
1793 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1794 // A threadprivate variable must not have a reference type.
1795 if (VD->getType()->isReferenceType()) {
1796 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001797 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1798 bool IsDecl =
1799 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1800 Diag(VD->getLocation(),
1801 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1802 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001803 continue;
1804 }
1805
Samuel Antaof8b50122015-07-13 22:54:53 +00001806 // Check if this is a TLS variable. If TLS is not being supported, produce
1807 // the corresponding diagnostic.
1808 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1809 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1810 getLangOpts().OpenMPUseTLS &&
1811 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001812 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1813 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001814 Diag(ILoc, diag::err_omp_var_thread_local)
1815 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001816 bool IsDecl =
1817 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1818 Diag(VD->getLocation(),
1819 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1820 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001821 continue;
1822 }
1823
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001824 // Check if initial value of threadprivate variable reference variable with
1825 // local storage (it is not supported by runtime).
1826 if (auto Init = VD->getAnyInitializer()) {
1827 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001828 if (Checker.Visit(Init))
1829 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001830 }
1831
Alexey Bataeved09d242014-05-28 05:53:51 +00001832 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001833 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001834 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1835 Context, SourceRange(Loc, Loc)));
1836 if (auto *ML = Context.getASTMutationListener())
1837 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001838 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001839 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001840 if (!Vars.empty()) {
1841 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1842 Vars);
1843 D->setAccess(AS_public);
1844 }
1845 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001846}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001847
Alexey Bataev7ff55242014-06-19 09:13:45 +00001848static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001849 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001850 bool IsLoopIterVar = false) {
1851 if (DVar.RefExpr) {
1852 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1853 << getOpenMPClauseName(DVar.CKind);
1854 return;
1855 }
1856 enum {
1857 PDSA_StaticMemberShared,
1858 PDSA_StaticLocalVarShared,
1859 PDSA_LoopIterVarPrivate,
1860 PDSA_LoopIterVarLinear,
1861 PDSA_LoopIterVarLastprivate,
1862 PDSA_ConstVarShared,
1863 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001864 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001865 PDSA_LocalVarPrivate,
1866 PDSA_Implicit
1867 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001868 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001869 auto ReportLoc = D->getLocation();
1870 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001871 if (IsLoopIterVar) {
1872 if (DVar.CKind == OMPC_private)
1873 Reason = PDSA_LoopIterVarPrivate;
1874 else if (DVar.CKind == OMPC_lastprivate)
1875 Reason = PDSA_LoopIterVarLastprivate;
1876 else
1877 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001878 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1879 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001880 Reason = PDSA_TaskVarFirstprivate;
1881 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001882 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001883 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001884 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001885 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001886 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001887 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001888 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001889 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001890 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001891 ReportHint = true;
1892 Reason = PDSA_LocalVarPrivate;
1893 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001894 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001895 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001896 << Reason << ReportHint
1897 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1898 } else if (DVar.ImplicitDSALoc.isValid()) {
1899 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1900 << getOpenMPClauseName(DVar.CKind);
1901 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001902}
1903
Alexey Bataev758e55e2013-09-06 18:03:48 +00001904namespace {
1905class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1906 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001907 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001908 bool ErrorFound;
1909 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001910 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001911 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001912 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001913 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001914
Alexey Bataev758e55e2013-09-06 18:03:48 +00001915public:
1916 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001917 if (E->isTypeDependent() || E->isValueDependent() ||
1918 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1919 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001920 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001921 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001922 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001923 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001924 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001925
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001926 auto DVar = Stack->getTopDSA(VD, false);
1927 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001928 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001929 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001930
Alexey Bataevafe50572017-10-06 17:00:28 +00001931 // Skip internally declared static variables.
1932 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1933 return;
1934
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001935 auto ELoc = E->getExprLoc();
1936 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001937 // The default(none) clause requires that each variable that is referenced
1938 // in the construct, and does not have a predetermined data-sharing
1939 // attribute, must have its data-sharing attribute explicitly determined
1940 // by being listed in a data-sharing attribute clause.
1941 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001942 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001943 VarsWithInheritedDSA.count(VD) == 0) {
1944 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001945 return;
1946 }
1947
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001948 if (isOpenMPTargetExecutionDirective(DKind) &&
1949 !Stack->isLoopControlVariable(VD).first) {
1950 if (!Stack->checkMappableExprComponentListsForDecl(
1951 VD, /*CurrentRegionOnly=*/true,
1952 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1953 StackComponents,
1954 OpenMPClauseKind) {
1955 // Variable is used if it has been marked as an array, array
1956 // section or the variable iself.
1957 return StackComponents.size() == 1 ||
1958 std::all_of(
1959 std::next(StackComponents.rbegin()),
1960 StackComponents.rend(),
1961 [](const OMPClauseMappableExprCommon::
1962 MappableComponent &MC) {
1963 return MC.getAssociatedDeclaration() ==
1964 nullptr &&
1965 (isa<OMPArraySectionExpr>(
1966 MC.getAssociatedExpression()) ||
1967 isa<ArraySubscriptExpr>(
1968 MC.getAssociatedExpression()));
1969 });
1970 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001971 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001972 // By default lambdas are captured as firstprivates.
1973 if (const auto *RD =
1974 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001975 IsFirstprivate = RD->isLambda();
1976 IsFirstprivate =
1977 IsFirstprivate ||
1978 (VD->getType().getNonReferenceType()->isScalarType() &&
1979 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1980 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001981 ImplicitFirstprivate.emplace_back(E);
1982 else
1983 ImplicitMap.emplace_back(E);
1984 return;
1985 }
1986 }
1987
Alexey Bataev758e55e2013-09-06 18:03:48 +00001988 // OpenMP [2.9.3.6, Restrictions, p.2]
1989 // A list item that appears in a reduction clause of the innermost
1990 // enclosing worksharing or parallel construct may not be accessed in an
1991 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001992 DVar = Stack->hasInnermostDSA(
1993 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1994 [](OpenMPDirectiveKind K) -> bool {
1995 return isOpenMPParallelDirective(K) ||
1996 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1997 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001998 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001999 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002000 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002001 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2002 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002003 return;
2004 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002005
2006 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002007 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002008 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2009 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002010 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002011 }
2012 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002013 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002014 if (E->isTypeDependent() || E->isValueDependent() ||
2015 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2016 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002017 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002018 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002019 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002020 if (!FD)
2021 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002022 auto DVar = Stack->getTopDSA(FD, false);
2023 // Check if the variable has explicit DSA set and stop analysis if it
2024 // so.
2025 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2026 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002027
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002028 if (isOpenMPTargetExecutionDirective(DKind) &&
2029 !Stack->isLoopControlVariable(FD).first &&
2030 !Stack->checkMappableExprComponentListsForDecl(
2031 FD, /*CurrentRegionOnly=*/true,
2032 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2033 StackComponents,
2034 OpenMPClauseKind) {
2035 return isa<CXXThisExpr>(
2036 cast<MemberExpr>(
2037 StackComponents.back().getAssociatedExpression())
2038 ->getBase()
2039 ->IgnoreParens());
2040 })) {
2041 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2042 // A bit-field cannot appear in a map clause.
2043 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002044 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002045 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002046 ImplicitMap.emplace_back(E);
2047 return;
2048 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002049
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002050 auto ELoc = E->getExprLoc();
2051 // OpenMP [2.9.3.6, Restrictions, p.2]
2052 // A list item that appears in a reduction clause of the innermost
2053 // enclosing worksharing or parallel construct may not be accessed in
2054 // an explicit task.
2055 DVar = Stack->hasInnermostDSA(
2056 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2057 [](OpenMPDirectiveKind K) -> bool {
2058 return isOpenMPParallelDirective(K) ||
2059 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2060 },
2061 /*FromParent=*/true);
2062 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2063 ErrorFound = true;
2064 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2065 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
2066 return;
2067 }
2068
2069 // Define implicit data-sharing attributes for task.
2070 DVar = Stack->getImplicitDSA(FD, false);
2071 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2072 !Stack->isLoopControlVariable(FD).first)
2073 ImplicitFirstprivate.push_back(E);
2074 return;
2075 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002076 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002077 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002078 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2079 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002080 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002081 auto *VD = cast<ValueDecl>(
2082 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2083 if (!Stack->checkMappableExprComponentListsForDecl(
2084 VD, /*CurrentRegionOnly=*/true,
2085 [&CurComponents](
2086 OMPClauseMappableExprCommon::MappableExprComponentListRef
2087 StackComponents,
2088 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002089 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002090 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002091 for (const auto &SC : llvm::reverse(StackComponents)) {
2092 // Do both expressions have the same kind?
2093 if (CCI->getAssociatedExpression()->getStmtClass() !=
2094 SC.getAssociatedExpression()->getStmtClass())
2095 if (!(isa<OMPArraySectionExpr>(
2096 SC.getAssociatedExpression()) &&
2097 isa<ArraySubscriptExpr>(
2098 CCI->getAssociatedExpression())))
2099 return false;
2100
2101 Decl *CCD = CCI->getAssociatedDeclaration();
2102 Decl *SCD = SC.getAssociatedDeclaration();
2103 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2104 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2105 if (SCD != CCD)
2106 return false;
2107 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002108 if (CCI == CCE)
2109 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002110 }
2111 return true;
2112 })) {
2113 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002114 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002115 } else
2116 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002117 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002118 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002119 for (auto *C : S->clauses()) {
2120 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002121 // for task|target directives.
2122 // Skip analysis of arguments of implicitly defined map clause for target
2123 // directives.
2124 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2125 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002126 for (auto *CC : C->children()) {
2127 if (CC)
2128 Visit(CC);
2129 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002130 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002131 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002132 }
2133 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002134 for (auto *C : S->children()) {
2135 if (C && !isa<OMPExecutableDirective>(C))
2136 Visit(C);
2137 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002138 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002139
2140 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002141 ArrayRef<Expr *> getImplicitFirstprivate() const {
2142 return ImplicitFirstprivate;
2143 }
2144 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002145 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002146 return VarsWithInheritedDSA;
2147 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002148
Alexey Bataev7ff55242014-06-19 09:13:45 +00002149 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2150 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002151};
Alexey Bataeved09d242014-05-28 05:53:51 +00002152} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002153
Alexey Bataevbae9a792014-06-27 10:37:06 +00002154void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002155 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002156 case OMPD_parallel:
2157 case OMPD_parallel_for:
2158 case OMPD_parallel_for_simd:
2159 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002160 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002161 case OMPD_teams_distribute:
2162 case OMPD_teams_distribute_simd: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002163 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002164 QualType KmpInt32PtrTy =
2165 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002166 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002167 std::make_pair(".global_tid.", KmpInt32PtrTy),
2168 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2169 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002170 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002171 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2172 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002173 break;
2174 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002175 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002176 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002177 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002178 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002179 case OMPD_target_teams_distribute:
2180 case OMPD_target_teams_distribute_simd: {
Alexey Bataev8451efa2018-01-15 19:06:12 +00002181 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2182 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2183 FunctionProtoType::ExtProtoInfo EPI;
2184 EPI.Variadic = true;
2185 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2186 Sema::CapturedParamNameType Params[] = {
2187 std::make_pair(".global_tid.", KmpInt32Ty),
2188 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2189 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2190 std::make_pair(".copy_fn.",
2191 Context.getPointerType(CopyFnType).withConst()),
2192 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2193 std::make_pair(StringRef(), QualType()) // __context with shared vars
2194 };
2195 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2196 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002197 // Mark this captured region as inlined, because we don't use outlined
2198 // function directly.
2199 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2200 AlwaysInlineAttr::CreateImplicit(
2201 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002202 Sema::CapturedParamNameType ParamsTarget[] = {
2203 std::make_pair(StringRef(), QualType()) // __context with shared vars
2204 };
2205 // Start a captured region for 'target' with no implicit parameters.
2206 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2207 ParamsTarget);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002208 QualType KmpInt32PtrTy =
2209 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002210 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002211 std::make_pair(".global_tid.", KmpInt32PtrTy),
2212 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2213 std::make_pair(StringRef(), QualType()) // __context with shared vars
2214 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002215 // Start a captured region for 'teams' or 'parallel'. Both regions have
2216 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002217 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002218 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002219 break;
2220 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002221 case OMPD_target:
2222 case OMPD_target_simd: {
2223 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2224 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2225 FunctionProtoType::ExtProtoInfo EPI;
2226 EPI.Variadic = true;
2227 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2228 Sema::CapturedParamNameType Params[] = {
2229 std::make_pair(".global_tid.", KmpInt32Ty),
2230 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2231 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2232 std::make_pair(".copy_fn.",
2233 Context.getPointerType(CopyFnType).withConst()),
2234 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2235 std::make_pair(StringRef(), QualType()) // __context with shared vars
2236 };
2237 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2238 Params);
2239 // Mark this captured region as inlined, because we don't use outlined
2240 // function directly.
2241 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2242 AlwaysInlineAttr::CreateImplicit(
2243 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2244 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2245 std::make_pair(StringRef(), QualType()));
2246 break;
2247 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002248 case OMPD_simd:
2249 case OMPD_for:
2250 case OMPD_for_simd:
2251 case OMPD_sections:
2252 case OMPD_section:
2253 case OMPD_single:
2254 case OMPD_master:
2255 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002256 case OMPD_taskgroup:
2257 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002258 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002259 case OMPD_ordered:
2260 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002261 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002262 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002263 std::make_pair(StringRef(), QualType()) // __context with shared vars
2264 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002265 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2266 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002267 break;
2268 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002269 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002270 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002271 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2272 FunctionProtoType::ExtProtoInfo EPI;
2273 EPI.Variadic = true;
2274 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002275 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002276 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002277 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2278 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2279 std::make_pair(".copy_fn.",
2280 Context.getPointerType(CopyFnType).withConst()),
2281 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002282 std::make_pair(StringRef(), QualType()) // __context with shared vars
2283 };
2284 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2285 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002286 // Mark this captured region as inlined, because we don't use outlined
2287 // function directly.
2288 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2289 AlwaysInlineAttr::CreateImplicit(
2290 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002291 break;
2292 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002293 case OMPD_taskloop:
2294 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002295 QualType KmpInt32Ty =
2296 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2297 QualType KmpUInt64Ty =
2298 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2299 QualType KmpInt64Ty =
2300 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2301 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2302 FunctionProtoType::ExtProtoInfo EPI;
2303 EPI.Variadic = true;
2304 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002305 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002306 std::make_pair(".global_tid.", KmpInt32Ty),
2307 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2308 std::make_pair(".privates.",
2309 Context.VoidPtrTy.withConst().withRestrict()),
2310 std::make_pair(
2311 ".copy_fn.",
2312 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2313 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2314 std::make_pair(".lb.", KmpUInt64Ty),
2315 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2316 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002317 std::make_pair(".reductions.",
2318 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002319 std::make_pair(StringRef(), QualType()) // __context with shared vars
2320 };
2321 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2322 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002323 // Mark this captured region as inlined, because we don't use outlined
2324 // function directly.
2325 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2326 AlwaysInlineAttr::CreateImplicit(
2327 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002328 break;
2329 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002330 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002331 case OMPD_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002332 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2333 QualType KmpInt32PtrTy =
2334 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2335 Sema::CapturedParamNameType Params[] = {
2336 std::make_pair(".global_tid.", KmpInt32PtrTy),
2337 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2338 std::make_pair(".previous.lb.", Context.getSizeType()),
2339 std::make_pair(".previous.ub.", Context.getSizeType()),
2340 std::make_pair(StringRef(), QualType()) // __context with shared vars
2341 };
2342 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2343 Params);
2344 break;
2345 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002346 case OMPD_target_teams_distribute_parallel_for:
2347 case OMPD_target_teams_distribute_parallel_for_simd: {
Carlo Bertolli52978c32018-01-03 21:12:44 +00002348 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2349 QualType KmpInt32PtrTy =
2350 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2351
Alexey Bataev8451efa2018-01-15 19:06:12 +00002352 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2353 FunctionProtoType::ExtProtoInfo EPI;
2354 EPI.Variadic = true;
2355 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2356 Sema::CapturedParamNameType Params[] = {
2357 std::make_pair(".global_tid.", KmpInt32Ty),
2358 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2359 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2360 std::make_pair(".copy_fn.",
2361 Context.getPointerType(CopyFnType).withConst()),
2362 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2363 std::make_pair(StringRef(), QualType()) // __context with shared vars
2364 };
2365 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2366 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002367 // Mark this captured region as inlined, because we don't use outlined
2368 // function directly.
2369 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2370 AlwaysInlineAttr::CreateImplicit(
2371 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002372 Sema::CapturedParamNameType ParamsTarget[] = {
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 ParamsTarget);
2378
2379 Sema::CapturedParamNameType ParamsTeams[] = {
2380 std::make_pair(".global_tid.", KmpInt32PtrTy),
2381 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2382 std::make_pair(StringRef(), QualType()) // __context with shared vars
2383 };
2384 // Start a captured region for 'target' with no implicit parameters.
2385 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2386 ParamsTeams);
2387
2388 Sema::CapturedParamNameType ParamsParallel[] = {
2389 std::make_pair(".global_tid.", KmpInt32PtrTy),
2390 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2391 std::make_pair(".previous.lb.", Context.getSizeType()),
2392 std::make_pair(".previous.ub.", Context.getSizeType()),
2393 std::make_pair(StringRef(), QualType()) // __context with shared vars
2394 };
2395 // Start a captured region for 'teams' or 'parallel'. Both regions have
2396 // the same implicit parameters.
2397 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2398 ParamsParallel);
2399 break;
2400 }
2401
Alexey Bataev46506272017-12-05 17:41:34 +00002402 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002403 case OMPD_teams_distribute_parallel_for_simd: {
Carlo Bertolli62fae152017-11-20 20:46:39 +00002404 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2405 QualType KmpInt32PtrTy =
2406 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2407
2408 Sema::CapturedParamNameType ParamsTeams[] = {
2409 std::make_pair(".global_tid.", KmpInt32PtrTy),
2410 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2411 std::make_pair(StringRef(), QualType()) // __context with shared vars
2412 };
2413 // Start a captured region for 'target' with no implicit parameters.
2414 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2415 ParamsTeams);
2416
2417 Sema::CapturedParamNameType ParamsParallel[] = {
2418 std::make_pair(".global_tid.", KmpInt32PtrTy),
2419 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2420 std::make_pair(".previous.lb.", Context.getSizeType()),
2421 std::make_pair(".previous.ub.", Context.getSizeType()),
2422 std::make_pair(StringRef(), QualType()) // __context with shared vars
2423 };
2424 // Start a captured region for 'teams' or 'parallel'. Both regions have
2425 // the same implicit parameters.
2426 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2427 ParamsParallel);
2428 break;
2429 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002430 case OMPD_target_update:
2431 case OMPD_target_enter_data:
2432 case OMPD_target_exit_data: {
2433 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2434 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2435 FunctionProtoType::ExtProtoInfo EPI;
2436 EPI.Variadic = true;
2437 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2438 Sema::CapturedParamNameType Params[] = {
2439 std::make_pair(".global_tid.", KmpInt32Ty),
2440 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2441 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2442 std::make_pair(".copy_fn.",
2443 Context.getPointerType(CopyFnType).withConst()),
2444 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2445 std::make_pair(StringRef(), QualType()) // __context with shared vars
2446 };
2447 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2448 Params);
2449 // Mark this captured region as inlined, because we don't use outlined
2450 // function directly.
2451 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2452 AlwaysInlineAttr::CreateImplicit(
2453 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2454 break;
2455 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002456 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002457 case OMPD_taskyield:
2458 case OMPD_barrier:
2459 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002460 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002461 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002462 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002463 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002464 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002465 case OMPD_declare_target:
2466 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002467 llvm_unreachable("OpenMP Directive is not allowed");
2468 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002469 llvm_unreachable("Unknown OpenMP directive");
2470 }
2471}
2472
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002473int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2474 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2475 getOpenMPCaptureRegions(CaptureRegions, DKind);
2476 return CaptureRegions.size();
2477}
2478
Alexey Bataev3392d762016-02-16 11:18:12 +00002479static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002480 Expr *CaptureExpr, bool WithInit,
2481 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002482 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002483 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002484 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002485 QualType Ty = Init->getType();
2486 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002487 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002488 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002489 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002490 Ty = C.getPointerType(Ty);
2491 ExprResult Res =
2492 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2493 if (!Res.isUsable())
2494 return nullptr;
2495 Init = Res.get();
2496 }
Alexey Bataev61205072016-03-02 04:57:40 +00002497 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002498 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002499 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2500 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002501 if (!WithInit)
2502 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002503 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002504 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002505 return CED;
2506}
2507
Alexey Bataev61205072016-03-02 04:57:40 +00002508static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2509 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002510 OMPCapturedExprDecl *CD;
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002511 if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002512 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002513 } else {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002514 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2515 /*AsExpression=*/false);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002516 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002517 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002518 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002519}
2520
Alexey Bataev5a3af132016-03-29 08:58:54 +00002521static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002522 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002523 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002524 OMPCapturedExprDecl *CD = buildCaptureDecl(
2525 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2526 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002527 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2528 CaptureExpr->getExprLoc());
2529 }
2530 ExprResult Res = Ref;
2531 if (!S.getLangOpts().CPlusPlus &&
2532 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002533 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002534 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002535 if (!Res.isUsable())
2536 return ExprError();
2537 }
2538 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002539}
2540
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002541namespace {
2542// OpenMP directives parsed in this section are represented as a
2543// CapturedStatement with an associated statement. If a syntax error
2544// is detected during the parsing of the associated statement, the
2545// compiler must abort processing and close the CapturedStatement.
2546//
2547// Combined directives such as 'target parallel' have more than one
2548// nested CapturedStatements. This RAII ensures that we unwind out
2549// of all the nested CapturedStatements when an error is found.
2550class CaptureRegionUnwinderRAII {
2551private:
2552 Sema &S;
2553 bool &ErrorFound;
2554 OpenMPDirectiveKind DKind;
2555
2556public:
2557 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2558 OpenMPDirectiveKind DKind)
2559 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2560 ~CaptureRegionUnwinderRAII() {
2561 if (ErrorFound) {
2562 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2563 while (--ThisCaptureLevel >= 0)
2564 S.ActOnCapturedRegionError();
2565 }
2566 }
2567};
2568} // namespace
2569
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002570StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2571 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002572 bool ErrorFound = false;
2573 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2574 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002575 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002576 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002577 return StmtError();
2578 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002579
Alexey Bataev2ba67042017-11-28 21:11:44 +00002580 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2581 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002582 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002583 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002584 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002585 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002586 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002587 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002588 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2589 Clause->getClauseKind() == OMPC_in_reduction) {
2590 // Capture taskgroup task_reduction descriptors inside the tasking regions
2591 // with the corresponding in_reduction items.
2592 auto *IRC = cast<OMPInReductionClause>(Clause);
2593 for (auto *E : IRC->taskgroup_descriptors())
2594 if (E)
2595 MarkDeclarationsReferencedInExpr(E);
2596 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002597 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002598 Clause->getClauseKind() == OMPC_copyprivate ||
2599 (getLangOpts().OpenMPUseTLS &&
2600 getASTContext().getTargetInfo().isTLSSupported() &&
2601 Clause->getClauseKind() == OMPC_copyin)) {
2602 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002603 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002604 for (auto *VarRef : Clause->children()) {
2605 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002606 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002607 }
2608 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002609 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002610 } else if (CaptureRegions.size() > 1 ||
2611 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002612 if (auto *C = OMPClauseWithPreInit::get(Clause))
2613 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002614 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2615 if (auto *E = C->getPostUpdateExpr())
2616 MarkDeclarationsReferencedInExpr(E);
2617 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002618 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002619 if (Clause->getClauseKind() == OMPC_schedule)
2620 SC = cast<OMPScheduleClause>(Clause);
2621 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002622 OC = cast<OMPOrderedClause>(Clause);
2623 else if (Clause->getClauseKind() == OMPC_linear)
2624 LCs.push_back(cast<OMPLinearClause>(Clause));
2625 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002626 // OpenMP, 2.7.1 Loop Construct, Restrictions
2627 // The nonmonotonic modifier cannot be specified if an ordered clause is
2628 // specified.
2629 if (SC &&
2630 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2631 SC->getSecondScheduleModifier() ==
2632 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2633 OC) {
2634 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2635 ? SC->getFirstScheduleModifierLoc()
2636 : SC->getSecondScheduleModifierLoc(),
2637 diag::err_omp_schedule_nonmonotonic_ordered)
2638 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2639 ErrorFound = true;
2640 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002641 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2642 for (auto *C : LCs) {
2643 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2644 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2645 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002646 ErrorFound = true;
2647 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002648 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2649 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2650 OC->getNumForLoops()) {
2651 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2652 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2653 ErrorFound = true;
2654 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002655 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002656 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002657 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002658 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002659 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002660 // Mark all variables in private list clauses as used in inner region.
2661 // Required for proper codegen of combined directives.
2662 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002663 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002664 for (auto *C : PICs) {
2665 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2666 // Find the particular capture region for the clause if the
2667 // directive is a combined one with multiple capture regions.
2668 // If the directive is not a combined one, the capture region
2669 // associated with the clause is OMPD_unknown and is generated
2670 // only once.
2671 if (CaptureRegion == ThisCaptureRegion ||
2672 CaptureRegion == OMPD_unknown) {
2673 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2674 for (auto *D : DS->decls())
2675 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2676 }
2677 }
2678 }
2679 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002680 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002681 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002682 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002683}
2684
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002685static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2686 OpenMPDirectiveKind CancelRegion,
2687 SourceLocation StartLoc) {
2688 // CancelRegion is only needed for cancel and cancellation_point.
2689 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2690 return false;
2691
2692 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2693 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2694 return false;
2695
2696 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2697 << getOpenMPDirectiveName(CancelRegion);
2698 return true;
2699}
2700
2701static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002702 OpenMPDirectiveKind CurrentRegion,
2703 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002704 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002705 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002706 if (Stack->getCurScope()) {
2707 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002708 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002709 bool NestingProhibited = false;
2710 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002711 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002712 enum {
2713 NoRecommend,
2714 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002715 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002716 ShouldBeInTargetRegion,
2717 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002718 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002719 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002720 // OpenMP [2.16, Nesting of Regions]
2721 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002722 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002723 // An ordered construct with the simd clause is the only OpenMP
2724 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002725 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002726 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2727 // message.
2728 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2729 ? diag::err_omp_prohibited_region_simd
2730 : diag::warn_omp_nesting_simd);
2731 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002732 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002733 if (ParentRegion == OMPD_atomic) {
2734 // OpenMP [2.16, Nesting of Regions]
2735 // OpenMP constructs may not be nested inside an atomic region.
2736 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2737 return true;
2738 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002739 if (CurrentRegion == OMPD_section) {
2740 // OpenMP [2.7.2, sections Construct, Restrictions]
2741 // Orphaned section directives are prohibited. That is, the section
2742 // directives must appear within the sections construct and must not be
2743 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002744 if (ParentRegion != OMPD_sections &&
2745 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002746 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2747 << (ParentRegion != OMPD_unknown)
2748 << getOpenMPDirectiveName(ParentRegion);
2749 return true;
2750 }
2751 return false;
2752 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002753 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002754 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002755 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002756 if (ParentRegion == OMPD_unknown &&
2757 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002758 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002759 if (CurrentRegion == OMPD_cancellation_point ||
2760 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002761 // OpenMP [2.16, Nesting of Regions]
2762 // A cancellation point construct for which construct-type-clause is
2763 // taskgroup must be nested inside a task construct. A cancellation
2764 // point construct for which construct-type-clause is not taskgroup must
2765 // be closely nested inside an OpenMP construct that matches the type
2766 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002767 // A cancel construct for which construct-type-clause is taskgroup must be
2768 // nested inside a task construct. A cancel construct for which
2769 // construct-type-clause is not taskgroup must be closely nested inside an
2770 // OpenMP construct that matches the type specified in
2771 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002772 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002773 !((CancelRegion == OMPD_parallel &&
2774 (ParentRegion == OMPD_parallel ||
2775 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002776 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002777 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002778 ParentRegion == OMPD_target_parallel_for ||
2779 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002780 ParentRegion == OMPD_teams_distribute_parallel_for ||
2781 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002782 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2783 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002784 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2785 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002786 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002787 // OpenMP [2.16, Nesting of Regions]
2788 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002789 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002790 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002791 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002792 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2793 // OpenMP [2.16, Nesting of Regions]
2794 // A critical region may not be nested (closely or otherwise) inside a
2795 // critical region with the same name. Note that this restriction is not
2796 // sufficient to prevent deadlock.
2797 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002798 bool DeadLock = Stack->hasDirective(
2799 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2800 const DeclarationNameInfo &DNI,
2801 SourceLocation Loc) -> bool {
2802 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2803 PreviousCriticalLoc = Loc;
2804 return true;
2805 } else
2806 return false;
2807 },
2808 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002809 if (DeadLock) {
2810 SemaRef.Diag(StartLoc,
2811 diag::err_omp_prohibited_region_critical_same_name)
2812 << CurrentName.getName();
2813 if (PreviousCriticalLoc.isValid())
2814 SemaRef.Diag(PreviousCriticalLoc,
2815 diag::note_omp_previous_critical_region);
2816 return true;
2817 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002818 } else if (CurrentRegion == OMPD_barrier) {
2819 // OpenMP [2.16, Nesting of Regions]
2820 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002821 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002822 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2823 isOpenMPTaskingDirective(ParentRegion) ||
2824 ParentRegion == OMPD_master ||
2825 ParentRegion == OMPD_critical ||
2826 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002827 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002828 !isOpenMPParallelDirective(CurrentRegion) &&
2829 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002830 // OpenMP [2.16, Nesting of Regions]
2831 // A worksharing region may not be closely nested inside a worksharing,
2832 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002833 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2834 isOpenMPTaskingDirective(ParentRegion) ||
2835 ParentRegion == OMPD_master ||
2836 ParentRegion == OMPD_critical ||
2837 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002838 Recommend = ShouldBeInParallelRegion;
2839 } else if (CurrentRegion == OMPD_ordered) {
2840 // OpenMP [2.16, Nesting of Regions]
2841 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002842 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002843 // An ordered region must be closely nested inside a loop region (or
2844 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002845 // OpenMP [2.8.1,simd Construct, Restrictions]
2846 // An ordered construct with the simd clause is the only OpenMP construct
2847 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002848 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002849 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002850 !(isOpenMPSimdDirective(ParentRegion) ||
2851 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002852 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002853 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002854 // OpenMP [2.16, Nesting of Regions]
2855 // If specified, a teams construct must be contained within a target
2856 // construct.
2857 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002858 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002859 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002860 }
Kelvin Libf594a52016-12-17 05:48:59 +00002861 if (!NestingProhibited &&
2862 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2863 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2864 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002865 // OpenMP [2.16, Nesting of Regions]
2866 // distribute, parallel, parallel sections, parallel workshare, and the
2867 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2868 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002869 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2870 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002871 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002872 }
David Majnemer9d168222016-08-05 17:44:54 +00002873 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002874 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002875 // OpenMP 4.5 [2.17 Nesting of Regions]
2876 // The region associated with the distribute construct must be strictly
2877 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002878 NestingProhibited =
2879 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002880 Recommend = ShouldBeInTeamsRegion;
2881 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002882 if (!NestingProhibited &&
2883 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2884 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2885 // OpenMP 4.5 [2.17 Nesting of Regions]
2886 // If a target, target update, target data, target enter data, or
2887 // target exit data construct is encountered during execution of a
2888 // target region, the behavior is unspecified.
2889 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002890 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2891 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002892 if (isOpenMPTargetExecutionDirective(K)) {
2893 OffendingRegion = K;
2894 return true;
2895 } else
2896 return false;
2897 },
2898 false /* don't skip top directive */);
2899 CloseNesting = false;
2900 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002901 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002902 if (OrphanSeen) {
2903 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2904 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2905 } else {
2906 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2907 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2908 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2909 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002910 return true;
2911 }
2912 }
2913 return false;
2914}
2915
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002916static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2917 ArrayRef<OMPClause *> Clauses,
2918 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2919 bool ErrorFound = false;
2920 unsigned NamedModifiersNumber = 0;
2921 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2922 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002923 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002924 for (const auto *C : Clauses) {
2925 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2926 // At most one if clause without a directive-name-modifier can appear on
2927 // the directive.
2928 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2929 if (FoundNameModifiers[CurNM]) {
2930 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2931 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2932 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2933 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002934 } else if (CurNM != OMPD_unknown) {
2935 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002936 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002937 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002938 FoundNameModifiers[CurNM] = IC;
2939 if (CurNM == OMPD_unknown)
2940 continue;
2941 // Check if the specified name modifier is allowed for the current
2942 // directive.
2943 // At most one if clause with the particular directive-name-modifier can
2944 // appear on the directive.
2945 bool MatchFound = false;
2946 for (auto NM : AllowedNameModifiers) {
2947 if (CurNM == NM) {
2948 MatchFound = true;
2949 break;
2950 }
2951 }
2952 if (!MatchFound) {
2953 S.Diag(IC->getNameModifierLoc(),
2954 diag::err_omp_wrong_if_directive_name_modifier)
2955 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2956 ErrorFound = true;
2957 }
2958 }
2959 }
2960 // If any if clause on the directive includes a directive-name-modifier then
2961 // all if clauses on the directive must include a directive-name-modifier.
2962 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2963 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2964 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2965 diag::err_omp_no_more_if_clause);
2966 } else {
2967 std::string Values;
2968 std::string Sep(", ");
2969 unsigned AllowedCnt = 0;
2970 unsigned TotalAllowedNum =
2971 AllowedNameModifiers.size() - NamedModifiersNumber;
2972 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2973 ++Cnt) {
2974 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2975 if (!FoundNameModifiers[NM]) {
2976 Values += "'";
2977 Values += getOpenMPDirectiveName(NM);
2978 Values += "'";
2979 if (AllowedCnt + 2 == TotalAllowedNum)
2980 Values += " or ";
2981 else if (AllowedCnt + 1 != TotalAllowedNum)
2982 Values += Sep;
2983 ++AllowedCnt;
2984 }
2985 }
2986 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2987 diag::err_omp_unnamed_if_clause)
2988 << (TotalAllowedNum > 1) << Values;
2989 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002990 for (auto Loc : NameModifierLoc) {
2991 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2992 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002993 ErrorFound = true;
2994 }
2995 return ErrorFound;
2996}
2997
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002998StmtResult Sema::ActOnOpenMPExecutableDirective(
2999 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3000 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3001 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003002 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003003 // First check CancelRegion which is then used in checkNestingOfRegions.
3004 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3005 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003006 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003007 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003008
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003009 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003010 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003011 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003012 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003013 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003014 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3015
3016 // Check default data sharing attributes for referenced variables.
3017 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003018 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3019 Stmt *S = AStmt;
3020 while (--ThisCaptureLevel >= 0)
3021 S = cast<CapturedStmt>(S)->getCapturedStmt();
3022 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003023 if (DSAChecker.isErrorFound())
3024 return StmtError();
3025 // Generate list of implicitly defined firstprivate variables.
3026 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003027
Alexey Bataev88202be2017-07-27 13:20:36 +00003028 SmallVector<Expr *, 4> ImplicitFirstprivates(
3029 DSAChecker.getImplicitFirstprivate().begin(),
3030 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003031 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3032 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003033 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3034 for (auto *C : Clauses) {
3035 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3036 for (auto *E : IRC->taskgroup_descriptors())
3037 if (E)
3038 ImplicitFirstprivates.emplace_back(E);
3039 }
3040 }
3041 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003042 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003043 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3044 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003045 ClausesWithImplicit.push_back(Implicit);
3046 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003047 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00003048 } else
3049 ErrorFound = true;
3050 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003051 if (!ImplicitMaps.empty()) {
3052 if (OMPClause *Implicit = ActOnOpenMPMapClause(
3053 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3054 SourceLocation(), SourceLocation(), ImplicitMaps,
3055 SourceLocation(), SourceLocation(), SourceLocation())) {
3056 ClausesWithImplicit.emplace_back(Implicit);
3057 ErrorFound |=
3058 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3059 } else
3060 ErrorFound = true;
3061 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003062 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003063
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003064 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003065 switch (Kind) {
3066 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003067 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3068 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003069 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003070 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003071 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003072 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3073 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003074 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003075 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003076 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3077 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003078 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003079 case OMPD_for_simd:
3080 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3081 EndLoc, VarsWithInheritedDSA);
3082 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003083 case OMPD_sections:
3084 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3085 EndLoc);
3086 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003087 case OMPD_section:
3088 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003089 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003090 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3091 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003092 case OMPD_single:
3093 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3094 EndLoc);
3095 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003096 case OMPD_master:
3097 assert(ClausesWithImplicit.empty() &&
3098 "No clauses are allowed for 'omp master' directive");
3099 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3100 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003101 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003102 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3103 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003104 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003105 case OMPD_parallel_for:
3106 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3107 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003108 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003109 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003110 case OMPD_parallel_for_simd:
3111 Res = ActOnOpenMPParallelForSimdDirective(
3112 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003113 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003114 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003115 case OMPD_parallel_sections:
3116 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3117 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003118 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003119 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003120 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003121 Res =
3122 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003123 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003124 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003125 case OMPD_taskyield:
3126 assert(ClausesWithImplicit.empty() &&
3127 "No clauses are allowed for 'omp taskyield' directive");
3128 assert(AStmt == nullptr &&
3129 "No associated statement allowed for 'omp taskyield' directive");
3130 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3131 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003132 case OMPD_barrier:
3133 assert(ClausesWithImplicit.empty() &&
3134 "No clauses are allowed for 'omp barrier' directive");
3135 assert(AStmt == nullptr &&
3136 "No associated statement allowed for 'omp barrier' directive");
3137 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3138 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003139 case OMPD_taskwait:
3140 assert(ClausesWithImplicit.empty() &&
3141 "No clauses are allowed for 'omp taskwait' directive");
3142 assert(AStmt == nullptr &&
3143 "No associated statement allowed for 'omp taskwait' directive");
3144 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3145 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003146 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003147 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3148 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003149 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003150 case OMPD_flush:
3151 assert(AStmt == nullptr &&
3152 "No associated statement allowed for 'omp flush' directive");
3153 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3154 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003155 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003156 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3157 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003158 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003159 case OMPD_atomic:
3160 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3161 EndLoc);
3162 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003163 case OMPD_teams:
3164 Res =
3165 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3166 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003167 case OMPD_target:
3168 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3169 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003170 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003171 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003172 case OMPD_target_parallel:
3173 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3174 StartLoc, EndLoc);
3175 AllowedNameModifiers.push_back(OMPD_target);
3176 AllowedNameModifiers.push_back(OMPD_parallel);
3177 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003178 case OMPD_target_parallel_for:
3179 Res = ActOnOpenMPTargetParallelForDirective(
3180 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3181 AllowedNameModifiers.push_back(OMPD_target);
3182 AllowedNameModifiers.push_back(OMPD_parallel);
3183 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003184 case OMPD_cancellation_point:
3185 assert(ClausesWithImplicit.empty() &&
3186 "No clauses are allowed for 'omp cancellation point' directive");
3187 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3188 "cancellation point' directive");
3189 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3190 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003191 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003192 assert(AStmt == nullptr &&
3193 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003194 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3195 CancelRegion);
3196 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003197 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003198 case OMPD_target_data:
3199 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3200 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003201 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003202 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003203 case OMPD_target_enter_data:
3204 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003205 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003206 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3207 break;
Samuel Antao72590762016-01-19 20:04:50 +00003208 case OMPD_target_exit_data:
3209 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003210 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003211 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3212 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003213 case OMPD_taskloop:
3214 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3215 EndLoc, VarsWithInheritedDSA);
3216 AllowedNameModifiers.push_back(OMPD_taskloop);
3217 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003218 case OMPD_taskloop_simd:
3219 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3220 EndLoc, VarsWithInheritedDSA);
3221 AllowedNameModifiers.push_back(OMPD_taskloop);
3222 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003223 case OMPD_distribute:
3224 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3225 EndLoc, VarsWithInheritedDSA);
3226 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003227 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003228 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3229 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003230 AllowedNameModifiers.push_back(OMPD_target_update);
3231 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003232 case OMPD_distribute_parallel_for:
3233 Res = ActOnOpenMPDistributeParallelForDirective(
3234 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3235 AllowedNameModifiers.push_back(OMPD_parallel);
3236 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003237 case OMPD_distribute_parallel_for_simd:
3238 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3239 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3240 AllowedNameModifiers.push_back(OMPD_parallel);
3241 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003242 case OMPD_distribute_simd:
3243 Res = ActOnOpenMPDistributeSimdDirective(
3244 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3245 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003246 case OMPD_target_parallel_for_simd:
3247 Res = ActOnOpenMPTargetParallelForSimdDirective(
3248 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3249 AllowedNameModifiers.push_back(OMPD_target);
3250 AllowedNameModifiers.push_back(OMPD_parallel);
3251 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003252 case OMPD_target_simd:
3253 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3254 EndLoc, VarsWithInheritedDSA);
3255 AllowedNameModifiers.push_back(OMPD_target);
3256 break;
Kelvin Li02532872016-08-05 14:37:37 +00003257 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003258 Res = ActOnOpenMPTeamsDistributeDirective(
3259 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003260 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003261 case OMPD_teams_distribute_simd:
3262 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3263 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3264 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003265 case OMPD_teams_distribute_parallel_for_simd:
3266 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3267 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3268 AllowedNameModifiers.push_back(OMPD_parallel);
3269 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003270 case OMPD_teams_distribute_parallel_for:
3271 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3272 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3273 AllowedNameModifiers.push_back(OMPD_parallel);
3274 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003275 case OMPD_target_teams:
3276 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3277 EndLoc);
3278 AllowedNameModifiers.push_back(OMPD_target);
3279 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003280 case OMPD_target_teams_distribute:
3281 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3282 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3283 AllowedNameModifiers.push_back(OMPD_target);
3284 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003285 case OMPD_target_teams_distribute_parallel_for:
3286 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3287 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3288 AllowedNameModifiers.push_back(OMPD_target);
3289 AllowedNameModifiers.push_back(OMPD_parallel);
3290 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003291 case OMPD_target_teams_distribute_parallel_for_simd:
3292 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3293 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3294 AllowedNameModifiers.push_back(OMPD_target);
3295 AllowedNameModifiers.push_back(OMPD_parallel);
3296 break;
Kelvin Lida681182017-01-10 18:08:18 +00003297 case OMPD_target_teams_distribute_simd:
3298 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3299 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3300 AllowedNameModifiers.push_back(OMPD_target);
3301 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003302 case OMPD_declare_target:
3303 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003304 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003305 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003306 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003307 llvm_unreachable("OpenMP Directive is not allowed");
3308 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003309 llvm_unreachable("Unknown OpenMP directive");
3310 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003311
Alexey Bataev4acb8592014-07-07 13:01:15 +00003312 for (auto P : VarsWithInheritedDSA) {
3313 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3314 << P.first << P.second->getSourceRange();
3315 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003316 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3317
3318 if (!AllowedNameModifiers.empty())
3319 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3320 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003321
Alexey Bataeved09d242014-05-28 05:53:51 +00003322 if (ErrorFound)
3323 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003324 return Res;
3325}
3326
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003327Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3328 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003329 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003330 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3331 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003332 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003333 assert(Linears.size() == LinModifiers.size());
3334 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003335 if (!DG || DG.get().isNull())
3336 return DeclGroupPtrTy();
3337
3338 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003339 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003340 return DG;
3341 }
3342 auto *ADecl = DG.get().getSingleDecl();
3343 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3344 ADecl = FTD->getTemplatedDecl();
3345
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003346 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3347 if (!FD) {
3348 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003349 return DeclGroupPtrTy();
3350 }
3351
Alexey Bataev2af33e32016-04-07 12:45:37 +00003352 // OpenMP [2.8.2, declare simd construct, Description]
3353 // The parameter of the simdlen clause must be a constant positive integer
3354 // expression.
3355 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003356 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003357 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003358 // OpenMP [2.8.2, declare simd construct, Description]
3359 // The special this pointer can be used as if was one of the arguments to the
3360 // function in any of the linear, aligned, or uniform clauses.
3361 // The uniform clause declares one or more arguments to have an invariant
3362 // value for all concurrent invocations of the function in the execution of a
3363 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003364 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3365 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003366 for (auto *E : Uniforms) {
3367 E = E->IgnoreParenImpCasts();
3368 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3369 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3370 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3371 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003372 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3373 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003374 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003375 }
3376 if (isa<CXXThisExpr>(E)) {
3377 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003378 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003379 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003380 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3381 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003382 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003383 // OpenMP [2.8.2, declare simd construct, Description]
3384 // The aligned clause declares that the object to which each list item points
3385 // is aligned to the number of bytes expressed in the optional parameter of
3386 // the aligned clause.
3387 // The special this pointer can be used as if was one of the arguments to the
3388 // function in any of the linear, aligned, or uniform clauses.
3389 // The type of list items appearing in the aligned clause must be array,
3390 // pointer, reference to array, or reference to pointer.
3391 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3392 Expr *AlignedThis = nullptr;
3393 for (auto *E : Aligneds) {
3394 E = E->IgnoreParenImpCasts();
3395 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3396 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3397 auto *CanonPVD = PVD->getCanonicalDecl();
3398 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3399 FD->getParamDecl(PVD->getFunctionScopeIndex())
3400 ->getCanonicalDecl() == CanonPVD) {
3401 // OpenMP [2.8.1, simd construct, Restrictions]
3402 // A list-item cannot appear in more than one aligned clause.
3403 if (AlignedArgs.count(CanonPVD) > 0) {
3404 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3405 << 1 << E->getSourceRange();
3406 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3407 diag::note_omp_explicit_dsa)
3408 << getOpenMPClauseName(OMPC_aligned);
3409 continue;
3410 }
3411 AlignedArgs[CanonPVD] = E;
3412 QualType QTy = PVD->getType()
3413 .getNonReferenceType()
3414 .getUnqualifiedType()
3415 .getCanonicalType();
3416 const Type *Ty = QTy.getTypePtrOrNull();
3417 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3418 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3419 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3420 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3421 }
3422 continue;
3423 }
3424 }
3425 if (isa<CXXThisExpr>(E)) {
3426 if (AlignedThis) {
3427 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3428 << 2 << E->getSourceRange();
3429 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3430 << getOpenMPClauseName(OMPC_aligned);
3431 }
3432 AlignedThis = E;
3433 continue;
3434 }
3435 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3436 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3437 }
3438 // The optional parameter of the aligned clause, alignment, must be a constant
3439 // positive integer expression. If no optional parameter is specified,
3440 // implementation-defined default alignments for SIMD instructions on the
3441 // target platforms are assumed.
3442 SmallVector<Expr *, 4> NewAligns;
3443 for (auto *E : Alignments) {
3444 ExprResult Align;
3445 if (E)
3446 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3447 NewAligns.push_back(Align.get());
3448 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003449 // OpenMP [2.8.2, declare simd construct, Description]
3450 // The linear clause declares one or more list items to be private to a SIMD
3451 // lane and to have a linear relationship with respect to the iteration space
3452 // of a loop.
3453 // The special this pointer can be used as if was one of the arguments to the
3454 // function in any of the linear, aligned, or uniform clauses.
3455 // When a linear-step expression is specified in a linear clause it must be
3456 // either a constant integer expression or an integer-typed parameter that is
3457 // specified in a uniform clause on the directive.
3458 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3459 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3460 auto MI = LinModifiers.begin();
3461 for (auto *E : Linears) {
3462 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3463 ++MI;
3464 E = E->IgnoreParenImpCasts();
3465 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3466 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3467 auto *CanonPVD = PVD->getCanonicalDecl();
3468 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3469 FD->getParamDecl(PVD->getFunctionScopeIndex())
3470 ->getCanonicalDecl() == CanonPVD) {
3471 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3472 // A list-item cannot appear in more than one linear clause.
3473 if (LinearArgs.count(CanonPVD) > 0) {
3474 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3475 << getOpenMPClauseName(OMPC_linear)
3476 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3477 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3478 diag::note_omp_explicit_dsa)
3479 << getOpenMPClauseName(OMPC_linear);
3480 continue;
3481 }
3482 // Each argument can appear in at most one uniform or linear clause.
3483 if (UniformedArgs.count(CanonPVD) > 0) {
3484 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3485 << getOpenMPClauseName(OMPC_linear)
3486 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3487 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3488 diag::note_omp_explicit_dsa)
3489 << getOpenMPClauseName(OMPC_uniform);
3490 continue;
3491 }
3492 LinearArgs[CanonPVD] = E;
3493 if (E->isValueDependent() || E->isTypeDependent() ||
3494 E->isInstantiationDependent() ||
3495 E->containsUnexpandedParameterPack())
3496 continue;
3497 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3498 PVD->getOriginalType());
3499 continue;
3500 }
3501 }
3502 if (isa<CXXThisExpr>(E)) {
3503 if (UniformedLinearThis) {
3504 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3505 << getOpenMPClauseName(OMPC_linear)
3506 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3507 << E->getSourceRange();
3508 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3509 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3510 : OMPC_linear);
3511 continue;
3512 }
3513 UniformedLinearThis = E;
3514 if (E->isValueDependent() || E->isTypeDependent() ||
3515 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3516 continue;
3517 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3518 E->getType());
3519 continue;
3520 }
3521 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3522 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3523 }
3524 Expr *Step = nullptr;
3525 Expr *NewStep = nullptr;
3526 SmallVector<Expr *, 4> NewSteps;
3527 for (auto *E : Steps) {
3528 // Skip the same step expression, it was checked already.
3529 if (Step == E || !E) {
3530 NewSteps.push_back(E ? NewStep : nullptr);
3531 continue;
3532 }
3533 Step = E;
3534 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3535 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3536 auto *CanonPVD = PVD->getCanonicalDecl();
3537 if (UniformedArgs.count(CanonPVD) == 0) {
3538 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3539 << Step->getSourceRange();
3540 } else if (E->isValueDependent() || E->isTypeDependent() ||
3541 E->isInstantiationDependent() ||
3542 E->containsUnexpandedParameterPack() ||
3543 CanonPVD->getType()->hasIntegerRepresentation())
3544 NewSteps.push_back(Step);
3545 else {
3546 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3547 << Step->getSourceRange();
3548 }
3549 continue;
3550 }
3551 NewStep = Step;
3552 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3553 !Step->isInstantiationDependent() &&
3554 !Step->containsUnexpandedParameterPack()) {
3555 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3556 .get();
3557 if (NewStep)
3558 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3559 }
3560 NewSteps.push_back(NewStep);
3561 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003562 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3563 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003564 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003565 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3566 const_cast<Expr **>(Linears.data()), Linears.size(),
3567 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3568 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003569 ADecl->addAttr(NewAttr);
3570 return ConvertDeclToDeclGroup(ADecl);
3571}
3572
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003573StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3574 Stmt *AStmt,
3575 SourceLocation StartLoc,
3576 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003577 if (!AStmt)
3578 return StmtError();
3579
Alexey Bataev9959db52014-05-06 10:08:46 +00003580 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3581 // 1.2.2 OpenMP Language Terminology
3582 // Structured block - An executable statement with a single entry at the
3583 // top and a single exit at the bottom.
3584 // The point of exit cannot be a branch out of the structured block.
3585 // longjmp() and throw() must not violate the entry/exit criteria.
3586 CS->getCapturedDecl()->setNothrow();
3587
Reid Kleckner87a31802018-03-12 21:43:02 +00003588 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003589
Alexey Bataev25e5b442015-09-15 12:52:43 +00003590 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3591 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003592}
3593
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003594namespace {
3595/// \brief Helper class for checking canonical form of the OpenMP loops and
3596/// extracting iteration space of each loop in the loop nest, that will be used
3597/// for IR generation.
3598class OpenMPIterationSpaceChecker {
3599 /// \brief Reference to Sema.
3600 Sema &SemaRef;
3601 /// \brief A location for diagnostics (when there is no some better location).
3602 SourceLocation DefaultLoc;
3603 /// \brief A location for diagnostics (when increment is not compatible).
3604 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003605 /// \brief A source location for referring to loop init later.
3606 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003607 /// \brief A source location for referring to condition later.
3608 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003609 /// \brief A source location for referring to increment later.
3610 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003611 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003612 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003613 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003614 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003615 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003616 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003617 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003618 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003619 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003620 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003621 /// \brief This flag is true when condition is one of:
3622 /// Var < UB
3623 /// Var <= UB
3624 /// UB > Var
3625 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003626 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003627 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003628 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003629 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003630 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003631
3632public:
3633 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003634 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003635 /// \brief Check init-expr for canonical loop form and save loop counter
3636 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003637 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003638 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3639 /// for less/greater and for strict/non-strict comparison.
3640 bool CheckCond(Expr *S);
3641 /// \brief Check incr-expr for canonical loop form and return true if it
3642 /// does not conform, otherwise save loop step (#Step).
3643 bool CheckInc(Expr *S);
3644 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003645 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003646 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003647 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003648 /// \brief Source range of the loop init.
3649 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3650 /// \brief Source range of the loop condition.
3651 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3652 /// \brief Source range of the loop increment.
3653 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3654 /// \brief True if the step should be subtracted.
3655 bool ShouldSubtractStep() const { return SubtractStep; }
3656 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003657 Expr *
3658 BuildNumIterations(Scope *S, const bool LimitedType,
3659 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003660 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003661 Expr *BuildPreCond(Scope *S, Expr *Cond,
3662 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003663 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003664 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3665 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003666 /// \brief Build reference expression to the private counter be used for
3667 /// codegen.
3668 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003669 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003670 Expr *BuildCounterInit() const;
3671 /// \brief Build step of the counter be used for codegen.
3672 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003673 /// \brief Return true if any expression is dependent.
3674 bool Dependent() const;
3675
3676private:
3677 /// \brief Check the right-hand side of an assignment in the increment
3678 /// expression.
3679 bool CheckIncRHS(Expr *RHS);
3680 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003681 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003683 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003684 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003685 /// \brief Helper to set loop increment.
3686 bool SetStep(Expr *NewStep, bool Subtract);
3687};
3688
3689bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003690 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003691 assert(!LB && !UB && !Step);
3692 return false;
3693 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003694 return LCDecl->getType()->isDependentType() ||
3695 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3696 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003697}
3698
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003699bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3700 Expr *NewLCRefExpr,
3701 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003702 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003703 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003704 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003705 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003707 LCDecl = getCanonicalDecl(NewLCDecl);
3708 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003709 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3710 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003711 if ((Ctor->isCopyOrMoveConstructor() ||
3712 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3713 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003714 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 LB = NewLB;
3716 return false;
3717}
3718
3719bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003720 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003721 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003722 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3723 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003724 if (!NewUB)
3725 return true;
3726 UB = NewUB;
3727 TestIsLessOp = LessOp;
3728 TestIsStrictOp = StrictOp;
3729 ConditionSrcRange = SR;
3730 ConditionLoc = SL;
3731 return false;
3732}
3733
3734bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3735 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003736 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003737 if (!NewStep)
3738 return true;
3739 if (!NewStep->isValueDependent()) {
3740 // Check that the step is integer expression.
3741 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003742 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3743 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003744 if (Val.isInvalid())
3745 return true;
3746 NewStep = Val.get();
3747
3748 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3749 // If test-expr is of form var relational-op b and relational-op is < or
3750 // <= then incr-expr must cause var to increase on each iteration of the
3751 // loop. If test-expr is of form var relational-op b and relational-op is
3752 // > or >= then incr-expr must cause var to decrease on each iteration of
3753 // the loop.
3754 // If test-expr is of form b relational-op var and relational-op is < or
3755 // <= then incr-expr must cause var to decrease on each iteration of the
3756 // loop. If test-expr is of form b relational-op var and relational-op is
3757 // > or >= then incr-expr must cause var to increase on each iteration of
3758 // the loop.
3759 llvm::APSInt Result;
3760 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3761 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3762 bool IsConstNeg =
3763 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003764 bool IsConstPos =
3765 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003766 bool IsConstZero = IsConstant && !Result.getBoolValue();
3767 if (UB && (IsConstZero ||
3768 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003769 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003770 SemaRef.Diag(NewStep->getExprLoc(),
3771 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003772 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003773 SemaRef.Diag(ConditionLoc,
3774 diag::note_omp_loop_cond_requres_compatible_incr)
3775 << TestIsLessOp << ConditionSrcRange;
3776 return true;
3777 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003778 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003779 NewStep =
3780 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3781 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003782 Subtract = !Subtract;
3783 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003784 }
3785
3786 Step = NewStep;
3787 SubtractStep = Subtract;
3788 return false;
3789}
3790
Alexey Bataev9c821032015-04-30 04:23:23 +00003791bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003792 // Check init-expr for canonical loop form and save loop counter
3793 // variable - #Var and its initialization value - #LB.
3794 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3795 // var = lb
3796 // integer-type var = lb
3797 // random-access-iterator-type var = lb
3798 // pointer-type var = lb
3799 //
3800 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003801 if (EmitDiags) {
3802 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3803 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003804 return true;
3805 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003806 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3807 if (!ExprTemp->cleanupsHaveSideEffects())
3808 S = ExprTemp->getSubExpr();
3809
Alexander Musmana5f070a2014-10-01 06:03:56 +00003810 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003811 if (Expr *E = dyn_cast<Expr>(S))
3812 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003813 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003814 if (BO->getOpcode() == BO_Assign) {
3815 auto *LHS = BO->getLHS()->IgnoreParens();
3816 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3817 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3818 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3819 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3820 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3821 }
3822 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3823 if (ME->isArrow() &&
3824 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3825 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3826 }
3827 }
David Majnemer9d168222016-08-05 17:44:54 +00003828 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003829 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003830 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003831 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003832 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003833 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003834 SemaRef.Diag(S->getLocStart(),
3835 diag::ext_omp_loop_not_canonical_init)
3836 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003837 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003838 }
3839 }
3840 }
David Majnemer9d168222016-08-05 17:44:54 +00003841 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003842 if (CE->getOperator() == OO_Equal) {
3843 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003844 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003845 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3846 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3847 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3848 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3849 }
3850 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3851 if (ME->isArrow() &&
3852 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3853 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3854 }
3855 }
3856 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003857
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003858 if (Dependent() || SemaRef.CurContext->isDependentContext())
3859 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003860 if (EmitDiags) {
3861 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3862 << S->getSourceRange();
3863 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003864 return true;
3865}
3866
Alexey Bataev23b69422014-06-18 07:08:49 +00003867/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003868/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003869static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003870 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003871 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003872 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003873 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3874 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003875 if ((Ctor->isCopyOrMoveConstructor() ||
3876 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3877 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003878 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003879 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003880 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003881 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003882 }
3883 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3884 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3885 return getCanonicalDecl(ME->getMemberDecl());
3886 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003887}
3888
3889bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3890 // Check test-expr for canonical form, save upper-bound UB, flags for
3891 // less/greater and for strict/non-strict comparison.
3892 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3893 // var relational-op b
3894 // b relational-op var
3895 //
3896 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003897 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003898 return true;
3899 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003900 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003902 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003903 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003904 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003905 return SetUB(BO->getRHS(),
3906 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3907 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3908 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003909 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003910 return SetUB(BO->getLHS(),
3911 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3912 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3913 BO->getSourceRange(), BO->getOperatorLoc());
3914 }
David Majnemer9d168222016-08-05 17:44:54 +00003915 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003916 if (CE->getNumArgs() == 2) {
3917 auto Op = CE->getOperator();
3918 switch (Op) {
3919 case OO_Greater:
3920 case OO_GreaterEqual:
3921 case OO_Less:
3922 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003923 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003924 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3925 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3926 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003927 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003928 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3929 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3930 CE->getOperatorLoc());
3931 break;
3932 default:
3933 break;
3934 }
3935 }
3936 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003937 if (Dependent() || SemaRef.CurContext->isDependentContext())
3938 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003939 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003940 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003941 return true;
3942}
3943
3944bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3945 // RHS of canonical loop form increment can be:
3946 // var + incr
3947 // incr + var
3948 // var - incr
3949 //
3950 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003951 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003952 if (BO->isAdditiveOp()) {
3953 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003954 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003955 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003956 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003957 return SetStep(BO->getLHS(), false);
3958 }
David Majnemer9d168222016-08-05 17:44:54 +00003959 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003960 bool IsAdd = CE->getOperator() == OO_Plus;
3961 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003962 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003963 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003964 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003965 return SetStep(CE->getArg(0), false);
3966 }
3967 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003968 if (Dependent() || SemaRef.CurContext->isDependentContext())
3969 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003970 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003971 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003972 return true;
3973}
3974
3975bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3976 // Check incr-expr for canonical loop form and return true if it
3977 // does not conform.
3978 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3979 // ++var
3980 // var++
3981 // --var
3982 // var--
3983 // var += incr
3984 // var -= incr
3985 // var = var + incr
3986 // var = incr + var
3987 // var = var - incr
3988 //
3989 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003990 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003991 return true;
3992 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003993 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3994 if (!ExprTemp->cleanupsHaveSideEffects())
3995 S = ExprTemp->getSubExpr();
3996
Alexander Musmana5f070a2014-10-01 06:03:56 +00003997 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003998 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003999 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004000 if (UO->isIncrementDecrementOp() &&
4001 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00004002 return SetStep(SemaRef
4003 .ActOnIntegerConstant(UO->getLocStart(),
4004 (UO->isDecrementOp() ? -1 : 1))
4005 .get(),
4006 false);
4007 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004008 switch (BO->getOpcode()) {
4009 case BO_AddAssign:
4010 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004011 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004012 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4013 break;
4014 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004015 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004016 return CheckIncRHS(BO->getRHS());
4017 break;
4018 default:
4019 break;
4020 }
David Majnemer9d168222016-08-05 17:44:54 +00004021 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004022 switch (CE->getOperator()) {
4023 case OO_PlusPlus:
4024 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004025 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00004026 return SetStep(SemaRef
4027 .ActOnIntegerConstant(
4028 CE->getLocStart(),
4029 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4030 .get(),
4031 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004032 break;
4033 case OO_PlusEqual:
4034 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004035 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004036 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4037 break;
4038 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004039 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004040 return CheckIncRHS(CE->getArg(1));
4041 break;
4042 default:
4043 break;
4044 }
4045 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004046 if (Dependent() || SemaRef.CurContext->isDependentContext())
4047 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004048 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004049 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004050 return true;
4051}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004052
Alexey Bataev5a3af132016-03-29 08:58:54 +00004053static ExprResult
4054tryBuildCapture(Sema &SemaRef, Expr *Capture,
4055 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004056 if (SemaRef.CurContext->isDependentContext())
4057 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004058 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4059 return SemaRef.PerformImplicitConversion(
4060 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4061 /*AllowExplicit=*/true);
4062 auto I = Captures.find(Capture);
4063 if (I != Captures.end())
4064 return buildCapture(SemaRef, Capture, I->second);
4065 DeclRefExpr *Ref = nullptr;
4066 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4067 Captures[Capture] = Ref;
4068 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004069}
4070
Alexander Musmana5f070a2014-10-01 06:03:56 +00004071/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004072Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4073 Scope *S, const bool LimitedType,
4074 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004075 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004076 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004077 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004078 SemaRef.getLangOpts().CPlusPlus) {
4079 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004080 auto *UBExpr = TestIsLessOp ? UB : LB;
4081 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004082 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4083 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004084 if (!Upper || !Lower)
4085 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004086
4087 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4088
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004089 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004090 // BuildBinOp already emitted error, this one is to point user to upper
4091 // and lower bound, and to tell what is passed to 'operator-'.
4092 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4093 << Upper->getSourceRange() << Lower->getSourceRange();
4094 return nullptr;
4095 }
4096 }
4097
4098 if (!Diff.isUsable())
4099 return nullptr;
4100
4101 // Upper - Lower [- 1]
4102 if (TestIsStrictOp)
4103 Diff = SemaRef.BuildBinOp(
4104 S, DefaultLoc, BO_Sub, Diff.get(),
4105 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4106 if (!Diff.isUsable())
4107 return nullptr;
4108
4109 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00004110 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4111 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004112 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004113 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004114 if (!Diff.isUsable())
4115 return nullptr;
4116
4117 // Parentheses (for dumping/debugging purposes only).
4118 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4119 if (!Diff.isUsable())
4120 return nullptr;
4121
4122 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004123 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004124 if (!Diff.isUsable())
4125 return nullptr;
4126
Alexander Musman174b3ca2014-10-06 11:16:29 +00004127 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004128 QualType Type = Diff.get()->getType();
4129 auto &C = SemaRef.Context;
4130 bool UseVarType = VarType->hasIntegerRepresentation() &&
4131 C.getTypeSize(Type) > C.getTypeSize(VarType);
4132 if (!Type->isIntegerType() || UseVarType) {
4133 unsigned NewSize =
4134 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4135 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4136 : Type->hasSignedIntegerRepresentation();
4137 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004138 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4139 Diff = SemaRef.PerformImplicitConversion(
4140 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4141 if (!Diff.isUsable())
4142 return nullptr;
4143 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004144 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004145 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004146 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4147 if (NewSize != C.getTypeSize(Type)) {
4148 if (NewSize < C.getTypeSize(Type)) {
4149 assert(NewSize == 64 && "incorrect loop var size");
4150 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4151 << InitSrcRange << ConditionSrcRange;
4152 }
4153 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004154 NewSize, Type->hasSignedIntegerRepresentation() ||
4155 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004156 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4157 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4158 Sema::AA_Converting, true);
4159 if (!Diff.isUsable())
4160 return nullptr;
4161 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004162 }
4163 }
4164
Alexander Musmana5f070a2014-10-01 06:03:56 +00004165 return Diff.get();
4166}
4167
Alexey Bataev5a3af132016-03-29 08:58:54 +00004168Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4169 Scope *S, Expr *Cond,
4170 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004171 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4172 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4173 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004174
Alexey Bataev5a3af132016-03-29 08:58:54 +00004175 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4176 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4177 if (!NewLB.isUsable() || !NewUB.isUsable())
4178 return nullptr;
4179
Alexey Bataev62dbb972015-04-22 11:59:37 +00004180 auto CondExpr = SemaRef.BuildBinOp(
4181 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4182 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004183 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004184 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004185 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4186 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004187 CondExpr = SemaRef.PerformImplicitConversion(
4188 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4189 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004190 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004191 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4192 // Otherwise use original loop conditon and evaluate it in runtime.
4193 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4194}
4195
Alexander Musmana5f070a2014-10-01 06:03:56 +00004196/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004197DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004198 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004199 auto *VD = dyn_cast<VarDecl>(LCDecl);
4200 if (!VD) {
4201 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4202 auto *Ref = buildDeclRefExpr(
4203 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004204 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4205 // If the loop control decl is explicitly marked as private, do not mark it
4206 // as captured again.
4207 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4208 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004209 return Ref;
4210 }
4211 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004212 DefaultLoc);
4213}
4214
4215Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004216 if (LCDecl && !LCDecl->isInvalidDecl()) {
4217 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004218 auto *PrivateVar = buildVarDecl(
4219 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4220 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4221 isa<VarDecl>(LCDecl)
4222 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4223 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004224 if (PrivateVar->isInvalidDecl())
4225 return nullptr;
4226 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4227 }
4228 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004229}
4230
Samuel Antao4c8035b2016-12-12 18:00:20 +00004231/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004232Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4233
4234/// \brief Build step of the counter be used for codegen.
4235Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4236
4237/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004238struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004239 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004240 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004241 /// \brief This expression calculates the number of iterations in the loop.
4242 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004243 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004244 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004245 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004246 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004247 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004248 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004249 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004250 /// \brief This is step for the #CounterVar used to generate its update:
4251 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004252 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004253 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004254 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004255 /// \brief Source range of the loop init.
4256 SourceRange InitSrcRange;
4257 /// \brief Source range of the loop condition.
4258 SourceRange CondSrcRange;
4259 /// \brief Source range of the loop increment.
4260 SourceRange IncSrcRange;
4261};
4262
Alexey Bataev23b69422014-06-18 07:08:49 +00004263} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004264
Alexey Bataev9c821032015-04-30 04:23:23 +00004265void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4266 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4267 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004268 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4269 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004270 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4271 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004272 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4273 if (auto *D = ISC.GetLoopDecl()) {
4274 auto *VD = dyn_cast<VarDecl>(D);
4275 if (!VD) {
4276 if (auto *Private = IsOpenMPCapturedDecl(D))
4277 VD = Private;
4278 else {
4279 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4280 /*WithInit=*/false);
4281 VD = cast<VarDecl>(Ref->getDecl());
4282 }
4283 }
4284 DSAStack->addLoopControlVariable(D, VD);
4285 }
4286 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004287 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004288 }
4289}
4290
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004291/// \brief Called on a for stmt to check and extract its iteration space
4292/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004293static bool CheckOpenMPIterationSpace(
4294 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4295 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004296 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004297 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004298 LoopIterationSpace &ResultIterSpace,
4299 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004300 // OpenMP [2.6, Canonical Loop Form]
4301 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004302 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004303 if (!For) {
4304 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004305 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4306 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4307 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4308 if (NestedLoopCount > 1) {
4309 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4310 SemaRef.Diag(DSA.getConstructLoc(),
4311 diag::note_omp_collapse_ordered_expr)
4312 << 2 << CollapseLoopCountExpr->getSourceRange()
4313 << OrderedLoopCountExpr->getSourceRange();
4314 else if (CollapseLoopCountExpr)
4315 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4316 diag::note_omp_collapse_ordered_expr)
4317 << 0 << CollapseLoopCountExpr->getSourceRange();
4318 else
4319 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4320 diag::note_omp_collapse_ordered_expr)
4321 << 1 << OrderedLoopCountExpr->getSourceRange();
4322 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004323 return true;
4324 }
4325 assert(For->getBody());
4326
4327 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4328
4329 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004330 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004331 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004332 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004333
4334 bool HasErrors = false;
4335
4336 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004337 if (auto *LCDecl = ISC.GetLoopDecl()) {
4338 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004339
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004340 // OpenMP [2.6, Canonical Loop Form]
4341 // Var is one of the following:
4342 // A variable of signed or unsigned integer type.
4343 // For C++, a variable of a random access iterator type.
4344 // For C, a variable of a pointer type.
4345 auto VarType = LCDecl->getType().getNonReferenceType();
4346 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4347 !VarType->isPointerType() &&
4348 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4349 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4350 << SemaRef.getLangOpts().CPlusPlus;
4351 HasErrors = true;
4352 }
4353
4354 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4355 // a Construct
4356 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4357 // parallel for construct is (are) private.
4358 // The loop iteration variable in the associated for-loop of a simd
4359 // construct with just one associated for-loop is linear with a
4360 // constant-linear-step that is the increment of the associated for-loop.
4361 // Exclude loop var from the list of variables with implicitly defined data
4362 // sharing attributes.
4363 VarsWithImplicitDSA.erase(LCDecl);
4364
4365 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4366 // in a Construct, C/C++].
4367 // The loop iteration variable in the associated for-loop of a simd
4368 // construct with just one associated for-loop may be listed in a linear
4369 // clause with a constant-linear-step that is the increment of the
4370 // associated for-loop.
4371 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4372 // parallel for construct may be listed in a private or lastprivate clause.
4373 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4374 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4375 // declared in the loop and it is predetermined as a private.
4376 auto PredeterminedCKind =
4377 isOpenMPSimdDirective(DKind)
4378 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4379 : OMPC_private;
4380 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4381 DVar.CKind != PredeterminedCKind) ||
4382 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4383 isOpenMPDistributeDirective(DKind)) &&
4384 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4385 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4386 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4387 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4388 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4389 << getOpenMPClauseName(PredeterminedCKind);
4390 if (DVar.RefExpr == nullptr)
4391 DVar.CKind = PredeterminedCKind;
4392 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4393 HasErrors = true;
4394 } else if (LoopDeclRefExpr != nullptr) {
4395 // Make the loop iteration variable private (for worksharing constructs),
4396 // linear (for simd directives with the only one associated loop) or
4397 // lastprivate (for simd directives with several collapsed or ordered
4398 // loops).
4399 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004400 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4401 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004402 /*FromParent=*/false);
4403 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4404 }
4405
4406 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4407
4408 // Check test-expr.
4409 HasErrors |= ISC.CheckCond(For->getCond());
4410
4411 // Check incr-expr.
4412 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004413 }
4414
Alexander Musmana5f070a2014-10-01 06:03:56 +00004415 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004416 return HasErrors;
4417
Alexander Musmana5f070a2014-10-01 06:03:56 +00004418 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004419 ResultIterSpace.PreCond =
4420 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004421 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004422 DSA.getCurScope(),
4423 (isOpenMPWorksharingDirective(DKind) ||
4424 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4425 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004426 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004427 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004428 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4429 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4430 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4431 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4432 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4433 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4434
Alexey Bataev62dbb972015-04-22 11:59:37 +00004435 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4436 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004437 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004438 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004439 ResultIterSpace.CounterInit == nullptr ||
4440 ResultIterSpace.CounterStep == nullptr);
4441
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004442 return HasErrors;
4443}
4444
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004445/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004446static ExprResult
4447BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4448 ExprResult Start,
4449 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004450 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004451 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4452 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004453 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004454 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004455 VarRef.get()->getType())) {
4456 NewStart = SemaRef.PerformImplicitConversion(
4457 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4458 /*AllowExplicit=*/true);
4459 if (!NewStart.isUsable())
4460 return ExprError();
4461 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004462
4463 auto Init =
4464 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4465 return Init;
4466}
4467
Alexander Musmana5f070a2014-10-01 06:03:56 +00004468/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004469static ExprResult
4470BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4471 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4472 ExprResult Step, bool Subtract,
4473 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004474 // Add parentheses (for debugging purposes only).
4475 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4476 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4477 !Step.isUsable())
4478 return ExprError();
4479
Alexey Bataev5a3af132016-03-29 08:58:54 +00004480 ExprResult NewStep = Step;
4481 if (Captures)
4482 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004483 if (NewStep.isInvalid())
4484 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004485 ExprResult Update =
4486 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004487 if (!Update.isUsable())
4488 return ExprError();
4489
Alexey Bataevc0214e02016-02-16 12:13:49 +00004490 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4491 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004492 ExprResult NewStart = Start;
4493 if (Captures)
4494 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004495 if (NewStart.isInvalid())
4496 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004497
Alexey Bataevc0214e02016-02-16 12:13:49 +00004498 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4499 ExprResult SavedUpdate = Update;
4500 ExprResult UpdateVal;
4501 if (VarRef.get()->getType()->isOverloadableType() ||
4502 NewStart.get()->getType()->isOverloadableType() ||
4503 Update.get()->getType()->isOverloadableType()) {
4504 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4505 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4506 Update =
4507 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4508 if (Update.isUsable()) {
4509 UpdateVal =
4510 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4511 VarRef.get(), SavedUpdate.get());
4512 if (UpdateVal.isUsable()) {
4513 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4514 UpdateVal.get());
4515 }
4516 }
4517 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4518 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004519
Alexey Bataevc0214e02016-02-16 12:13:49 +00004520 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4521 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4522 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4523 NewStart.get(), SavedUpdate.get());
4524 if (!Update.isUsable())
4525 return ExprError();
4526
Alexey Bataev11481f52016-02-17 10:29:05 +00004527 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4528 VarRef.get()->getType())) {
4529 Update = SemaRef.PerformImplicitConversion(
4530 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4531 if (!Update.isUsable())
4532 return ExprError();
4533 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004534
4535 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4536 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004537 return Update;
4538}
4539
4540/// \brief Convert integer expression \a E to make it have at least \a Bits
4541/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004542static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004543 if (E == nullptr)
4544 return ExprError();
4545 auto &C = SemaRef.Context;
4546 QualType OldType = E->getType();
4547 unsigned HasBits = C.getTypeSize(OldType);
4548 if (HasBits >= Bits)
4549 return ExprResult(E);
4550 // OK to convert to signed, because new type has more bits than old.
4551 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4552 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4553 true);
4554}
4555
4556/// \brief Check if the given expression \a E is a constant integer that fits
4557/// into \a Bits bits.
4558static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4559 if (E == nullptr)
4560 return false;
4561 llvm::APSInt Result;
4562 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4563 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4564 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004565}
4566
Alexey Bataev5a3af132016-03-29 08:58:54 +00004567/// Build preinits statement for the given declarations.
4568static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004569 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004570 if (!PreInits.empty()) {
4571 return new (Context) DeclStmt(
4572 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4573 SourceLocation(), SourceLocation());
4574 }
4575 return nullptr;
4576}
4577
4578/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004579static Stmt *
4580buildPreInits(ASTContext &Context,
4581 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004582 if (!Captures.empty()) {
4583 SmallVector<Decl *, 16> PreInits;
4584 for (auto &Pair : Captures)
4585 PreInits.push_back(Pair.second->getDecl());
4586 return buildPreInits(Context, PreInits);
4587 }
4588 return nullptr;
4589}
4590
4591/// Build postupdate expression for the given list of postupdates expressions.
4592static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4593 Expr *PostUpdate = nullptr;
4594 if (!PostUpdates.empty()) {
4595 for (auto *E : PostUpdates) {
4596 Expr *ConvE = S.BuildCStyleCastExpr(
4597 E->getExprLoc(),
4598 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4599 E->getExprLoc(), E)
4600 .get();
4601 PostUpdate = PostUpdate
4602 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4603 PostUpdate, ConvE)
4604 .get()
4605 : ConvE;
4606 }
4607 }
4608 return PostUpdate;
4609}
4610
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004611/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004612/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4613/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004614static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004615CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4616 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4617 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004618 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004619 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004620 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004621 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004622 // Found 'collapse' clause - calculate collapse number.
4623 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004624 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004625 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004626 }
4627 if (OrderedLoopCountExpr) {
4628 // Found 'ordered' clause - calculate collapse number.
4629 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004630 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4631 if (Result.getLimitedValue() < NestedLoopCount) {
4632 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4633 diag::err_omp_wrong_ordered_loop_count)
4634 << OrderedLoopCountExpr->getSourceRange();
4635 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4636 diag::note_collapse_loop_count)
4637 << CollapseLoopCountExpr->getSourceRange();
4638 }
4639 NestedLoopCount = Result.getLimitedValue();
4640 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004641 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004642 // This is helper routine for loop directives (e.g., 'for', 'simd',
4643 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004644 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004645 SmallVector<LoopIterationSpace, 4> IterSpaces;
4646 IterSpaces.resize(NestedLoopCount);
4647 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004648 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004649 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004650 NestedLoopCount, CollapseLoopCountExpr,
4651 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004652 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004653 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004654 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004655 // OpenMP [2.8.1, simd construct, Restrictions]
4656 // All loops associated with the construct must be perfectly nested; that
4657 // is, there must be no intervening code nor any OpenMP directive between
4658 // any two loops.
4659 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004660 }
4661
Alexander Musmana5f070a2014-10-01 06:03:56 +00004662 Built.clear(/* size */ NestedLoopCount);
4663
4664 if (SemaRef.CurContext->isDependentContext())
4665 return NestedLoopCount;
4666
4667 // An example of what is generated for the following code:
4668 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004669 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004670 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004671 // for (k = 0; k < NK; ++k)
4672 // for (j = J0; j < NJ; j+=2) {
4673 // <loop body>
4674 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004675 //
4676 // We generate the code below.
4677 // Note: the loop body may be outlined in CodeGen.
4678 // Note: some counters may be C++ classes, operator- is used to find number of
4679 // iterations and operator+= to calculate counter value.
4680 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4681 // or i64 is currently supported).
4682 //
4683 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4684 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4685 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4686 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4687 // // similar updates for vars in clauses (e.g. 'linear')
4688 // <loop body (using local i and j)>
4689 // }
4690 // i = NI; // assign final values of counters
4691 // j = NJ;
4692 //
4693
4694 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4695 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004696 // Precondition tests if there is at least one iteration (all conditions are
4697 // true).
4698 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004699 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004700 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004701 32 /* Bits */, SemaRef
4702 .PerformImplicitConversion(
4703 N0->IgnoreImpCasts(), N0->getType(),
4704 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004705 .get(),
4706 SemaRef);
4707 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004708 64 /* Bits */, SemaRef
4709 .PerformImplicitConversion(
4710 N0->IgnoreImpCasts(), N0->getType(),
4711 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004712 .get(),
4713 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004714
4715 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4716 return NestedLoopCount;
4717
4718 auto &C = SemaRef.Context;
4719 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4720
4721 Scope *CurScope = DSA.getCurScope();
4722 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004723 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004724 PreCond =
4725 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4726 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004727 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004728 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004729 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004730 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4731 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004732 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004733 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004734 SemaRef
4735 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4736 Sema::AA_Converting,
4737 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004738 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004739 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004740 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004741 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004742 SemaRef
4743 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4744 Sema::AA_Converting,
4745 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004746 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004747 }
4748
4749 // Choose either the 32-bit or 64-bit version.
4750 ExprResult LastIteration = LastIteration64;
4751 if (LastIteration32.isUsable() &&
4752 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4753 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4754 FitsInto(
4755 32 /* Bits */,
4756 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4757 LastIteration64.get(), SemaRef)))
4758 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004759 QualType VType = LastIteration.get()->getType();
4760 QualType RealVType = VType;
4761 QualType StrideVType = VType;
4762 if (isOpenMPTaskLoopDirective(DKind)) {
4763 VType =
4764 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4765 StrideVType =
4766 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4767 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004768
4769 if (!LastIteration.isUsable())
4770 return 0;
4771
4772 // Save the number of iterations.
4773 ExprResult NumIterations = LastIteration;
4774 {
4775 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004776 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4777 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004778 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4779 if (!LastIteration.isUsable())
4780 return 0;
4781 }
4782
4783 // Calculate the last iteration number beforehand instead of doing this on
4784 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4785 llvm::APSInt Result;
4786 bool IsConstant =
4787 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4788 ExprResult CalcLastIteration;
4789 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004790 ExprResult SaveRef =
4791 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004792 LastIteration = SaveRef;
4793
4794 // Prepare SaveRef + 1.
4795 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004796 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004797 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4798 if (!NumIterations.isUsable())
4799 return 0;
4800 }
4801
4802 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4803
David Majnemer9d168222016-08-05 17:44:54 +00004804 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004805 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004806 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4807 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004808 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004809 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4810 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004811 SemaRef.AddInitializerToDecl(LBDecl,
4812 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4813 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004814
4815 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004816 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4817 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004818 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004819 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004820
4821 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4822 // This will be used to implement clause 'lastprivate'.
4823 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004824 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4825 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004826 SemaRef.AddInitializerToDecl(ILDecl,
4827 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4828 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004829
4830 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004831 VarDecl *STDecl =
4832 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4833 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004834 SemaRef.AddInitializerToDecl(STDecl,
4835 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4836 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004837
4838 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004839 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004840 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4841 UB.get(), LastIteration.get());
4842 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4843 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4844 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4845 CondOp.get());
4846 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004847
4848 // If we have a combined directive that combines 'distribute', 'for' or
4849 // 'simd' we need to be able to access the bounds of the schedule of the
4850 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4851 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4852 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004853
Carlo Bertolliffafe102017-04-20 00:39:39 +00004854 // Lower bound variable, initialized with zero.
4855 VarDecl *CombLBDecl =
4856 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4857 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4858 SemaRef.AddInitializerToDecl(
4859 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4860 /*DirectInit*/ false);
4861
4862 // Upper bound variable, initialized with last iteration number.
4863 VarDecl *CombUBDecl =
4864 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4865 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4866 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4867 /*DirectInit*/ false);
4868
4869 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4870 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4871 ExprResult CombCondOp =
4872 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4873 LastIteration.get(), CombUB.get());
4874 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4875 CombCondOp.get());
4876 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4877
4878 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004879 // We expect to have at least 2 more parameters than the 'parallel'
4880 // directive does - the lower and upper bounds of the previous schedule.
4881 assert(CD->getNumParams() >= 4 &&
4882 "Unexpected number of parameters in loop combined directive");
4883
4884 // Set the proper type for the bounds given what we learned from the
4885 // enclosed loops.
4886 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4887 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4888
4889 // Previous lower and upper bounds are obtained from the region
4890 // parameters.
4891 PrevLB =
4892 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4893 PrevUB =
4894 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4895 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004896 }
4897
4898 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004899 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004900 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004901 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004902 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4903 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004904 Expr *RHS =
4905 (isOpenMPWorksharingDirective(DKind) ||
4906 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4907 ? LB.get()
4908 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004909 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4910 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004911
4912 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4913 Expr *CombRHS =
4914 (isOpenMPWorksharingDirective(DKind) ||
4915 isOpenMPTaskLoopDirective(DKind) ||
4916 isOpenMPDistributeDirective(DKind))
4917 ? CombLB.get()
4918 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4919 CombInit =
4920 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4921 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4922 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004923 }
4924
Alexander Musmanc6388682014-12-15 07:07:06 +00004925 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004926 SourceLocation CondLoc = AStmt->getLocStart();
Alexander Musmanc6388682014-12-15 07:07:06 +00004927 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004928 (isOpenMPWorksharingDirective(DKind) ||
4929 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004930 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4931 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4932 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004933 ExprResult CombCond;
4934 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4935 CombCond =
4936 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4937 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004938 // Loop increment (IV = IV + 1)
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004939 SourceLocation IncLoc = AStmt->getLocStart();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004940 ExprResult Inc =
4941 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4942 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4943 if (!Inc.isUsable())
4944 return 0;
4945 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004946 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4947 if (!Inc.isUsable())
4948 return 0;
4949
4950 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4951 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004952 // In combined construct, add combined version that use CombLB and CombUB
4953 // base variables for the update
4954 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004955 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4956 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004957 // LB + ST
4958 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4959 if (!NextLB.isUsable())
4960 return 0;
4961 // LB = LB + ST
4962 NextLB =
4963 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4964 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4965 if (!NextLB.isUsable())
4966 return 0;
4967 // UB + ST
4968 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4969 if (!NextUB.isUsable())
4970 return 0;
4971 // UB = UB + ST
4972 NextUB =
4973 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4974 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4975 if (!NextUB.isUsable())
4976 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004977 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4978 CombNextLB =
4979 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4980 if (!NextLB.isUsable())
4981 return 0;
4982 // LB = LB + ST
4983 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4984 CombNextLB.get());
4985 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4986 if (!CombNextLB.isUsable())
4987 return 0;
4988 // UB + ST
4989 CombNextUB =
4990 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4991 if (!CombNextUB.isUsable())
4992 return 0;
4993 // UB = UB + ST
4994 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4995 CombNextUB.get());
4996 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4997 if (!CombNextUB.isUsable())
4998 return 0;
4999 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005000 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005001
Carlo Bertolliffafe102017-04-20 00:39:39 +00005002 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005003 // directive with for as IV = IV + ST; ensure upper bound expression based
5004 // on PrevUB instead of NumIterations - used to implement 'for' when found
5005 // in combination with 'distribute', like in 'distribute parallel for'
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005006 SourceLocation DistIncLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005007 ExprResult DistCond, DistInc, PrevEUB;
5008 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5009 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5010 assert(DistCond.isUsable() && "distribute cond expr was not built");
5011
5012 DistInc =
5013 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5014 assert(DistInc.isUsable() && "distribute inc expr was not built");
5015 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5016 DistInc.get());
5017 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5018 assert(DistInc.isUsable() && "distribute inc expr was not built");
5019
5020 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5021 // construct
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005022 SourceLocation DistEUBLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005023 ExprResult IsUBGreater =
5024 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5025 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5026 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5027 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5028 CondOp.get());
5029 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5030 }
5031
Alexander Musmana5f070a2014-10-01 06:03:56 +00005032 // Build updates and final values of the loop counters.
5033 bool HasErrors = false;
5034 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005035 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005036 Built.Updates.resize(NestedLoopCount);
5037 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00005038 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005039 {
5040 ExprResult Div;
5041 // Go from inner nested loop to outer.
5042 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5043 LoopIterationSpace &IS = IterSpaces[Cnt];
5044 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5045 // Build: Iter = (IV / Div) % IS.NumIters
5046 // where Div is product of previous iterations' IS.NumIters.
5047 ExprResult Iter;
5048 if (Div.isUsable()) {
5049 Iter =
5050 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5051 } else {
5052 Iter = IV;
5053 assert((Cnt == (int)NestedLoopCount - 1) &&
5054 "unusable div expected on first iteration only");
5055 }
5056
5057 if (Cnt != 0 && Iter.isUsable())
5058 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5059 IS.NumIterations);
5060 if (!Iter.isUsable()) {
5061 HasErrors = true;
5062 break;
5063 }
5064
Alexey Bataev39f915b82015-05-08 10:41:21 +00005065 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005066 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5067 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
5068 IS.CounterVar->getExprLoc(),
5069 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005070 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005071 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005072 if (!Init.isUsable()) {
5073 HasErrors = true;
5074 break;
5075 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00005076 ExprResult Update = BuildCounterUpdate(
5077 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5078 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005079 if (!Update.isUsable()) {
5080 HasErrors = true;
5081 break;
5082 }
5083
5084 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5085 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005086 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005087 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005088 if (!Final.isUsable()) {
5089 HasErrors = true;
5090 break;
5091 }
5092
5093 // Build Div for the next iteration: Div <- Div * IS.NumIters
5094 if (Cnt != 0) {
5095 if (Div.isUnset())
5096 Div = IS.NumIterations;
5097 else
5098 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5099 IS.NumIterations);
5100
5101 // Add parentheses (for debugging purposes only).
5102 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00005103 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005104 if (!Div.isUsable()) {
5105 HasErrors = true;
5106 break;
5107 }
Alexey Bataev8b427062016-05-25 12:36:08 +00005108 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005109 }
5110 if (!Update.isUsable() || !Final.isUsable()) {
5111 HasErrors = true;
5112 break;
5113 }
5114 // Save results
5115 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005116 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005117 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005118 Built.Updates[Cnt] = Update.get();
5119 Built.Finals[Cnt] = Final.get();
5120 }
5121 }
5122
5123 if (HasErrors)
5124 return 0;
5125
5126 // Save results
5127 Built.IterationVarRef = IV.get();
5128 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005129 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005130 Built.CalcLastIteration =
5131 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005132 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005133 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005134 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005135 Built.Init = Init.get();
5136 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005137 Built.LB = LB.get();
5138 Built.UB = UB.get();
5139 Built.IL = IL.get();
5140 Built.ST = ST.get();
5141 Built.EUB = EUB.get();
5142 Built.NLB = NextLB.get();
5143 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005144 Built.PrevLB = PrevLB.get();
5145 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005146 Built.DistInc = DistInc.get();
5147 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005148 Built.DistCombinedFields.LB = CombLB.get();
5149 Built.DistCombinedFields.UB = CombUB.get();
5150 Built.DistCombinedFields.EUB = CombEUB.get();
5151 Built.DistCombinedFields.Init = CombInit.get();
5152 Built.DistCombinedFields.Cond = CombCond.get();
5153 Built.DistCombinedFields.NLB = CombNextLB.get();
5154 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005155
Alexey Bataev8b427062016-05-25 12:36:08 +00005156 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5157 // Fill data for doacross depend clauses.
5158 for (auto Pair : DSA.getDoacrossDependClauses()) {
5159 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5160 Pair.first->setCounterValue(CounterVal);
5161 else {
5162 if (NestedLoopCount != Pair.second.size() ||
5163 NestedLoopCount != LoopMultipliers.size() + 1) {
5164 // Erroneous case - clause has some problems.
5165 Pair.first->setCounterValue(CounterVal);
5166 continue;
5167 }
5168 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5169 auto I = Pair.second.rbegin();
5170 auto IS = IterSpaces.rbegin();
5171 auto ILM = LoopMultipliers.rbegin();
5172 Expr *UpCounterVal = CounterVal;
5173 Expr *Multiplier = nullptr;
5174 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5175 if (I->first) {
5176 assert(IS->CounterStep);
5177 Expr *NormalizedOffset =
5178 SemaRef
5179 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5180 I->first, IS->CounterStep)
5181 .get();
5182 if (Multiplier) {
5183 NormalizedOffset =
5184 SemaRef
5185 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5186 NormalizedOffset, Multiplier)
5187 .get();
5188 }
5189 assert(I->second == OO_Plus || I->second == OO_Minus);
5190 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005191 UpCounterVal = SemaRef
5192 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5193 UpCounterVal, NormalizedOffset)
5194 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005195 }
5196 Multiplier = *ILM;
5197 ++I;
5198 ++IS;
5199 ++ILM;
5200 }
5201 Pair.first->setCounterValue(UpCounterVal);
5202 }
5203 }
5204
Alexey Bataevabfc0692014-06-25 06:52:00 +00005205 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005206}
5207
Alexey Bataev10e775f2015-07-30 11:36:16 +00005208static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005209 auto CollapseClauses =
5210 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5211 if (CollapseClauses.begin() != CollapseClauses.end())
5212 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005213 return nullptr;
5214}
5215
Alexey Bataev10e775f2015-07-30 11:36:16 +00005216static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005217 auto OrderedClauses =
5218 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5219 if (OrderedClauses.begin() != OrderedClauses.end())
5220 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005221 return nullptr;
5222}
5223
Kelvin Lic5609492016-07-15 04:39:07 +00005224static bool checkSimdlenSafelenSpecified(Sema &S,
5225 const ArrayRef<OMPClause *> Clauses) {
5226 OMPSafelenClause *Safelen = nullptr;
5227 OMPSimdlenClause *Simdlen = nullptr;
5228
5229 for (auto *Clause : Clauses) {
5230 if (Clause->getClauseKind() == OMPC_safelen)
5231 Safelen = cast<OMPSafelenClause>(Clause);
5232 else if (Clause->getClauseKind() == OMPC_simdlen)
5233 Simdlen = cast<OMPSimdlenClause>(Clause);
5234 if (Safelen && Simdlen)
5235 break;
5236 }
5237
5238 if (Simdlen && Safelen) {
5239 llvm::APSInt SimdlenRes, SafelenRes;
5240 auto SimdlenLength = Simdlen->getSimdlen();
5241 auto SafelenLength = Safelen->getSafelen();
5242 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5243 SimdlenLength->isInstantiationDependent() ||
5244 SimdlenLength->containsUnexpandedParameterPack())
5245 return false;
5246 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5247 SafelenLength->isInstantiationDependent() ||
5248 SafelenLength->containsUnexpandedParameterPack())
5249 return false;
5250 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5251 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5252 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5253 // If both simdlen and safelen clauses are specified, the value of the
5254 // simdlen parameter must be less than or equal to the value of the safelen
5255 // parameter.
5256 if (SimdlenRes > SafelenRes) {
5257 S.Diag(SimdlenLength->getExprLoc(),
5258 diag::err_omp_wrong_simdlen_safelen_values)
5259 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5260 return true;
5261 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005262 }
5263 return false;
5264}
5265
Alexey Bataev4acb8592014-07-07 13:01:15 +00005266StmtResult Sema::ActOnOpenMPSimdDirective(
5267 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5268 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005269 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005270 if (!AStmt)
5271 return StmtError();
5272
5273 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005274 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005275 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5276 // define the nested loops number.
5277 unsigned NestedLoopCount = CheckOpenMPLoop(
5278 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5279 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005280 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005281 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005282
Alexander Musmana5f070a2014-10-01 06:03:56 +00005283 assert((CurContext->isDependentContext() || B.builtAll()) &&
5284 "omp simd loop exprs were not built");
5285
Alexander Musman3276a272015-03-21 10:12:56 +00005286 if (!CurContext->isDependentContext()) {
5287 // Finalize the clauses that need pre-built expressions for CodeGen.
5288 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005289 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005290 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005291 B.NumIterations, *this, CurScope,
5292 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005293 return StmtError();
5294 }
5295 }
5296
Kelvin Lic5609492016-07-15 04:39:07 +00005297 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005298 return StmtError();
5299
Reid Kleckner87a31802018-03-12 21:43:02 +00005300 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005301 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5302 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005303}
5304
Alexey Bataev4acb8592014-07-07 13:01:15 +00005305StmtResult Sema::ActOnOpenMPForDirective(
5306 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5307 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005308 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005309 if (!AStmt)
5310 return StmtError();
5311
5312 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005313 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5315 // define the nested loops number.
5316 unsigned NestedLoopCount = CheckOpenMPLoop(
5317 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5318 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005319 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005320 return StmtError();
5321
Alexander Musmana5f070a2014-10-01 06:03:56 +00005322 assert((CurContext->isDependentContext() || B.builtAll()) &&
5323 "omp for loop exprs were not built");
5324
Alexey Bataev54acd402015-08-04 11:18:19 +00005325 if (!CurContext->isDependentContext()) {
5326 // Finalize the clauses that need pre-built expressions for CodeGen.
5327 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005328 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005329 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005330 B.NumIterations, *this, CurScope,
5331 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005332 return StmtError();
5333 }
5334 }
5335
Reid Kleckner87a31802018-03-12 21:43:02 +00005336 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005337 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005338 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005339}
5340
Alexander Musmanf82886e2014-09-18 05:12:34 +00005341StmtResult Sema::ActOnOpenMPForSimdDirective(
5342 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5343 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005344 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005345 if (!AStmt)
5346 return StmtError();
5347
5348 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005349 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005350 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5351 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005352 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005353 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5354 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5355 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005356 if (NestedLoopCount == 0)
5357 return StmtError();
5358
Alexander Musmanc6388682014-12-15 07:07:06 +00005359 assert((CurContext->isDependentContext() || B.builtAll()) &&
5360 "omp for simd loop exprs were not built");
5361
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005362 if (!CurContext->isDependentContext()) {
5363 // Finalize the clauses that need pre-built expressions for CodeGen.
5364 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005365 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005366 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005367 B.NumIterations, *this, CurScope,
5368 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005369 return StmtError();
5370 }
5371 }
5372
Kelvin Lic5609492016-07-15 04:39:07 +00005373 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005374 return StmtError();
5375
Reid Kleckner87a31802018-03-12 21:43:02 +00005376 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005377 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5378 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005379}
5380
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005381StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5382 Stmt *AStmt,
5383 SourceLocation StartLoc,
5384 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005385 if (!AStmt)
5386 return StmtError();
5387
5388 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005389 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005390 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005391 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005392 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005393 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005394 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005395 return StmtError();
5396 // All associated statements must be '#pragma omp section' except for
5397 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005398 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005399 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5400 if (SectionStmt)
5401 Diag(SectionStmt->getLocStart(),
5402 diag::err_omp_sections_substmt_not_section);
5403 return StmtError();
5404 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005405 cast<OMPSectionDirective>(SectionStmt)
5406 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005407 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005408 } else {
5409 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5410 return StmtError();
5411 }
5412
Reid Kleckner87a31802018-03-12 21:43:02 +00005413 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005414
Alexey Bataev25e5b442015-09-15 12:52:43 +00005415 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5416 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005417}
5418
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005419StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5420 SourceLocation StartLoc,
5421 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005422 if (!AStmt)
5423 return StmtError();
5424
5425 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005426
Reid Kleckner87a31802018-03-12 21:43:02 +00005427 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005428 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005429
Alexey Bataev25e5b442015-09-15 12:52:43 +00005430 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5431 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005432}
5433
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005434StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5435 Stmt *AStmt,
5436 SourceLocation StartLoc,
5437 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005438 if (!AStmt)
5439 return StmtError();
5440
5441 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005442
Reid Kleckner87a31802018-03-12 21:43:02 +00005443 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005444
Alexey Bataev3255bf32015-01-19 05:20:46 +00005445 // OpenMP [2.7.3, single Construct, Restrictions]
5446 // The copyprivate clause must not be used with the nowait clause.
5447 OMPClause *Nowait = nullptr;
5448 OMPClause *Copyprivate = nullptr;
5449 for (auto *Clause : Clauses) {
5450 if (Clause->getClauseKind() == OMPC_nowait)
5451 Nowait = Clause;
5452 else if (Clause->getClauseKind() == OMPC_copyprivate)
5453 Copyprivate = Clause;
5454 if (Copyprivate && Nowait) {
5455 Diag(Copyprivate->getLocStart(),
5456 diag::err_omp_single_copyprivate_with_nowait);
5457 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5458 return StmtError();
5459 }
5460 }
5461
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005462 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5463}
5464
Alexander Musman80c22892014-07-17 08:54:58 +00005465StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5466 SourceLocation StartLoc,
5467 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005468 if (!AStmt)
5469 return StmtError();
5470
5471 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005472
Reid Kleckner87a31802018-03-12 21:43:02 +00005473 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00005474
5475 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5476}
5477
Alexey Bataev28c75412015-12-15 08:19:24 +00005478StmtResult Sema::ActOnOpenMPCriticalDirective(
5479 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5480 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005481 if (!AStmt)
5482 return StmtError();
5483
5484 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005485
Alexey Bataev28c75412015-12-15 08:19:24 +00005486 bool ErrorFound = false;
5487 llvm::APSInt Hint;
5488 SourceLocation HintLoc;
5489 bool DependentHint = false;
5490 for (auto *C : Clauses) {
5491 if (C->getClauseKind() == OMPC_hint) {
5492 if (!DirName.getName()) {
5493 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5494 ErrorFound = true;
5495 }
5496 Expr *E = cast<OMPHintClause>(C)->getHint();
5497 if (E->isTypeDependent() || E->isValueDependent() ||
5498 E->isInstantiationDependent())
5499 DependentHint = true;
5500 else {
5501 Hint = E->EvaluateKnownConstInt(Context);
5502 HintLoc = C->getLocStart();
5503 }
5504 }
5505 }
5506 if (ErrorFound)
5507 return StmtError();
5508 auto Pair = DSAStack->getCriticalWithHint(DirName);
5509 if (Pair.first && DirName.getName() && !DependentHint) {
5510 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5511 Diag(StartLoc, diag::err_omp_critical_with_hint);
5512 if (HintLoc.isValid()) {
5513 Diag(HintLoc, diag::note_omp_critical_hint_here)
5514 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5515 } else
5516 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5517 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5518 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5519 << 1
5520 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5521 /*Radix=*/10, /*Signed=*/false);
5522 } else
5523 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5524 }
5525 }
5526
Reid Kleckner87a31802018-03-12 21:43:02 +00005527 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005528
Alexey Bataev28c75412015-12-15 08:19:24 +00005529 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5530 Clauses, AStmt);
5531 if (!Pair.first && DirName.getName() && !DependentHint)
5532 DSAStack->addCriticalWithHint(Dir, Hint);
5533 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005534}
5535
Alexey Bataev4acb8592014-07-07 13:01:15 +00005536StmtResult Sema::ActOnOpenMPParallelForDirective(
5537 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5538 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005539 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005540 if (!AStmt)
5541 return StmtError();
5542
Alexey Bataev4acb8592014-07-07 13:01:15 +00005543 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5544 // 1.2.2 OpenMP Language Terminology
5545 // Structured block - An executable statement with a single entry at the
5546 // top and a single exit at the bottom.
5547 // The point of exit cannot be a branch out of the structured block.
5548 // longjmp() and throw() must not violate the entry/exit criteria.
5549 CS->getCapturedDecl()->setNothrow();
5550
Alexander Musmanc6388682014-12-15 07:07:06 +00005551 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005552 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5553 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005554 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005555 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5556 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5557 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005558 if (NestedLoopCount == 0)
5559 return StmtError();
5560
Alexander Musmana5f070a2014-10-01 06:03:56 +00005561 assert((CurContext->isDependentContext() || B.builtAll()) &&
5562 "omp parallel for loop exprs were not built");
5563
Alexey Bataev54acd402015-08-04 11:18:19 +00005564 if (!CurContext->isDependentContext()) {
5565 // Finalize the clauses that need pre-built expressions for CodeGen.
5566 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005567 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005568 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005569 B.NumIterations, *this, CurScope,
5570 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005571 return StmtError();
5572 }
5573 }
5574
Reid Kleckner87a31802018-03-12 21:43:02 +00005575 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005576 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005577 NestedLoopCount, Clauses, AStmt, B,
5578 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005579}
5580
Alexander Musmane4e893b2014-09-23 09:33:00 +00005581StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5582 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5583 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005584 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005585 if (!AStmt)
5586 return StmtError();
5587
Alexander Musmane4e893b2014-09-23 09:33:00 +00005588 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5589 // 1.2.2 OpenMP Language Terminology
5590 // Structured block - An executable statement with a single entry at the
5591 // top and a single exit at the bottom.
5592 // The point of exit cannot be a branch out of the structured block.
5593 // longjmp() and throw() must not violate the entry/exit criteria.
5594 CS->getCapturedDecl()->setNothrow();
5595
Alexander Musmanc6388682014-12-15 07:07:06 +00005596 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005597 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5598 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005599 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005600 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5601 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5602 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005603 if (NestedLoopCount == 0)
5604 return StmtError();
5605
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005606 if (!CurContext->isDependentContext()) {
5607 // Finalize the clauses that need pre-built expressions for CodeGen.
5608 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005609 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005610 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005611 B.NumIterations, *this, CurScope,
5612 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005613 return StmtError();
5614 }
5615 }
5616
Kelvin Lic5609492016-07-15 04:39:07 +00005617 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005618 return StmtError();
5619
Reid Kleckner87a31802018-03-12 21:43:02 +00005620 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005621 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005622 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005623}
5624
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005625StmtResult
5626Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5627 Stmt *AStmt, SourceLocation StartLoc,
5628 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005629 if (!AStmt)
5630 return StmtError();
5631
5632 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005633 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005634 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005635 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005636 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005637 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005638 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005639 return StmtError();
5640 // All associated statements must be '#pragma omp section' except for
5641 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005642 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005643 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5644 if (SectionStmt)
5645 Diag(SectionStmt->getLocStart(),
5646 diag::err_omp_parallel_sections_substmt_not_section);
5647 return StmtError();
5648 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005649 cast<OMPSectionDirective>(SectionStmt)
5650 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005651 }
5652 } else {
5653 Diag(AStmt->getLocStart(),
5654 diag::err_omp_parallel_sections_not_compound_stmt);
5655 return StmtError();
5656 }
5657
Reid Kleckner87a31802018-03-12 21:43:02 +00005658 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005659
Alexey Bataev25e5b442015-09-15 12:52:43 +00005660 return OMPParallelSectionsDirective::Create(
5661 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005662}
5663
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005664StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5665 Stmt *AStmt, SourceLocation StartLoc,
5666 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005667 if (!AStmt)
5668 return StmtError();
5669
David Majnemer9d168222016-08-05 17:44:54 +00005670 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005671 // 1.2.2 OpenMP Language Terminology
5672 // Structured block - An executable statement with a single entry at the
5673 // top and a single exit at the bottom.
5674 // The point of exit cannot be a branch out of the structured block.
5675 // longjmp() and throw() must not violate the entry/exit criteria.
5676 CS->getCapturedDecl()->setNothrow();
5677
Reid Kleckner87a31802018-03-12 21:43:02 +00005678 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005679
Alexey Bataev25e5b442015-09-15 12:52:43 +00005680 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5681 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005682}
5683
Alexey Bataev68446b72014-07-18 07:47:19 +00005684StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5685 SourceLocation EndLoc) {
5686 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5687}
5688
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005689StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5690 SourceLocation EndLoc) {
5691 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5692}
5693
Alexey Bataev2df347a2014-07-18 10:17:07 +00005694StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5695 SourceLocation EndLoc) {
5696 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5697}
5698
Alexey Bataev169d96a2017-07-18 20:17:46 +00005699StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5700 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005701 SourceLocation StartLoc,
5702 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005703 if (!AStmt)
5704 return StmtError();
5705
5706 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005707
Reid Kleckner87a31802018-03-12 21:43:02 +00005708 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005709
Alexey Bataev169d96a2017-07-18 20:17:46 +00005710 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005711 AStmt,
5712 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005713}
5714
Alexey Bataev6125da92014-07-21 11:26:11 +00005715StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5716 SourceLocation StartLoc,
5717 SourceLocation EndLoc) {
5718 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5719 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5720}
5721
Alexey Bataev346265e2015-09-25 10:37:12 +00005722StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5723 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005724 SourceLocation StartLoc,
5725 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005726 OMPClause *DependFound = nullptr;
5727 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005728 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005729 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005730 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005731 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005732 for (auto *C : Clauses) {
5733 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5734 DependFound = C;
5735 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5736 if (DependSourceClause) {
5737 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5738 << getOpenMPDirectiveName(OMPD_ordered)
5739 << getOpenMPClauseName(OMPC_depend) << 2;
5740 ErrorFound = true;
5741 } else
5742 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005743 if (DependSinkClause) {
5744 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5745 << 0;
5746 ErrorFound = true;
5747 }
5748 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5749 if (DependSourceClause) {
5750 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5751 << 1;
5752 ErrorFound = true;
5753 }
5754 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005755 }
5756 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005757 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005758 else if (C->getClauseKind() == OMPC_simd)
5759 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005760 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005761 if (!ErrorFound && !SC &&
5762 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005763 // OpenMP [2.8.1,simd Construct, Restrictions]
5764 // An ordered construct with the simd clause is the only OpenMP construct
5765 // that can appear in the simd region.
5766 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005767 ErrorFound = true;
5768 } else if (DependFound && (TC || SC)) {
5769 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5770 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5771 ErrorFound = true;
5772 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5773 Diag(DependFound->getLocStart(),
5774 diag::err_omp_ordered_directive_without_param);
5775 ErrorFound = true;
5776 } else if (TC || Clauses.empty()) {
5777 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5778 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5779 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5780 << (TC != nullptr);
5781 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5782 ErrorFound = true;
5783 }
5784 }
5785 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005786 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005787
5788 if (AStmt) {
5789 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5790
Reid Kleckner87a31802018-03-12 21:43:02 +00005791 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005792 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005793
5794 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005795}
5796
Alexey Bataev1d160b12015-03-13 12:27:31 +00005797namespace {
5798/// \brief Helper class for checking expression in 'omp atomic [update]'
5799/// construct.
5800class OpenMPAtomicUpdateChecker {
5801 /// \brief Error results for atomic update expressions.
5802 enum ExprAnalysisErrorCode {
5803 /// \brief A statement is not an expression statement.
5804 NotAnExpression,
5805 /// \brief Expression is not builtin binary or unary operation.
5806 NotABinaryOrUnaryExpression,
5807 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5808 NotAnUnaryIncDecExpression,
5809 /// \brief An expression is not of scalar type.
5810 NotAScalarType,
5811 /// \brief A binary operation is not an assignment operation.
5812 NotAnAssignmentOp,
5813 /// \brief RHS part of the binary operation is not a binary expression.
5814 NotABinaryExpression,
5815 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5816 /// expression.
5817 NotABinaryOperator,
5818 /// \brief RHS binary operation does not have reference to the updated LHS
5819 /// part.
5820 NotAnUpdateExpression,
5821 /// \brief No errors is found.
5822 NoError
5823 };
5824 /// \brief Reference to Sema.
5825 Sema &SemaRef;
5826 /// \brief A location for note diagnostics (when error is found).
5827 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005828 /// \brief 'x' lvalue part of the source atomic expression.
5829 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005830 /// \brief 'expr' rvalue part of the source atomic expression.
5831 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005832 /// \brief Helper expression of the form
5833 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5834 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5835 Expr *UpdateExpr;
5836 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5837 /// important for non-associative operations.
5838 bool IsXLHSInRHSPart;
5839 BinaryOperatorKind Op;
5840 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005841 /// \brief true if the source expression is a postfix unary operation, false
5842 /// if it is a prefix unary operation.
5843 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005844
5845public:
5846 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005847 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005848 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005849 /// \brief Check specified statement that it is suitable for 'atomic update'
5850 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005851 /// expression. If DiagId and NoteId == 0, then only check is performed
5852 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005853 /// \param DiagId Diagnostic which should be emitted if error is found.
5854 /// \param NoteId Diagnostic note for the main error message.
5855 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005856 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005857 /// \brief Return the 'x' lvalue part of the source atomic expression.
5858 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005859 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5860 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005861 /// \brief Return the update expression used in calculation of the updated
5862 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5863 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5864 Expr *getUpdateExpr() const { return UpdateExpr; }
5865 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5866 /// false otherwise.
5867 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5868
Alexey Bataevb78ca832015-04-01 03:33:17 +00005869 /// \brief true if the source expression is a postfix unary operation, false
5870 /// if it is a prefix unary operation.
5871 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5872
Alexey Bataev1d160b12015-03-13 12:27:31 +00005873private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005874 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5875 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005876};
5877} // namespace
5878
5879bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5880 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5881 ExprAnalysisErrorCode ErrorFound = NoError;
5882 SourceLocation ErrorLoc, NoteLoc;
5883 SourceRange ErrorRange, NoteRange;
5884 // Allowed constructs are:
5885 // x = x binop expr;
5886 // x = expr binop x;
5887 if (AtomicBinOp->getOpcode() == BO_Assign) {
5888 X = AtomicBinOp->getLHS();
5889 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5890 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5891 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5892 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5893 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005894 Op = AtomicInnerBinOp->getOpcode();
5895 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005896 auto *LHS = AtomicInnerBinOp->getLHS();
5897 auto *RHS = AtomicInnerBinOp->getRHS();
5898 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5899 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5900 /*Canonical=*/true);
5901 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5902 /*Canonical=*/true);
5903 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5904 /*Canonical=*/true);
5905 if (XId == LHSId) {
5906 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005907 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005908 } else if (XId == RHSId) {
5909 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005910 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005911 } else {
5912 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5913 ErrorRange = AtomicInnerBinOp->getSourceRange();
5914 NoteLoc = X->getExprLoc();
5915 NoteRange = X->getSourceRange();
5916 ErrorFound = NotAnUpdateExpression;
5917 }
5918 } else {
5919 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5920 ErrorRange = AtomicInnerBinOp->getSourceRange();
5921 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5922 NoteRange = SourceRange(NoteLoc, NoteLoc);
5923 ErrorFound = NotABinaryOperator;
5924 }
5925 } else {
5926 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5927 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5928 ErrorFound = NotABinaryExpression;
5929 }
5930 } else {
5931 ErrorLoc = AtomicBinOp->getExprLoc();
5932 ErrorRange = AtomicBinOp->getSourceRange();
5933 NoteLoc = AtomicBinOp->getOperatorLoc();
5934 NoteRange = SourceRange(NoteLoc, NoteLoc);
5935 ErrorFound = NotAnAssignmentOp;
5936 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005937 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005938 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5939 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5940 return true;
5941 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005942 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005943 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005944}
5945
5946bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5947 unsigned NoteId) {
5948 ExprAnalysisErrorCode ErrorFound = NoError;
5949 SourceLocation ErrorLoc, NoteLoc;
5950 SourceRange ErrorRange, NoteRange;
5951 // Allowed constructs are:
5952 // x++;
5953 // x--;
5954 // ++x;
5955 // --x;
5956 // x binop= expr;
5957 // x = x binop expr;
5958 // x = expr binop x;
5959 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5960 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5961 if (AtomicBody->getType()->isScalarType() ||
5962 AtomicBody->isInstantiationDependent()) {
5963 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5964 AtomicBody->IgnoreParenImpCasts())) {
5965 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005966 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005967 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005968 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005969 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005970 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005971 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005972 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5973 AtomicBody->IgnoreParenImpCasts())) {
5974 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005975 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005976 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005977 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5978 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005979 // Check for Unary Operation
5980 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005981 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005982 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5983 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005984 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005985 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5986 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005987 } else {
5988 ErrorFound = NotAnUnaryIncDecExpression;
5989 ErrorLoc = AtomicUnaryOp->getExprLoc();
5990 ErrorRange = AtomicUnaryOp->getSourceRange();
5991 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5992 NoteRange = SourceRange(NoteLoc, NoteLoc);
5993 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005994 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005995 ErrorFound = NotABinaryOrUnaryExpression;
5996 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5997 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5998 }
5999 } else {
6000 ErrorFound = NotAScalarType;
6001 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
6002 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6003 }
6004 } else {
6005 ErrorFound = NotAnExpression;
6006 NoteLoc = ErrorLoc = S->getLocStart();
6007 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6008 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006009 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006010 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6011 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6012 return true;
6013 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006014 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006015 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006016 // Build an update expression of form 'OpaqueValueExpr(x) binop
6017 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6018 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6019 auto *OVEX = new (SemaRef.getASTContext())
6020 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6021 auto *OVEExpr = new (SemaRef.getASTContext())
6022 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6023 auto Update =
6024 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6025 IsXLHSInRHSPart ? OVEExpr : OVEX);
6026 if (Update.isInvalid())
6027 return true;
6028 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6029 Sema::AA_Casting);
6030 if (Update.isInvalid())
6031 return true;
6032 UpdateExpr = Update.get();
6033 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006034 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006035}
6036
Alexey Bataev0162e452014-07-22 10:10:35 +00006037StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6038 Stmt *AStmt,
6039 SourceLocation StartLoc,
6040 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006041 if (!AStmt)
6042 return StmtError();
6043
David Majnemer9d168222016-08-05 17:44:54 +00006044 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006045 // 1.2.2 OpenMP Language Terminology
6046 // Structured block - An executable statement with a single entry at the
6047 // top and a single exit at the bottom.
6048 // The point of exit cannot be a branch out of the structured block.
6049 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006050 OpenMPClauseKind AtomicKind = OMPC_unknown;
6051 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006052 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006053 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006054 C->getClauseKind() == OMPC_update ||
6055 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006056 if (AtomicKind != OMPC_unknown) {
6057 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6058 << SourceRange(C->getLocStart(), C->getLocEnd());
6059 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6060 << getOpenMPClauseName(AtomicKind);
6061 } else {
6062 AtomicKind = C->getClauseKind();
6063 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006064 }
6065 }
6066 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006067
Alexey Bataev459dec02014-07-24 06:46:57 +00006068 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006069 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6070 Body = EWC->getSubExpr();
6071
Alexey Bataev62cec442014-11-18 10:14:22 +00006072 Expr *X = nullptr;
6073 Expr *V = nullptr;
6074 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006075 Expr *UE = nullptr;
6076 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006077 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006078 // OpenMP [2.12.6, atomic Construct]
6079 // In the next expressions:
6080 // * x and v (as applicable) are both l-value expressions with scalar type.
6081 // * During the execution of an atomic region, multiple syntactic
6082 // occurrences of x must designate the same storage location.
6083 // * Neither of v and expr (as applicable) may access the storage location
6084 // designated by x.
6085 // * Neither of x and expr (as applicable) may access the storage location
6086 // designated by v.
6087 // * expr is an expression with scalar type.
6088 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6089 // * binop, binop=, ++, and -- are not overloaded operators.
6090 // * The expression x binop expr must be numerically equivalent to x binop
6091 // (expr). This requirement is satisfied if the operators in expr have
6092 // precedence greater than binop, or by using parentheses around expr or
6093 // subexpressions of expr.
6094 // * The expression expr binop x must be numerically equivalent to (expr)
6095 // binop x. This requirement is satisfied if the operators in expr have
6096 // precedence equal to or greater than binop, or by using parentheses around
6097 // expr or subexpressions of expr.
6098 // * For forms that allow multiple occurrences of x, the number of times
6099 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006100 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006101 enum {
6102 NotAnExpression,
6103 NotAnAssignmentOp,
6104 NotAScalarType,
6105 NotAnLValue,
6106 NoError
6107 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006108 SourceLocation ErrorLoc, NoteLoc;
6109 SourceRange ErrorRange, NoteRange;
6110 // If clause is read:
6111 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00006112 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6113 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006114 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6115 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6116 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6117 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6118 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6119 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6120 if (!X->isLValue() || !V->isLValue()) {
6121 auto NotLValueExpr = X->isLValue() ? V : X;
6122 ErrorFound = NotAnLValue;
6123 ErrorLoc = AtomicBinOp->getExprLoc();
6124 ErrorRange = AtomicBinOp->getSourceRange();
6125 NoteLoc = NotLValueExpr->getExprLoc();
6126 NoteRange = NotLValueExpr->getSourceRange();
6127 }
6128 } else if (!X->isInstantiationDependent() ||
6129 !V->isInstantiationDependent()) {
6130 auto NotScalarExpr =
6131 (X->isInstantiationDependent() || X->getType()->isScalarType())
6132 ? V
6133 : X;
6134 ErrorFound = NotAScalarType;
6135 ErrorLoc = AtomicBinOp->getExprLoc();
6136 ErrorRange = AtomicBinOp->getSourceRange();
6137 NoteLoc = NotScalarExpr->getExprLoc();
6138 NoteRange = NotScalarExpr->getSourceRange();
6139 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006140 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006141 ErrorFound = NotAnAssignmentOp;
6142 ErrorLoc = AtomicBody->getExprLoc();
6143 ErrorRange = AtomicBody->getSourceRange();
6144 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6145 : AtomicBody->getExprLoc();
6146 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6147 : AtomicBody->getSourceRange();
6148 }
6149 } else {
6150 ErrorFound = NotAnExpression;
6151 NoteLoc = ErrorLoc = Body->getLocStart();
6152 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006153 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006154 if (ErrorFound != NoError) {
6155 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6156 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006157 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6158 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006159 return StmtError();
6160 } else if (CurContext->isDependentContext())
6161 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006162 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006163 enum {
6164 NotAnExpression,
6165 NotAnAssignmentOp,
6166 NotAScalarType,
6167 NotAnLValue,
6168 NoError
6169 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006170 SourceLocation ErrorLoc, NoteLoc;
6171 SourceRange ErrorRange, NoteRange;
6172 // If clause is write:
6173 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00006174 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6175 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006176 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6177 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006178 X = AtomicBinOp->getLHS();
6179 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006180 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6181 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6182 if (!X->isLValue()) {
6183 ErrorFound = NotAnLValue;
6184 ErrorLoc = AtomicBinOp->getExprLoc();
6185 ErrorRange = AtomicBinOp->getSourceRange();
6186 NoteLoc = X->getExprLoc();
6187 NoteRange = X->getSourceRange();
6188 }
6189 } else if (!X->isInstantiationDependent() ||
6190 !E->isInstantiationDependent()) {
6191 auto NotScalarExpr =
6192 (X->isInstantiationDependent() || X->getType()->isScalarType())
6193 ? E
6194 : X;
6195 ErrorFound = NotAScalarType;
6196 ErrorLoc = AtomicBinOp->getExprLoc();
6197 ErrorRange = AtomicBinOp->getSourceRange();
6198 NoteLoc = NotScalarExpr->getExprLoc();
6199 NoteRange = NotScalarExpr->getSourceRange();
6200 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006201 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006202 ErrorFound = NotAnAssignmentOp;
6203 ErrorLoc = AtomicBody->getExprLoc();
6204 ErrorRange = AtomicBody->getSourceRange();
6205 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6206 : AtomicBody->getExprLoc();
6207 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6208 : AtomicBody->getSourceRange();
6209 }
6210 } else {
6211 ErrorFound = NotAnExpression;
6212 NoteLoc = ErrorLoc = Body->getLocStart();
6213 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006214 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006215 if (ErrorFound != NoError) {
6216 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6217 << ErrorRange;
6218 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6219 << NoteRange;
6220 return StmtError();
6221 } else if (CurContext->isDependentContext())
6222 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006223 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006224 // If clause is update:
6225 // x++;
6226 // x--;
6227 // ++x;
6228 // --x;
6229 // x binop= expr;
6230 // x = x binop expr;
6231 // x = expr binop x;
6232 OpenMPAtomicUpdateChecker Checker(*this);
6233 if (Checker.checkStatement(
6234 Body, (AtomicKind == OMPC_update)
6235 ? diag::err_omp_atomic_update_not_expression_statement
6236 : diag::err_omp_atomic_not_expression_statement,
6237 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006238 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006239 if (!CurContext->isDependentContext()) {
6240 E = Checker.getExpr();
6241 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006242 UE = Checker.getUpdateExpr();
6243 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006244 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006245 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006246 enum {
6247 NotAnAssignmentOp,
6248 NotACompoundStatement,
6249 NotTwoSubstatements,
6250 NotASpecificExpression,
6251 NoError
6252 } ErrorFound = NoError;
6253 SourceLocation ErrorLoc, NoteLoc;
6254 SourceRange ErrorRange, NoteRange;
6255 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6256 // If clause is a capture:
6257 // v = x++;
6258 // v = x--;
6259 // v = ++x;
6260 // v = --x;
6261 // v = x binop= expr;
6262 // v = x = x binop expr;
6263 // v = x = expr binop x;
6264 auto *AtomicBinOp =
6265 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6266 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6267 V = AtomicBinOp->getLHS();
6268 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6269 OpenMPAtomicUpdateChecker Checker(*this);
6270 if (Checker.checkStatement(
6271 Body, diag::err_omp_atomic_capture_not_expression_statement,
6272 diag::note_omp_atomic_update))
6273 return StmtError();
6274 E = Checker.getExpr();
6275 X = Checker.getX();
6276 UE = Checker.getUpdateExpr();
6277 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6278 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006279 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006280 ErrorLoc = AtomicBody->getExprLoc();
6281 ErrorRange = AtomicBody->getSourceRange();
6282 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6283 : AtomicBody->getExprLoc();
6284 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6285 : AtomicBody->getSourceRange();
6286 ErrorFound = NotAnAssignmentOp;
6287 }
6288 if (ErrorFound != NoError) {
6289 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6290 << ErrorRange;
6291 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6292 return StmtError();
6293 } else if (CurContext->isDependentContext()) {
6294 UE = V = E = X = nullptr;
6295 }
6296 } else {
6297 // If clause is a capture:
6298 // { v = x; x = expr; }
6299 // { v = x; x++; }
6300 // { v = x; x--; }
6301 // { v = x; ++x; }
6302 // { v = x; --x; }
6303 // { v = x; x binop= expr; }
6304 // { v = x; x = x binop expr; }
6305 // { v = x; x = expr binop x; }
6306 // { x++; v = x; }
6307 // { x--; v = x; }
6308 // { ++x; v = x; }
6309 // { --x; v = x; }
6310 // { x binop= expr; v = x; }
6311 // { x = x binop expr; v = x; }
6312 // { x = expr binop x; v = x; }
6313 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6314 // Check that this is { expr1; expr2; }
6315 if (CS->size() == 2) {
6316 auto *First = CS->body_front();
6317 auto *Second = CS->body_back();
6318 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6319 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6320 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6321 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6322 // Need to find what subexpression is 'v' and what is 'x'.
6323 OpenMPAtomicUpdateChecker Checker(*this);
6324 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6325 BinaryOperator *BinOp = nullptr;
6326 if (IsUpdateExprFound) {
6327 BinOp = dyn_cast<BinaryOperator>(First);
6328 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6329 }
6330 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6331 // { v = x; x++; }
6332 // { v = x; x--; }
6333 // { v = x; ++x; }
6334 // { v = x; --x; }
6335 // { v = x; x binop= expr; }
6336 // { v = x; x = x binop expr; }
6337 // { v = x; x = expr binop x; }
6338 // Check that the first expression has form v = x.
6339 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6340 llvm::FoldingSetNodeID XId, PossibleXId;
6341 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6342 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6343 IsUpdateExprFound = XId == PossibleXId;
6344 if (IsUpdateExprFound) {
6345 V = BinOp->getLHS();
6346 X = Checker.getX();
6347 E = Checker.getExpr();
6348 UE = Checker.getUpdateExpr();
6349 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006350 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006351 }
6352 }
6353 if (!IsUpdateExprFound) {
6354 IsUpdateExprFound = !Checker.checkStatement(First);
6355 BinOp = nullptr;
6356 if (IsUpdateExprFound) {
6357 BinOp = dyn_cast<BinaryOperator>(Second);
6358 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6359 }
6360 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6361 // { x++; v = x; }
6362 // { x--; v = x; }
6363 // { ++x; v = x; }
6364 // { --x; v = x; }
6365 // { x binop= expr; v = x; }
6366 // { x = x binop expr; v = x; }
6367 // { x = expr binop x; v = x; }
6368 // Check that the second expression has form v = x.
6369 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6370 llvm::FoldingSetNodeID XId, PossibleXId;
6371 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6372 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6373 IsUpdateExprFound = XId == PossibleXId;
6374 if (IsUpdateExprFound) {
6375 V = BinOp->getLHS();
6376 X = Checker.getX();
6377 E = Checker.getExpr();
6378 UE = Checker.getUpdateExpr();
6379 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006380 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006381 }
6382 }
6383 }
6384 if (!IsUpdateExprFound) {
6385 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006386 auto *FirstExpr = dyn_cast<Expr>(First);
6387 auto *SecondExpr = dyn_cast<Expr>(Second);
6388 if (!FirstExpr || !SecondExpr ||
6389 !(FirstExpr->isInstantiationDependent() ||
6390 SecondExpr->isInstantiationDependent())) {
6391 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6392 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006393 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006394 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6395 : First->getLocStart();
6396 NoteRange = ErrorRange = FirstBinOp
6397 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006398 : SourceRange(ErrorLoc, ErrorLoc);
6399 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006400 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6401 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6402 ErrorFound = NotAnAssignmentOp;
6403 NoteLoc = ErrorLoc = SecondBinOp
6404 ? SecondBinOp->getOperatorLoc()
6405 : Second->getLocStart();
6406 NoteRange = ErrorRange =
6407 SecondBinOp ? SecondBinOp->getSourceRange()
6408 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006409 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006410 auto *PossibleXRHSInFirst =
6411 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6412 auto *PossibleXLHSInSecond =
6413 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6414 llvm::FoldingSetNodeID X1Id, X2Id;
6415 PossibleXRHSInFirst->Profile(X1Id, Context,
6416 /*Canonical=*/true);
6417 PossibleXLHSInSecond->Profile(X2Id, Context,
6418 /*Canonical=*/true);
6419 IsUpdateExprFound = X1Id == X2Id;
6420 if (IsUpdateExprFound) {
6421 V = FirstBinOp->getLHS();
6422 X = SecondBinOp->getLHS();
6423 E = SecondBinOp->getRHS();
6424 UE = nullptr;
6425 IsXLHSInRHSPart = false;
6426 IsPostfixUpdate = true;
6427 } else {
6428 ErrorFound = NotASpecificExpression;
6429 ErrorLoc = FirstBinOp->getExprLoc();
6430 ErrorRange = FirstBinOp->getSourceRange();
6431 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6432 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6433 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006434 }
6435 }
6436 }
6437 }
6438 } else {
6439 NoteLoc = ErrorLoc = Body->getLocStart();
6440 NoteRange = ErrorRange =
6441 SourceRange(Body->getLocStart(), Body->getLocStart());
6442 ErrorFound = NotTwoSubstatements;
6443 }
6444 } else {
6445 NoteLoc = ErrorLoc = Body->getLocStart();
6446 NoteRange = ErrorRange =
6447 SourceRange(Body->getLocStart(), Body->getLocStart());
6448 ErrorFound = NotACompoundStatement;
6449 }
6450 if (ErrorFound != NoError) {
6451 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6452 << ErrorRange;
6453 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6454 return StmtError();
6455 } else if (CurContext->isDependentContext()) {
6456 UE = V = E = X = nullptr;
6457 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006458 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006459 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006460
Reid Kleckner87a31802018-03-12 21:43:02 +00006461 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00006462
Alexey Bataev62cec442014-11-18 10:14:22 +00006463 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006464 X, V, E, UE, IsXLHSInRHSPart,
6465 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006466}
6467
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006468StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6469 Stmt *AStmt,
6470 SourceLocation StartLoc,
6471 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006472 if (!AStmt)
6473 return StmtError();
6474
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006475 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6476 // 1.2.2 OpenMP Language Terminology
6477 // Structured block - An executable statement with a single entry at the
6478 // top and a single exit at the bottom.
6479 // The point of exit cannot be a branch out of the structured block.
6480 // longjmp() and throw() must not violate the entry/exit criteria.
6481 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006482 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6483 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6484 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6485 // 1.2.2 OpenMP Language Terminology
6486 // Structured block - An executable statement with a single entry at the
6487 // top and a single exit at the bottom.
6488 // The point of exit cannot be a branch out of the structured block.
6489 // longjmp() and throw() must not violate the entry/exit criteria.
6490 CS->getCapturedDecl()->setNothrow();
6491 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006492
Alexey Bataev13314bf2014-10-09 04:18:56 +00006493 // OpenMP [2.16, Nesting of Regions]
6494 // If specified, a teams construct must be contained within a target
6495 // construct. That target construct must contain no statements or directives
6496 // outside of the teams construct.
6497 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00006498 Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006499 bool OMPTeamsFound = true;
6500 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6501 auto I = CS->body_begin();
6502 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006503 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006504 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6505 OMPTeamsFound = false;
6506 break;
6507 }
6508 ++I;
6509 }
6510 assert(I != CS->body_end() && "Not found statement");
6511 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006512 } else {
6513 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6514 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006515 }
6516 if (!OMPTeamsFound) {
6517 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6518 Diag(DSAStack->getInnerTeamsRegionLoc(),
6519 diag::note_omp_nested_teams_construct_here);
6520 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6521 << isa<OMPExecutableDirective>(S);
6522 return StmtError();
6523 }
6524 }
6525
Reid Kleckner87a31802018-03-12 21:43:02 +00006526 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006527
6528 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6529}
6530
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006531StmtResult
6532Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6533 Stmt *AStmt, SourceLocation StartLoc,
6534 SourceLocation EndLoc) {
6535 if (!AStmt)
6536 return StmtError();
6537
6538 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6539 // 1.2.2 OpenMP Language Terminology
6540 // Structured block - An executable statement with a single entry at the
6541 // top and a single exit at the bottom.
6542 // The point of exit cannot be a branch out of the structured block.
6543 // longjmp() and throw() must not violate the entry/exit criteria.
6544 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006545 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6546 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6547 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6548 // 1.2.2 OpenMP Language Terminology
6549 // Structured block - An executable statement with a single entry at the
6550 // top and a single exit at the bottom.
6551 // The point of exit cannot be a branch out of the structured block.
6552 // longjmp() and throw() must not violate the entry/exit criteria.
6553 CS->getCapturedDecl()->setNothrow();
6554 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006555
Reid Kleckner87a31802018-03-12 21:43:02 +00006556 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006557
6558 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6559 AStmt);
6560}
6561
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006562StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6563 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6564 SourceLocation EndLoc,
6565 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6566 if (!AStmt)
6567 return StmtError();
6568
6569 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6570 // 1.2.2 OpenMP Language Terminology
6571 // Structured block - An executable statement with a single entry at the
6572 // top and a single exit at the bottom.
6573 // The point of exit cannot be a branch out of the structured block.
6574 // longjmp() and throw() must not violate the entry/exit criteria.
6575 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006576 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6577 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6578 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6579 // 1.2.2 OpenMP Language Terminology
6580 // Structured block - An executable statement with a single entry at the
6581 // top and a single exit at the bottom.
6582 // The point of exit cannot be a branch out of the structured block.
6583 // longjmp() and throw() must not violate the entry/exit criteria.
6584 CS->getCapturedDecl()->setNothrow();
6585 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006586
6587 OMPLoopDirective::HelperExprs B;
6588 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6589 // define the nested loops number.
6590 unsigned NestedLoopCount =
6591 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006592 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006593 VarsWithImplicitDSA, B);
6594 if (NestedLoopCount == 0)
6595 return StmtError();
6596
6597 assert((CurContext->isDependentContext() || B.builtAll()) &&
6598 "omp target parallel for loop exprs were not built");
6599
6600 if (!CurContext->isDependentContext()) {
6601 // Finalize the clauses that need pre-built expressions for CodeGen.
6602 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006603 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006604 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006605 B.NumIterations, *this, CurScope,
6606 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006607 return StmtError();
6608 }
6609 }
6610
Reid Kleckner87a31802018-03-12 21:43:02 +00006611 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006612 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6613 NestedLoopCount, Clauses, AStmt,
6614 B, DSAStack->isCancelRegion());
6615}
6616
Alexey Bataev95b64a92017-05-30 16:00:04 +00006617/// Check for existence of a map clause in the list of clauses.
6618static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6619 const OpenMPClauseKind K) {
6620 return llvm::any_of(
6621 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6622}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006623
Alexey Bataev95b64a92017-05-30 16:00:04 +00006624template <typename... Params>
6625static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6626 const Params... ClauseTypes) {
6627 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006628}
6629
Michael Wong65f367f2015-07-21 13:44:28 +00006630StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6631 Stmt *AStmt,
6632 SourceLocation StartLoc,
6633 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006634 if (!AStmt)
6635 return StmtError();
6636
6637 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6638
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006639 // OpenMP [2.10.1, Restrictions, p. 97]
6640 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006641 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6642 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6643 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006644 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006645 return StmtError();
6646 }
6647
Reid Kleckner87a31802018-03-12 21:43:02 +00006648 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00006649
6650 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6651 AStmt);
6652}
6653
Samuel Antaodf67fc42016-01-19 19:15:56 +00006654StmtResult
6655Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6656 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006657 SourceLocation EndLoc, Stmt *AStmt) {
6658 if (!AStmt)
6659 return StmtError();
6660
6661 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6662 // 1.2.2 OpenMP Language Terminology
6663 // Structured block - An executable statement with a single entry at the
6664 // top and a single exit at the bottom.
6665 // The point of exit cannot be a branch out of the structured block.
6666 // longjmp() and throw() must not violate the entry/exit criteria.
6667 CS->getCapturedDecl()->setNothrow();
6668 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6669 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6670 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6671 // 1.2.2 OpenMP Language Terminology
6672 // Structured block - An executable statement with a single entry at the
6673 // top and a single exit at the bottom.
6674 // The point of exit cannot be a branch out of the structured block.
6675 // longjmp() and throw() must not violate the entry/exit criteria.
6676 CS->getCapturedDecl()->setNothrow();
6677 }
6678
Samuel Antaodf67fc42016-01-19 19:15:56 +00006679 // OpenMP [2.10.2, Restrictions, p. 99]
6680 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006681 if (!hasClauses(Clauses, OMPC_map)) {
6682 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6683 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006684 return StmtError();
6685 }
6686
Alexey Bataev7828b252017-11-21 17:08:48 +00006687 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6688 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006689}
6690
Samuel Antao72590762016-01-19 20:04:50 +00006691StmtResult
6692Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6693 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006694 SourceLocation EndLoc, Stmt *AStmt) {
6695 if (!AStmt)
6696 return StmtError();
6697
6698 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6699 // 1.2.2 OpenMP Language Terminology
6700 // Structured block - An executable statement with a single entry at the
6701 // top and a single exit at the bottom.
6702 // The point of exit cannot be a branch out of the structured block.
6703 // longjmp() and throw() must not violate the entry/exit criteria.
6704 CS->getCapturedDecl()->setNothrow();
6705 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6706 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6707 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6708 // 1.2.2 OpenMP Language Terminology
6709 // Structured block - An executable statement with a single entry at the
6710 // top and a single exit at the bottom.
6711 // The point of exit cannot be a branch out of the structured block.
6712 // longjmp() and throw() must not violate the entry/exit criteria.
6713 CS->getCapturedDecl()->setNothrow();
6714 }
6715
Samuel Antao72590762016-01-19 20:04:50 +00006716 // OpenMP [2.10.3, Restrictions, p. 102]
6717 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006718 if (!hasClauses(Clauses, OMPC_map)) {
6719 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6720 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006721 return StmtError();
6722 }
6723
Alexey Bataev7828b252017-11-21 17:08:48 +00006724 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6725 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006726}
6727
Samuel Antao686c70c2016-05-26 17:30:50 +00006728StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6729 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006730 SourceLocation EndLoc,
6731 Stmt *AStmt) {
6732 if (!AStmt)
6733 return StmtError();
6734
6735 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6736 // 1.2.2 OpenMP Language Terminology
6737 // Structured block - An executable statement with a single entry at the
6738 // top and a single exit at the bottom.
6739 // The point of exit cannot be a branch out of the structured block.
6740 // longjmp() and throw() must not violate the entry/exit criteria.
6741 CS->getCapturedDecl()->setNothrow();
6742 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6743 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6744 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6745 // 1.2.2 OpenMP Language Terminology
6746 // Structured block - An executable statement with a single entry at the
6747 // top and a single exit at the bottom.
6748 // The point of exit cannot be a branch out of the structured block.
6749 // longjmp() and throw() must not violate the entry/exit criteria.
6750 CS->getCapturedDecl()->setNothrow();
6751 }
6752
Alexey Bataev95b64a92017-05-30 16:00:04 +00006753 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006754 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6755 return StmtError();
6756 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006757 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6758 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006759}
6760
Alexey Bataev13314bf2014-10-09 04:18:56 +00006761StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6762 Stmt *AStmt, SourceLocation StartLoc,
6763 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006764 if (!AStmt)
6765 return StmtError();
6766
Alexey Bataev13314bf2014-10-09 04:18:56 +00006767 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6768 // 1.2.2 OpenMP Language Terminology
6769 // Structured block - An executable statement with a single entry at the
6770 // top and a single exit at the bottom.
6771 // The point of exit cannot be a branch out of the structured block.
6772 // longjmp() and throw() must not violate the entry/exit criteria.
6773 CS->getCapturedDecl()->setNothrow();
6774
Reid Kleckner87a31802018-03-12 21:43:02 +00006775 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00006776
Alexey Bataevceabd412017-11-30 18:01:54 +00006777 DSAStack->setParentTeamsRegionLoc(StartLoc);
6778
Alexey Bataev13314bf2014-10-09 04:18:56 +00006779 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6780}
6781
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006782StmtResult
6783Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6784 SourceLocation EndLoc,
6785 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006786 if (DSAStack->isParentNowaitRegion()) {
6787 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6788 return StmtError();
6789 }
6790 if (DSAStack->isParentOrderedRegion()) {
6791 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6792 return StmtError();
6793 }
6794 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6795 CancelRegion);
6796}
6797
Alexey Bataev87933c72015-09-18 08:07:34 +00006798StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6799 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006800 SourceLocation EndLoc,
6801 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006802 if (DSAStack->isParentNowaitRegion()) {
6803 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6804 return StmtError();
6805 }
6806 if (DSAStack->isParentOrderedRegion()) {
6807 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6808 return StmtError();
6809 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006810 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006811 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6812 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006813}
6814
Alexey Bataev382967a2015-12-08 12:06:20 +00006815static bool checkGrainsizeNumTasksClauses(Sema &S,
6816 ArrayRef<OMPClause *> Clauses) {
6817 OMPClause *PrevClause = nullptr;
6818 bool ErrorFound = false;
6819 for (auto *C : Clauses) {
6820 if (C->getClauseKind() == OMPC_grainsize ||
6821 C->getClauseKind() == OMPC_num_tasks) {
6822 if (!PrevClause)
6823 PrevClause = C;
6824 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6825 S.Diag(C->getLocStart(),
6826 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6827 << getOpenMPClauseName(C->getClauseKind())
6828 << getOpenMPClauseName(PrevClause->getClauseKind());
6829 S.Diag(PrevClause->getLocStart(),
6830 diag::note_omp_previous_grainsize_num_tasks)
6831 << getOpenMPClauseName(PrevClause->getClauseKind());
6832 ErrorFound = true;
6833 }
6834 }
6835 }
6836 return ErrorFound;
6837}
6838
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006839static bool checkReductionClauseWithNogroup(Sema &S,
6840 ArrayRef<OMPClause *> Clauses) {
6841 OMPClause *ReductionClause = nullptr;
6842 OMPClause *NogroupClause = nullptr;
6843 for (auto *C : Clauses) {
6844 if (C->getClauseKind() == OMPC_reduction) {
6845 ReductionClause = C;
6846 if (NogroupClause)
6847 break;
6848 continue;
6849 }
6850 if (C->getClauseKind() == OMPC_nogroup) {
6851 NogroupClause = C;
6852 if (ReductionClause)
6853 break;
6854 continue;
6855 }
6856 }
6857 if (ReductionClause && NogroupClause) {
6858 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6859 << SourceRange(NogroupClause->getLocStart(),
6860 NogroupClause->getLocEnd());
6861 return true;
6862 }
6863 return false;
6864}
6865
Alexey Bataev49f6e782015-12-01 04:18:41 +00006866StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6867 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6868 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006869 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006870 if (!AStmt)
6871 return StmtError();
6872
6873 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6874 OMPLoopDirective::HelperExprs B;
6875 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6876 // define the nested loops number.
6877 unsigned NestedLoopCount =
6878 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006879 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006880 VarsWithImplicitDSA, B);
6881 if (NestedLoopCount == 0)
6882 return StmtError();
6883
6884 assert((CurContext->isDependentContext() || B.builtAll()) &&
6885 "omp for loop exprs were not built");
6886
Alexey Bataev382967a2015-12-08 12:06:20 +00006887 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6888 // The grainsize clause and num_tasks clause are mutually exclusive and may
6889 // not appear on the same taskloop directive.
6890 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6891 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006892 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6893 // If a reduction clause is present on the taskloop directive, the nogroup
6894 // clause must not be specified.
6895 if (checkReductionClauseWithNogroup(*this, Clauses))
6896 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006897
Reid Kleckner87a31802018-03-12 21:43:02 +00006898 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00006899 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6900 NestedLoopCount, Clauses, AStmt, B);
6901}
6902
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006903StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6904 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6905 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006906 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006907 if (!AStmt)
6908 return StmtError();
6909
6910 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6911 OMPLoopDirective::HelperExprs B;
6912 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6913 // define the nested loops number.
6914 unsigned NestedLoopCount =
6915 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6916 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6917 VarsWithImplicitDSA, B);
6918 if (NestedLoopCount == 0)
6919 return StmtError();
6920
6921 assert((CurContext->isDependentContext() || B.builtAll()) &&
6922 "omp for loop exprs were not built");
6923
Alexey Bataev5a3af132016-03-29 08:58:54 +00006924 if (!CurContext->isDependentContext()) {
6925 // Finalize the clauses that need pre-built expressions for CodeGen.
6926 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006927 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006928 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006929 B.NumIterations, *this, CurScope,
6930 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006931 return StmtError();
6932 }
6933 }
6934
Alexey Bataev382967a2015-12-08 12:06:20 +00006935 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6936 // The grainsize clause and num_tasks clause are mutually exclusive and may
6937 // not appear on the same taskloop directive.
6938 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6939 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006940 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6941 // If a reduction clause is present on the taskloop directive, the nogroup
6942 // clause must not be specified.
6943 if (checkReductionClauseWithNogroup(*this, Clauses))
6944 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006945 if (checkSimdlenSafelenSpecified(*this, Clauses))
6946 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006947
Reid Kleckner87a31802018-03-12 21:43:02 +00006948 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006949 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6950 NestedLoopCount, Clauses, AStmt, B);
6951}
6952
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006953StmtResult Sema::ActOnOpenMPDistributeDirective(
6954 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6955 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006956 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006957 if (!AStmt)
6958 return StmtError();
6959
6960 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6961 OMPLoopDirective::HelperExprs B;
6962 // In presence of clause 'collapse' with number of loops, it will
6963 // define the nested loops number.
6964 unsigned NestedLoopCount =
6965 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6966 nullptr /*ordered not a clause on distribute*/, AStmt,
6967 *this, *DSAStack, VarsWithImplicitDSA, B);
6968 if (NestedLoopCount == 0)
6969 return StmtError();
6970
6971 assert((CurContext->isDependentContext() || B.builtAll()) &&
6972 "omp for loop exprs were not built");
6973
Reid Kleckner87a31802018-03-12 21:43:02 +00006974 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006975 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6976 NestedLoopCount, Clauses, AStmt, B);
6977}
6978
Carlo Bertolli9925f152016-06-27 14:55:37 +00006979StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6980 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6981 SourceLocation EndLoc,
6982 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6983 if (!AStmt)
6984 return StmtError();
6985
6986 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6987 // 1.2.2 OpenMP Language Terminology
6988 // Structured block - An executable statement with a single entry at the
6989 // top and a single exit at the bottom.
6990 // The point of exit cannot be a branch out of the structured block.
6991 // longjmp() and throw() must not violate the entry/exit criteria.
6992 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006993 for (int ThisCaptureLevel =
6994 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6995 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6996 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6997 // 1.2.2 OpenMP Language Terminology
6998 // Structured block - An executable statement with a single entry at the
6999 // top and a single exit at the bottom.
7000 // The point of exit cannot be a branch out of the structured block.
7001 // longjmp() and throw() must not violate the entry/exit criteria.
7002 CS->getCapturedDecl()->setNothrow();
7003 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007004
7005 OMPLoopDirective::HelperExprs B;
7006 // In presence of clause 'collapse' with number of loops, it will
7007 // define the nested loops number.
7008 unsigned NestedLoopCount = CheckOpenMPLoop(
7009 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007010 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007011 VarsWithImplicitDSA, B);
7012 if (NestedLoopCount == 0)
7013 return StmtError();
7014
7015 assert((CurContext->isDependentContext() || B.builtAll()) &&
7016 "omp for loop exprs were not built");
7017
Reid Kleckner87a31802018-03-12 21:43:02 +00007018 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007019 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007020 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7021 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007022}
7023
Kelvin Li4a39add2016-07-05 05:00:15 +00007024StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7025 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7026 SourceLocation EndLoc,
7027 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7028 if (!AStmt)
7029 return StmtError();
7030
7031 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7032 // 1.2.2 OpenMP Language Terminology
7033 // Structured block - An executable statement with a single entry at the
7034 // top and a single exit at the bottom.
7035 // The point of exit cannot be a branch out of the structured block.
7036 // longjmp() and throw() must not violate the entry/exit criteria.
7037 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007038 for (int ThisCaptureLevel =
7039 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7040 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7041 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7042 // 1.2.2 OpenMP Language Terminology
7043 // Structured block - An executable statement with a single entry at the
7044 // top and a single exit at the bottom.
7045 // The point of exit cannot be a branch out of the structured block.
7046 // longjmp() and throw() must not violate the entry/exit criteria.
7047 CS->getCapturedDecl()->setNothrow();
7048 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007049
7050 OMPLoopDirective::HelperExprs B;
7051 // In presence of clause 'collapse' with number of loops, it will
7052 // define the nested loops number.
7053 unsigned NestedLoopCount = CheckOpenMPLoop(
7054 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007055 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007056 VarsWithImplicitDSA, B);
7057 if (NestedLoopCount == 0)
7058 return StmtError();
7059
7060 assert((CurContext->isDependentContext() || B.builtAll()) &&
7061 "omp for loop exprs were not built");
7062
Alexey Bataev438388c2017-11-22 18:34:02 +00007063 if (!CurContext->isDependentContext()) {
7064 // Finalize the clauses that need pre-built expressions for CodeGen.
7065 for (auto C : Clauses) {
7066 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7067 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7068 B.NumIterations, *this, CurScope,
7069 DSAStack))
7070 return StmtError();
7071 }
7072 }
7073
Kelvin Lic5609492016-07-15 04:39:07 +00007074 if (checkSimdlenSafelenSpecified(*this, Clauses))
7075 return StmtError();
7076
Reid Kleckner87a31802018-03-12 21:43:02 +00007077 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007078 return OMPDistributeParallelForSimdDirective::Create(
7079 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7080}
7081
Kelvin Li787f3fc2016-07-06 04:45:38 +00007082StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7083 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7084 SourceLocation EndLoc,
7085 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7086 if (!AStmt)
7087 return StmtError();
7088
7089 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7090 // 1.2.2 OpenMP Language Terminology
7091 // Structured block - An executable statement with a single entry at the
7092 // top and a single exit at the bottom.
7093 // The point of exit cannot be a branch out of the structured block.
7094 // longjmp() and throw() must not violate the entry/exit criteria.
7095 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007096 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7097 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7098 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7099 // 1.2.2 OpenMP Language Terminology
7100 // Structured block - An executable statement with a single entry at the
7101 // top and a single exit at the bottom.
7102 // The point of exit cannot be a branch out of the structured block.
7103 // longjmp() and throw() must not violate the entry/exit criteria.
7104 CS->getCapturedDecl()->setNothrow();
7105 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007106
7107 OMPLoopDirective::HelperExprs B;
7108 // In presence of clause 'collapse' with number of loops, it will
7109 // define the nested loops number.
7110 unsigned NestedLoopCount =
7111 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007112 nullptr /*ordered not a clause on distribute*/, CS, *this,
7113 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007114 if (NestedLoopCount == 0)
7115 return StmtError();
7116
7117 assert((CurContext->isDependentContext() || B.builtAll()) &&
7118 "omp for loop exprs were not built");
7119
Alexey Bataev438388c2017-11-22 18:34:02 +00007120 if (!CurContext->isDependentContext()) {
7121 // Finalize the clauses that need pre-built expressions for CodeGen.
7122 for (auto C : Clauses) {
7123 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7124 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7125 B.NumIterations, *this, CurScope,
7126 DSAStack))
7127 return StmtError();
7128 }
7129 }
7130
Kelvin Lic5609492016-07-15 04:39:07 +00007131 if (checkSimdlenSafelenSpecified(*this, Clauses))
7132 return StmtError();
7133
Reid Kleckner87a31802018-03-12 21:43:02 +00007134 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007135 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7136 NestedLoopCount, Clauses, AStmt, B);
7137}
7138
Kelvin Lia579b912016-07-14 02:54:56 +00007139StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7140 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7141 SourceLocation EndLoc,
7142 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7143 if (!AStmt)
7144 return StmtError();
7145
7146 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7147 // 1.2.2 OpenMP Language Terminology
7148 // Structured block - An executable statement with a single entry at the
7149 // top and a single exit at the bottom.
7150 // The point of exit cannot be a branch out of the structured block.
7151 // longjmp() and throw() must not violate the entry/exit criteria.
7152 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007153 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7154 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7155 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7156 // 1.2.2 OpenMP Language Terminology
7157 // Structured block - An executable statement with a single entry at the
7158 // top and a single exit at the bottom.
7159 // The point of exit cannot be a branch out of the structured block.
7160 // longjmp() and throw() must not violate the entry/exit criteria.
7161 CS->getCapturedDecl()->setNothrow();
7162 }
Kelvin Lia579b912016-07-14 02:54:56 +00007163
7164 OMPLoopDirective::HelperExprs B;
7165 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7166 // define the nested loops number.
7167 unsigned NestedLoopCount = CheckOpenMPLoop(
7168 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007169 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007170 VarsWithImplicitDSA, B);
7171 if (NestedLoopCount == 0)
7172 return StmtError();
7173
7174 assert((CurContext->isDependentContext() || B.builtAll()) &&
7175 "omp target parallel for simd loop exprs were not built");
7176
7177 if (!CurContext->isDependentContext()) {
7178 // Finalize the clauses that need pre-built expressions for CodeGen.
7179 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007180 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007181 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7182 B.NumIterations, *this, CurScope,
7183 DSAStack))
7184 return StmtError();
7185 }
7186 }
Kelvin Lic5609492016-07-15 04:39:07 +00007187 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007188 return StmtError();
7189
Reid Kleckner87a31802018-03-12 21:43:02 +00007190 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007191 return OMPTargetParallelForSimdDirective::Create(
7192 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7193}
7194
Kelvin Li986330c2016-07-20 22:57:10 +00007195StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7196 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7197 SourceLocation EndLoc,
7198 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7199 if (!AStmt)
7200 return StmtError();
7201
7202 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7203 // 1.2.2 OpenMP Language Terminology
7204 // Structured block - An executable statement with a single entry at the
7205 // top and a single exit at the bottom.
7206 // The point of exit cannot be a branch out of the structured block.
7207 // longjmp() and throw() must not violate the entry/exit criteria.
7208 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007209 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7210 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7211 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7212 // 1.2.2 OpenMP Language Terminology
7213 // Structured block - An executable statement with a single entry at the
7214 // top and a single exit at the bottom.
7215 // The point of exit cannot be a branch out of the structured block.
7216 // longjmp() and throw() must not violate the entry/exit criteria.
7217 CS->getCapturedDecl()->setNothrow();
7218 }
7219
Kelvin Li986330c2016-07-20 22:57:10 +00007220 OMPLoopDirective::HelperExprs B;
7221 // In presence of clause 'collapse' with number of loops, it will define the
7222 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007223 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007224 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007225 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007226 VarsWithImplicitDSA, B);
7227 if (NestedLoopCount == 0)
7228 return StmtError();
7229
7230 assert((CurContext->isDependentContext() || B.builtAll()) &&
7231 "omp target simd loop exprs were not built");
7232
7233 if (!CurContext->isDependentContext()) {
7234 // Finalize the clauses that need pre-built expressions for CodeGen.
7235 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007236 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007237 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7238 B.NumIterations, *this, CurScope,
7239 DSAStack))
7240 return StmtError();
7241 }
7242 }
7243
7244 if (checkSimdlenSafelenSpecified(*this, Clauses))
7245 return StmtError();
7246
Reid Kleckner87a31802018-03-12 21:43:02 +00007247 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007248 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7249 NestedLoopCount, Clauses, AStmt, B);
7250}
7251
Kelvin Li02532872016-08-05 14:37:37 +00007252StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7253 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7254 SourceLocation EndLoc,
7255 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7256 if (!AStmt)
7257 return StmtError();
7258
7259 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7260 // 1.2.2 OpenMP Language Terminology
7261 // Structured block - An executable statement with a single entry at the
7262 // top and a single exit at the bottom.
7263 // The point of exit cannot be a branch out of the structured block.
7264 // longjmp() and throw() must not violate the entry/exit criteria.
7265 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007266 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7267 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7268 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7269 // 1.2.2 OpenMP Language Terminology
7270 // Structured block - An executable statement with a single entry at the
7271 // top and a single exit at the bottom.
7272 // The point of exit cannot be a branch out of the structured block.
7273 // longjmp() and throw() must not violate the entry/exit criteria.
7274 CS->getCapturedDecl()->setNothrow();
7275 }
Kelvin Li02532872016-08-05 14:37:37 +00007276
7277 OMPLoopDirective::HelperExprs B;
7278 // In presence of clause 'collapse' with number of loops, it will
7279 // define the nested loops number.
7280 unsigned NestedLoopCount =
7281 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007282 nullptr /*ordered not a clause on distribute*/, CS, *this,
7283 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007284 if (NestedLoopCount == 0)
7285 return StmtError();
7286
7287 assert((CurContext->isDependentContext() || B.builtAll()) &&
7288 "omp teams distribute loop exprs were not built");
7289
Reid Kleckner87a31802018-03-12 21:43:02 +00007290 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007291
7292 DSAStack->setParentTeamsRegionLoc(StartLoc);
7293
David Majnemer9d168222016-08-05 17:44:54 +00007294 return OMPTeamsDistributeDirective::Create(
7295 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007296}
7297
Kelvin Li4e325f72016-10-25 12:50:55 +00007298StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7300 SourceLocation EndLoc,
7301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7302 if (!AStmt)
7303 return StmtError();
7304
7305 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7306 // 1.2.2 OpenMP Language Terminology
7307 // Structured block - An executable statement with a single entry at the
7308 // top and a single exit at the bottom.
7309 // The point of exit cannot be a branch out of the structured block.
7310 // longjmp() and throw() must not violate the entry/exit criteria.
7311 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007312 for (int ThisCaptureLevel =
7313 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7314 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7315 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7316 // 1.2.2 OpenMP Language Terminology
7317 // Structured block - An executable statement with a single entry at the
7318 // top and a single exit at the bottom.
7319 // The point of exit cannot be a branch out of the structured block.
7320 // longjmp() and throw() must not violate the entry/exit criteria.
7321 CS->getCapturedDecl()->setNothrow();
7322 }
7323
Kelvin Li4e325f72016-10-25 12:50:55 +00007324
7325 OMPLoopDirective::HelperExprs B;
7326 // In presence of clause 'collapse' with number of loops, it will
7327 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007328 unsigned NestedLoopCount = CheckOpenMPLoop(
7329 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007330 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007331 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007332
7333 if (NestedLoopCount == 0)
7334 return StmtError();
7335
7336 assert((CurContext->isDependentContext() || B.builtAll()) &&
7337 "omp teams distribute simd loop exprs were not built");
7338
7339 if (!CurContext->isDependentContext()) {
7340 // Finalize the clauses that need pre-built expressions for CodeGen.
7341 for (auto C : Clauses) {
7342 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7343 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7344 B.NumIterations, *this, CurScope,
7345 DSAStack))
7346 return StmtError();
7347 }
7348 }
7349
7350 if (checkSimdlenSafelenSpecified(*this, Clauses))
7351 return StmtError();
7352
Reid Kleckner87a31802018-03-12 21:43:02 +00007353 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007354
7355 DSAStack->setParentTeamsRegionLoc(StartLoc);
7356
Kelvin Li4e325f72016-10-25 12:50:55 +00007357 return OMPTeamsDistributeSimdDirective::Create(
7358 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7359}
7360
Kelvin Li579e41c2016-11-30 23:51:03 +00007361StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7362 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7363 SourceLocation EndLoc,
7364 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7365 if (!AStmt)
7366 return StmtError();
7367
7368 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7369 // 1.2.2 OpenMP Language Terminology
7370 // Structured block - An executable statement with a single entry at the
7371 // top and a single exit at the bottom.
7372 // The point of exit cannot be a branch out of the structured block.
7373 // longjmp() and throw() must not violate the entry/exit criteria.
7374 CS->getCapturedDecl()->setNothrow();
7375
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007376 for (int ThisCaptureLevel =
7377 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7378 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7379 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7380 // 1.2.2 OpenMP Language Terminology
7381 // Structured block - An executable statement with a single entry at the
7382 // top and a single exit at the bottom.
7383 // The point of exit cannot be a branch out of the structured block.
7384 // longjmp() and throw() must not violate the entry/exit criteria.
7385 CS->getCapturedDecl()->setNothrow();
7386 }
7387
Kelvin Li579e41c2016-11-30 23:51:03 +00007388 OMPLoopDirective::HelperExprs B;
7389 // In presence of clause 'collapse' with number of loops, it will
7390 // define the nested loops number.
7391 auto NestedLoopCount = CheckOpenMPLoop(
7392 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007393 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007394 VarsWithImplicitDSA, B);
7395
7396 if (NestedLoopCount == 0)
7397 return StmtError();
7398
7399 assert((CurContext->isDependentContext() || B.builtAll()) &&
7400 "omp for loop exprs were not built");
7401
7402 if (!CurContext->isDependentContext()) {
7403 // Finalize the clauses that need pre-built expressions for CodeGen.
7404 for (auto C : Clauses) {
7405 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7406 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7407 B.NumIterations, *this, CurScope,
7408 DSAStack))
7409 return StmtError();
7410 }
7411 }
7412
7413 if (checkSimdlenSafelenSpecified(*this, Clauses))
7414 return StmtError();
7415
Reid Kleckner87a31802018-03-12 21:43:02 +00007416 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007417
7418 DSAStack->setParentTeamsRegionLoc(StartLoc);
7419
Kelvin Li579e41c2016-11-30 23:51:03 +00007420 return OMPTeamsDistributeParallelForSimdDirective::Create(
7421 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7422}
7423
Kelvin Li7ade93f2016-12-09 03:24:30 +00007424StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7426 SourceLocation EndLoc,
7427 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7428 if (!AStmt)
7429 return StmtError();
7430
7431 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7432 // 1.2.2 OpenMP Language Terminology
7433 // Structured block - An executable statement with a single entry at the
7434 // top and a single exit at the bottom.
7435 // The point of exit cannot be a branch out of the structured block.
7436 // longjmp() and throw() must not violate the entry/exit criteria.
7437 CS->getCapturedDecl()->setNothrow();
7438
Carlo Bertolli62fae152017-11-20 20:46:39 +00007439 for (int ThisCaptureLevel =
7440 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7441 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7442 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7443 // 1.2.2 OpenMP Language Terminology
7444 // Structured block - An executable statement with a single entry at the
7445 // top and a single exit at the bottom.
7446 // The point of exit cannot be a branch out of the structured block.
7447 // longjmp() and throw() must not violate the entry/exit criteria.
7448 CS->getCapturedDecl()->setNothrow();
7449 }
7450
Kelvin Li7ade93f2016-12-09 03:24:30 +00007451 OMPLoopDirective::HelperExprs B;
7452 // In presence of clause 'collapse' with number of loops, it will
7453 // define the nested loops number.
7454 unsigned NestedLoopCount = CheckOpenMPLoop(
7455 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007456 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007457 VarsWithImplicitDSA, B);
7458
7459 if (NestedLoopCount == 0)
7460 return StmtError();
7461
7462 assert((CurContext->isDependentContext() || B.builtAll()) &&
7463 "omp for loop exprs were not built");
7464
Reid Kleckner87a31802018-03-12 21:43:02 +00007465 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007466
7467 DSAStack->setParentTeamsRegionLoc(StartLoc);
7468
Kelvin Li7ade93f2016-12-09 03:24:30 +00007469 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007470 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7471 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007472}
7473
Kelvin Libf594a52016-12-17 05:48:59 +00007474StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7475 Stmt *AStmt,
7476 SourceLocation StartLoc,
7477 SourceLocation EndLoc) {
7478 if (!AStmt)
7479 return StmtError();
7480
7481 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7482 // 1.2.2 OpenMP Language Terminology
7483 // Structured block - An executable statement with a single entry at the
7484 // top and a single exit at the bottom.
7485 // The point of exit cannot be a branch out of the structured block.
7486 // longjmp() and throw() must not violate the entry/exit criteria.
7487 CS->getCapturedDecl()->setNothrow();
7488
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007489 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7490 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7491 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7492 // 1.2.2 OpenMP Language Terminology
7493 // Structured block - An executable statement with a single entry at the
7494 // top and a single exit at the bottom.
7495 // The point of exit cannot be a branch out of the structured block.
7496 // longjmp() and throw() must not violate the entry/exit criteria.
7497 CS->getCapturedDecl()->setNothrow();
7498 }
Reid Kleckner87a31802018-03-12 21:43:02 +00007499 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00007500
7501 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7502 AStmt);
7503}
7504
Kelvin Li83c451e2016-12-25 04:52:54 +00007505StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7506 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7507 SourceLocation EndLoc,
7508 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7509 if (!AStmt)
7510 return StmtError();
7511
7512 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7513 // 1.2.2 OpenMP Language Terminology
7514 // Structured block - An executable statement with a single entry at the
7515 // top and a single exit at the bottom.
7516 // The point of exit cannot be a branch out of the structured block.
7517 // longjmp() and throw() must not violate the entry/exit criteria.
7518 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007519 for (int ThisCaptureLevel =
7520 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7521 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7522 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7523 // 1.2.2 OpenMP Language Terminology
7524 // Structured block - An executable statement with a single entry at the
7525 // top and a single exit at the bottom.
7526 // The point of exit cannot be a branch out of the structured block.
7527 // longjmp() and throw() must not violate the entry/exit criteria.
7528 CS->getCapturedDecl()->setNothrow();
7529 }
Kelvin Li83c451e2016-12-25 04:52:54 +00007530
7531 OMPLoopDirective::HelperExprs B;
7532 // In presence of clause 'collapse' with number of loops, it will
7533 // define the nested loops number.
7534 auto NestedLoopCount = CheckOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007535 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7536 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00007537 VarsWithImplicitDSA, B);
7538 if (NestedLoopCount == 0)
7539 return StmtError();
7540
7541 assert((CurContext->isDependentContext() || B.builtAll()) &&
7542 "omp target teams distribute loop exprs were not built");
7543
Reid Kleckner87a31802018-03-12 21:43:02 +00007544 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00007545 return OMPTargetTeamsDistributeDirective::Create(
7546 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7547}
7548
Kelvin Li80e8f562016-12-29 22:16:30 +00007549StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7550 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7551 SourceLocation EndLoc,
7552 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7553 if (!AStmt)
7554 return StmtError();
7555
7556 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7557 // 1.2.2 OpenMP Language Terminology
7558 // Structured block - An executable statement with a single entry at the
7559 // top and a single exit at the bottom.
7560 // The point of exit cannot be a branch out of the structured block.
7561 // longjmp() and throw() must not violate the entry/exit criteria.
7562 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00007563 for (int ThisCaptureLevel =
7564 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7565 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7566 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7567 // 1.2.2 OpenMP Language Terminology
7568 // Structured block - An executable statement with a single entry at the
7569 // top and a single exit at the bottom.
7570 // The point of exit cannot be a branch out of the structured block.
7571 // longjmp() and throw() must not violate the entry/exit criteria.
7572 CS->getCapturedDecl()->setNothrow();
7573 }
7574
Kelvin Li80e8f562016-12-29 22:16:30 +00007575 OMPLoopDirective::HelperExprs B;
7576 // In presence of clause 'collapse' with number of loops, it will
7577 // define the nested loops number.
7578 auto NestedLoopCount = CheckOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00007579 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7580 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00007581 VarsWithImplicitDSA, B);
7582 if (NestedLoopCount == 0)
7583 return StmtError();
7584
7585 assert((CurContext->isDependentContext() || B.builtAll()) &&
7586 "omp target teams distribute parallel for loop exprs were not built");
7587
Alexey Bataev647dd842018-01-15 20:59:40 +00007588 if (!CurContext->isDependentContext()) {
7589 // Finalize the clauses that need pre-built expressions for CodeGen.
7590 for (auto C : Clauses) {
7591 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7592 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7593 B.NumIterations, *this, CurScope,
7594 DSAStack))
7595 return StmtError();
7596 }
7597 }
7598
Reid Kleckner87a31802018-03-12 21:43:02 +00007599 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00007600 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007601 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7602 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007603}
7604
Kelvin Li1851df52017-01-03 05:23:48 +00007605StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7606 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7607 SourceLocation EndLoc,
7608 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7609 if (!AStmt)
7610 return StmtError();
7611
7612 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7613 // 1.2.2 OpenMP Language Terminology
7614 // Structured block - An executable statement with a single entry at the
7615 // top and a single exit at the bottom.
7616 // The point of exit cannot be a branch out of the structured block.
7617 // longjmp() and throw() must not violate the entry/exit criteria.
7618 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00007619 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7620 OMPD_target_teams_distribute_parallel_for_simd);
7621 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7622 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7623 // 1.2.2 OpenMP Language Terminology
7624 // Structured block - An executable statement with a single entry at the
7625 // top and a single exit at the bottom.
7626 // The point of exit cannot be a branch out of the structured block.
7627 // longjmp() and throw() must not violate the entry/exit criteria.
7628 CS->getCapturedDecl()->setNothrow();
7629 }
Kelvin Li1851df52017-01-03 05:23:48 +00007630
7631 OMPLoopDirective::HelperExprs B;
7632 // In presence of clause 'collapse' with number of loops, it will
7633 // define the nested loops number.
Alexey Bataev647dd842018-01-15 20:59:40 +00007634 auto NestedLoopCount =
7635 CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7636 getCollapseNumberExpr(Clauses),
7637 nullptr /*ordered not a clause on distribute*/, CS, *this,
7638 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00007639 if (NestedLoopCount == 0)
7640 return StmtError();
7641
7642 assert((CurContext->isDependentContext() || B.builtAll()) &&
7643 "omp target teams distribute parallel for simd loop exprs were not "
7644 "built");
7645
7646 if (!CurContext->isDependentContext()) {
7647 // Finalize the clauses that need pre-built expressions for CodeGen.
7648 for (auto C : Clauses) {
7649 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7650 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7651 B.NumIterations, *this, CurScope,
7652 DSAStack))
7653 return StmtError();
7654 }
7655 }
7656
Alexey Bataev438388c2017-11-22 18:34:02 +00007657 if (checkSimdlenSafelenSpecified(*this, Clauses))
7658 return StmtError();
7659
Reid Kleckner87a31802018-03-12 21:43:02 +00007660 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00007661 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7662 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7663}
7664
Kelvin Lida681182017-01-10 18:08:18 +00007665StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7667 SourceLocation EndLoc,
7668 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7669 if (!AStmt)
7670 return StmtError();
7671
7672 auto *CS = cast<CapturedStmt>(AStmt);
7673 // 1.2.2 OpenMP Language Terminology
7674 // Structured block - An executable statement with a single entry at the
7675 // top and a single exit at the bottom.
7676 // The point of exit cannot be a branch out of the structured block.
7677 // longjmp() and throw() must not violate the entry/exit criteria.
7678 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007679 for (int ThisCaptureLevel =
7680 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7681 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7682 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7683 // 1.2.2 OpenMP Language Terminology
7684 // Structured block - An executable statement with a single entry at the
7685 // top and a single exit at the bottom.
7686 // The point of exit cannot be a branch out of the structured block.
7687 // longjmp() and throw() must not violate the entry/exit criteria.
7688 CS->getCapturedDecl()->setNothrow();
7689 }
Kelvin Lida681182017-01-10 18:08:18 +00007690
7691 OMPLoopDirective::HelperExprs B;
7692 // In presence of clause 'collapse' with number of loops, it will
7693 // define the nested loops number.
7694 auto NestedLoopCount = CheckOpenMPLoop(
7695 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007696 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00007697 VarsWithImplicitDSA, B);
7698 if (NestedLoopCount == 0)
7699 return StmtError();
7700
7701 assert((CurContext->isDependentContext() || B.builtAll()) &&
7702 "omp target teams distribute simd loop exprs were not built");
7703
Alexey Bataev438388c2017-11-22 18:34:02 +00007704 if (!CurContext->isDependentContext()) {
7705 // Finalize the clauses that need pre-built expressions for CodeGen.
7706 for (auto C : Clauses) {
7707 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7708 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7709 B.NumIterations, *this, CurScope,
7710 DSAStack))
7711 return StmtError();
7712 }
7713 }
7714
7715 if (checkSimdlenSafelenSpecified(*this, Clauses))
7716 return StmtError();
7717
Reid Kleckner87a31802018-03-12 21:43:02 +00007718 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00007719 return OMPTargetTeamsDistributeSimdDirective::Create(
7720 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7721}
7722
Alexey Bataeved09d242014-05-28 05:53:51 +00007723OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007724 SourceLocation StartLoc,
7725 SourceLocation LParenLoc,
7726 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007727 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007728 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007729 case OMPC_final:
7730 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7731 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007732 case OMPC_num_threads:
7733 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7734 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007735 case OMPC_safelen:
7736 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7737 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007738 case OMPC_simdlen:
7739 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7740 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007741 case OMPC_collapse:
7742 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7743 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007744 case OMPC_ordered:
7745 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7746 break;
Michael Wonge710d542015-08-07 16:16:36 +00007747 case OMPC_device:
7748 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7749 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007750 case OMPC_num_teams:
7751 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7752 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007753 case OMPC_thread_limit:
7754 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7755 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007756 case OMPC_priority:
7757 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7758 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007759 case OMPC_grainsize:
7760 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7761 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007762 case OMPC_num_tasks:
7763 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7764 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007765 case OMPC_hint:
7766 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7767 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007768 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007769 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007770 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007771 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007772 case OMPC_private:
7773 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007774 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007775 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007776 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007777 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007778 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007779 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007780 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007781 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007782 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007783 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007784 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007785 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007786 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007787 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007788 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007789 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007790 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007791 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007792 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007793 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007794 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007795 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007796 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007797 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007798 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007799 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007800 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007801 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007802 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007803 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007804 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007805 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007806 llvm_unreachable("Clause is not allowed.");
7807 }
7808 return Res;
7809}
7810
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007811// An OpenMP directive such as 'target parallel' has two captured regions:
7812// for the 'target' and 'parallel' respectively. This function returns
7813// the region in which to capture expressions associated with a clause.
7814// A return value of OMPD_unknown signifies that the expression should not
7815// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007816static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7817 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7818 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007819 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007820 switch (CKind) {
7821 case OMPC_if:
7822 switch (DKind) {
7823 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007824 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007825 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007826 // If this clause applies to the nested 'parallel' region, capture within
7827 // the 'target' region, otherwise do not capture.
7828 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7829 CaptureRegion = OMPD_target;
7830 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007831 case OMPD_target_teams_distribute_parallel_for:
7832 case OMPD_target_teams_distribute_parallel_for_simd:
7833 // If this clause applies to the nested 'parallel' region, capture within
7834 // the 'teams' region, otherwise do not capture.
7835 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7836 CaptureRegion = OMPD_teams;
7837 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007838 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007839 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007840 CaptureRegion = OMPD_teams;
7841 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007842 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00007843 case OMPD_target_enter_data:
7844 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007845 CaptureRegion = OMPD_task;
7846 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007847 case OMPD_cancel:
7848 case OMPD_parallel:
7849 case OMPD_parallel_sections:
7850 case OMPD_parallel_for:
7851 case OMPD_parallel_for_simd:
7852 case OMPD_target:
7853 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007854 case OMPD_target_teams:
7855 case OMPD_target_teams_distribute:
7856 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007857 case OMPD_distribute_parallel_for:
7858 case OMPD_distribute_parallel_for_simd:
7859 case OMPD_task:
7860 case OMPD_taskloop:
7861 case OMPD_taskloop_simd:
7862 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007863 // Do not capture if-clause expressions.
7864 break;
7865 case OMPD_threadprivate:
7866 case OMPD_taskyield:
7867 case OMPD_barrier:
7868 case OMPD_taskwait:
7869 case OMPD_cancellation_point:
7870 case OMPD_flush:
7871 case OMPD_declare_reduction:
7872 case OMPD_declare_simd:
7873 case OMPD_declare_target:
7874 case OMPD_end_declare_target:
7875 case OMPD_teams:
7876 case OMPD_simd:
7877 case OMPD_for:
7878 case OMPD_for_simd:
7879 case OMPD_sections:
7880 case OMPD_section:
7881 case OMPD_single:
7882 case OMPD_master:
7883 case OMPD_critical:
7884 case OMPD_taskgroup:
7885 case OMPD_distribute:
7886 case OMPD_ordered:
7887 case OMPD_atomic:
7888 case OMPD_distribute_simd:
7889 case OMPD_teams_distribute:
7890 case OMPD_teams_distribute_simd:
7891 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7892 case OMPD_unknown:
7893 llvm_unreachable("Unknown OpenMP directive");
7894 }
7895 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007896 case OMPC_num_threads:
7897 switch (DKind) {
7898 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007899 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007900 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007901 CaptureRegion = OMPD_target;
7902 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007903 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007904 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00007905 case OMPD_target_teams_distribute_parallel_for:
7906 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007907 CaptureRegion = OMPD_teams;
7908 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007909 case OMPD_parallel:
7910 case OMPD_parallel_sections:
7911 case OMPD_parallel_for:
7912 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007913 case OMPD_distribute_parallel_for:
7914 case OMPD_distribute_parallel_for_simd:
7915 // Do not capture num_threads-clause expressions.
7916 break;
7917 case OMPD_target_data:
7918 case OMPD_target_enter_data:
7919 case OMPD_target_exit_data:
7920 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007921 case OMPD_target:
7922 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007923 case OMPD_target_teams:
7924 case OMPD_target_teams_distribute:
7925 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007926 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007927 case OMPD_task:
7928 case OMPD_taskloop:
7929 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007930 case OMPD_threadprivate:
7931 case OMPD_taskyield:
7932 case OMPD_barrier:
7933 case OMPD_taskwait:
7934 case OMPD_cancellation_point:
7935 case OMPD_flush:
7936 case OMPD_declare_reduction:
7937 case OMPD_declare_simd:
7938 case OMPD_declare_target:
7939 case OMPD_end_declare_target:
7940 case OMPD_teams:
7941 case OMPD_simd:
7942 case OMPD_for:
7943 case OMPD_for_simd:
7944 case OMPD_sections:
7945 case OMPD_section:
7946 case OMPD_single:
7947 case OMPD_master:
7948 case OMPD_critical:
7949 case OMPD_taskgroup:
7950 case OMPD_distribute:
7951 case OMPD_ordered:
7952 case OMPD_atomic:
7953 case OMPD_distribute_simd:
7954 case OMPD_teams_distribute:
7955 case OMPD_teams_distribute_simd:
7956 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7957 case OMPD_unknown:
7958 llvm_unreachable("Unknown OpenMP directive");
7959 }
7960 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007961 case OMPC_num_teams:
7962 switch (DKind) {
7963 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007964 case OMPD_target_teams_distribute:
7965 case OMPD_target_teams_distribute_simd:
7966 case OMPD_target_teams_distribute_parallel_for:
7967 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007968 CaptureRegion = OMPD_target;
7969 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007970 case OMPD_teams_distribute_parallel_for:
7971 case OMPD_teams_distribute_parallel_for_simd:
7972 case OMPD_teams:
7973 case OMPD_teams_distribute:
7974 case OMPD_teams_distribute_simd:
7975 // Do not capture num_teams-clause expressions.
7976 break;
7977 case OMPD_distribute_parallel_for:
7978 case OMPD_distribute_parallel_for_simd:
7979 case OMPD_task:
7980 case OMPD_taskloop:
7981 case OMPD_taskloop_simd:
7982 case OMPD_target_data:
7983 case OMPD_target_enter_data:
7984 case OMPD_target_exit_data:
7985 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007986 case OMPD_cancel:
7987 case OMPD_parallel:
7988 case OMPD_parallel_sections:
7989 case OMPD_parallel_for:
7990 case OMPD_parallel_for_simd:
7991 case OMPD_target:
7992 case OMPD_target_simd:
7993 case OMPD_target_parallel:
7994 case OMPD_target_parallel_for:
7995 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007996 case OMPD_threadprivate:
7997 case OMPD_taskyield:
7998 case OMPD_barrier:
7999 case OMPD_taskwait:
8000 case OMPD_cancellation_point:
8001 case OMPD_flush:
8002 case OMPD_declare_reduction:
8003 case OMPD_declare_simd:
8004 case OMPD_declare_target:
8005 case OMPD_end_declare_target:
8006 case OMPD_simd:
8007 case OMPD_for:
8008 case OMPD_for_simd:
8009 case OMPD_sections:
8010 case OMPD_section:
8011 case OMPD_single:
8012 case OMPD_master:
8013 case OMPD_critical:
8014 case OMPD_taskgroup:
8015 case OMPD_distribute:
8016 case OMPD_ordered:
8017 case OMPD_atomic:
8018 case OMPD_distribute_simd:
8019 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8020 case OMPD_unknown:
8021 llvm_unreachable("Unknown OpenMP directive");
8022 }
8023 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008024 case OMPC_thread_limit:
8025 switch (DKind) {
8026 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008027 case OMPD_target_teams_distribute:
8028 case OMPD_target_teams_distribute_simd:
8029 case OMPD_target_teams_distribute_parallel_for:
8030 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008031 CaptureRegion = OMPD_target;
8032 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008033 case OMPD_teams_distribute_parallel_for:
8034 case OMPD_teams_distribute_parallel_for_simd:
8035 case OMPD_teams:
8036 case OMPD_teams_distribute:
8037 case OMPD_teams_distribute_simd:
8038 // Do not capture thread_limit-clause expressions.
8039 break;
8040 case OMPD_distribute_parallel_for:
8041 case OMPD_distribute_parallel_for_simd:
8042 case OMPD_task:
8043 case OMPD_taskloop:
8044 case OMPD_taskloop_simd:
8045 case OMPD_target_data:
8046 case OMPD_target_enter_data:
8047 case OMPD_target_exit_data:
8048 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008049 case OMPD_cancel:
8050 case OMPD_parallel:
8051 case OMPD_parallel_sections:
8052 case OMPD_parallel_for:
8053 case OMPD_parallel_for_simd:
8054 case OMPD_target:
8055 case OMPD_target_simd:
8056 case OMPD_target_parallel:
8057 case OMPD_target_parallel_for:
8058 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008059 case OMPD_threadprivate:
8060 case OMPD_taskyield:
8061 case OMPD_barrier:
8062 case OMPD_taskwait:
8063 case OMPD_cancellation_point:
8064 case OMPD_flush:
8065 case OMPD_declare_reduction:
8066 case OMPD_declare_simd:
8067 case OMPD_declare_target:
8068 case OMPD_end_declare_target:
8069 case OMPD_simd:
8070 case OMPD_for:
8071 case OMPD_for_simd:
8072 case OMPD_sections:
8073 case OMPD_section:
8074 case OMPD_single:
8075 case OMPD_master:
8076 case OMPD_critical:
8077 case OMPD_taskgroup:
8078 case OMPD_distribute:
8079 case OMPD_ordered:
8080 case OMPD_atomic:
8081 case OMPD_distribute_simd:
8082 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8083 case OMPD_unknown:
8084 llvm_unreachable("Unknown OpenMP directive");
8085 }
8086 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008087 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008088 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008089 case OMPD_parallel_for:
8090 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008091 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008092 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008093 case OMPD_teams_distribute_parallel_for:
8094 case OMPD_teams_distribute_parallel_for_simd:
8095 case OMPD_target_parallel_for:
8096 case OMPD_target_parallel_for_simd:
8097 case OMPD_target_teams_distribute_parallel_for:
8098 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008099 CaptureRegion = OMPD_parallel;
8100 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008101 case OMPD_for:
8102 case OMPD_for_simd:
8103 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008104 break;
8105 case OMPD_task:
8106 case OMPD_taskloop:
8107 case OMPD_taskloop_simd:
8108 case OMPD_target_data:
8109 case OMPD_target_enter_data:
8110 case OMPD_target_exit_data:
8111 case OMPD_target_update:
8112 case OMPD_teams:
8113 case OMPD_teams_distribute:
8114 case OMPD_teams_distribute_simd:
8115 case OMPD_target_teams_distribute:
8116 case OMPD_target_teams_distribute_simd:
8117 case OMPD_target:
8118 case OMPD_target_simd:
8119 case OMPD_target_parallel:
8120 case OMPD_cancel:
8121 case OMPD_parallel:
8122 case OMPD_parallel_sections:
8123 case OMPD_threadprivate:
8124 case OMPD_taskyield:
8125 case OMPD_barrier:
8126 case OMPD_taskwait:
8127 case OMPD_cancellation_point:
8128 case OMPD_flush:
8129 case OMPD_declare_reduction:
8130 case OMPD_declare_simd:
8131 case OMPD_declare_target:
8132 case OMPD_end_declare_target:
8133 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008134 case OMPD_sections:
8135 case OMPD_section:
8136 case OMPD_single:
8137 case OMPD_master:
8138 case OMPD_critical:
8139 case OMPD_taskgroup:
8140 case OMPD_distribute:
8141 case OMPD_ordered:
8142 case OMPD_atomic:
8143 case OMPD_distribute_simd:
8144 case OMPD_target_teams:
8145 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8146 case OMPD_unknown:
8147 llvm_unreachable("Unknown OpenMP directive");
8148 }
8149 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008150 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008151 switch (DKind) {
8152 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008153 case OMPD_teams_distribute_parallel_for_simd:
8154 case OMPD_teams_distribute:
8155 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008156 case OMPD_target_teams_distribute_parallel_for:
8157 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008158 case OMPD_target_teams_distribute:
8159 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008160 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008161 break;
8162 case OMPD_distribute_parallel_for:
8163 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008164 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008165 case OMPD_distribute_simd:
8166 // Do not capture thread_limit-clause expressions.
8167 break;
8168 case OMPD_parallel_for:
8169 case OMPD_parallel_for_simd:
8170 case OMPD_target_parallel_for_simd:
8171 case OMPD_target_parallel_for:
8172 case OMPD_task:
8173 case OMPD_taskloop:
8174 case OMPD_taskloop_simd:
8175 case OMPD_target_data:
8176 case OMPD_target_enter_data:
8177 case OMPD_target_exit_data:
8178 case OMPD_target_update:
8179 case OMPD_teams:
8180 case OMPD_target:
8181 case OMPD_target_simd:
8182 case OMPD_target_parallel:
8183 case OMPD_cancel:
8184 case OMPD_parallel:
8185 case OMPD_parallel_sections:
8186 case OMPD_threadprivate:
8187 case OMPD_taskyield:
8188 case OMPD_barrier:
8189 case OMPD_taskwait:
8190 case OMPD_cancellation_point:
8191 case OMPD_flush:
8192 case OMPD_declare_reduction:
8193 case OMPD_declare_simd:
8194 case OMPD_declare_target:
8195 case OMPD_end_declare_target:
8196 case OMPD_simd:
8197 case OMPD_for:
8198 case OMPD_for_simd:
8199 case OMPD_sections:
8200 case OMPD_section:
8201 case OMPD_single:
8202 case OMPD_master:
8203 case OMPD_critical:
8204 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008205 case OMPD_ordered:
8206 case OMPD_atomic:
8207 case OMPD_target_teams:
8208 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8209 case OMPD_unknown:
8210 llvm_unreachable("Unknown OpenMP directive");
8211 }
8212 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008213 case OMPC_device:
8214 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008215 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008216 case OMPD_target_enter_data:
8217 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008218 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008219 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008220 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008221 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008222 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008223 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008224 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008225 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008226 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008227 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008228 CaptureRegion = OMPD_task;
8229 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008230 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008231 // Do not capture device-clause expressions.
8232 break;
8233 case OMPD_teams_distribute_parallel_for:
8234 case OMPD_teams_distribute_parallel_for_simd:
8235 case OMPD_teams:
8236 case OMPD_teams_distribute:
8237 case OMPD_teams_distribute_simd:
8238 case OMPD_distribute_parallel_for:
8239 case OMPD_distribute_parallel_for_simd:
8240 case OMPD_task:
8241 case OMPD_taskloop:
8242 case OMPD_taskloop_simd:
8243 case OMPD_cancel:
8244 case OMPD_parallel:
8245 case OMPD_parallel_sections:
8246 case OMPD_parallel_for:
8247 case OMPD_parallel_for_simd:
8248 case OMPD_threadprivate:
8249 case OMPD_taskyield:
8250 case OMPD_barrier:
8251 case OMPD_taskwait:
8252 case OMPD_cancellation_point:
8253 case OMPD_flush:
8254 case OMPD_declare_reduction:
8255 case OMPD_declare_simd:
8256 case OMPD_declare_target:
8257 case OMPD_end_declare_target:
8258 case OMPD_simd:
8259 case OMPD_for:
8260 case OMPD_for_simd:
8261 case OMPD_sections:
8262 case OMPD_section:
8263 case OMPD_single:
8264 case OMPD_master:
8265 case OMPD_critical:
8266 case OMPD_taskgroup:
8267 case OMPD_distribute:
8268 case OMPD_ordered:
8269 case OMPD_atomic:
8270 case OMPD_distribute_simd:
8271 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8272 case OMPD_unknown:
8273 llvm_unreachable("Unknown OpenMP directive");
8274 }
8275 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008276 case OMPC_firstprivate:
8277 case OMPC_lastprivate:
8278 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008279 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008280 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008281 case OMPC_linear:
8282 case OMPC_default:
8283 case OMPC_proc_bind:
8284 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008285 case OMPC_safelen:
8286 case OMPC_simdlen:
8287 case OMPC_collapse:
8288 case OMPC_private:
8289 case OMPC_shared:
8290 case OMPC_aligned:
8291 case OMPC_copyin:
8292 case OMPC_copyprivate:
8293 case OMPC_ordered:
8294 case OMPC_nowait:
8295 case OMPC_untied:
8296 case OMPC_mergeable:
8297 case OMPC_threadprivate:
8298 case OMPC_flush:
8299 case OMPC_read:
8300 case OMPC_write:
8301 case OMPC_update:
8302 case OMPC_capture:
8303 case OMPC_seq_cst:
8304 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008305 case OMPC_threads:
8306 case OMPC_simd:
8307 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008308 case OMPC_priority:
8309 case OMPC_grainsize:
8310 case OMPC_nogroup:
8311 case OMPC_num_tasks:
8312 case OMPC_hint:
8313 case OMPC_defaultmap:
8314 case OMPC_unknown:
8315 case OMPC_uniform:
8316 case OMPC_to:
8317 case OMPC_from:
8318 case OMPC_use_device_ptr:
8319 case OMPC_is_device_ptr:
8320 llvm_unreachable("Unexpected OpenMP clause.");
8321 }
8322 return CaptureRegion;
8323}
8324
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008325OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8326 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008327 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008328 SourceLocation NameModifierLoc,
8329 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008330 SourceLocation EndLoc) {
8331 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008332 Stmt *HelperValStmt = nullptr;
8333 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008334 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8335 !Condition->isInstantiationDependent() &&
8336 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008337 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008338 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008339 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008340
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008341 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008342
8343 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8344 CaptureRegion =
8345 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008346 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008347 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008348 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8349 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8350 HelperValStmt = buildPreInits(Context, Captures);
8351 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008352 }
8353
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008354 return new (Context)
8355 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8356 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008357}
8358
Alexey Bataev3778b602014-07-17 07:32:53 +00008359OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8360 SourceLocation StartLoc,
8361 SourceLocation LParenLoc,
8362 SourceLocation EndLoc) {
8363 Expr *ValExpr = Condition;
8364 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8365 !Condition->isInstantiationDependent() &&
8366 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008367 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008368 if (Val.isInvalid())
8369 return nullptr;
8370
Richard Smith03a4aa32016-06-23 19:02:52 +00008371 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008372 }
8373
8374 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8375}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008376ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8377 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008378 if (!Op)
8379 return ExprError();
8380
8381 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8382 public:
8383 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008384 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008385 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8386 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008387 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8388 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008389 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8390 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008391 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8392 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008393 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8394 QualType T,
8395 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008396 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8397 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008398 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8399 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008400 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008401 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008402 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008403 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8404 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008405 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8406 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008407 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8408 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008409 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008410 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008411 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008412 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8413 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008414 llvm_unreachable("conversion functions are permitted");
8415 }
8416 } ConvertDiagnoser;
8417 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8418}
8419
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008420static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008421 OpenMPClauseKind CKind,
8422 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008423 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8424 !ValExpr->isInstantiationDependent()) {
8425 SourceLocation Loc = ValExpr->getExprLoc();
8426 ExprResult Value =
8427 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8428 if (Value.isInvalid())
8429 return false;
8430
8431 ValExpr = Value.get();
8432 // The expression must evaluate to a non-negative integer value.
8433 llvm::APSInt Result;
8434 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008435 Result.isSigned() &&
8436 !((!StrictlyPositive && Result.isNonNegative()) ||
8437 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008438 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008439 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8440 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008441 return false;
8442 }
8443 }
8444 return true;
8445}
8446
Alexey Bataev568a8332014-03-06 06:15:19 +00008447OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8448 SourceLocation StartLoc,
8449 SourceLocation LParenLoc,
8450 SourceLocation EndLoc) {
8451 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008452 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008453
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008454 // OpenMP [2.5, Restrictions]
8455 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008456 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8457 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008458 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008459
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008460 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008461 OpenMPDirectiveKind CaptureRegion =
8462 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8463 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008464 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008465 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8466 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8467 HelperValStmt = buildPreInits(Context, Captures);
8468 }
8469
8470 return new (Context) OMPNumThreadsClause(
8471 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008472}
8473
Alexey Bataev62c87d22014-03-21 04:51:18 +00008474ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008475 OpenMPClauseKind CKind,
8476 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008477 if (!E)
8478 return ExprError();
8479 if (E->isValueDependent() || E->isTypeDependent() ||
8480 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008481 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008482 llvm::APSInt Result;
8483 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8484 if (ICE.isInvalid())
8485 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008486 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8487 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008488 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008489 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8490 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008491 return ExprError();
8492 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008493 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8494 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8495 << E->getSourceRange();
8496 return ExprError();
8497 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008498 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8499 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008500 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008501 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008502 return ICE;
8503}
8504
8505OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8506 SourceLocation LParenLoc,
8507 SourceLocation EndLoc) {
8508 // OpenMP [2.8.1, simd construct, Description]
8509 // The parameter of the safelen clause must be a constant
8510 // positive integer expression.
8511 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8512 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008513 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008514 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008515 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008516}
8517
Alexey Bataev66b15b52015-08-21 11:14:16 +00008518OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8519 SourceLocation LParenLoc,
8520 SourceLocation EndLoc) {
8521 // OpenMP [2.8.1, simd construct, Description]
8522 // The parameter of the simdlen clause must be a constant
8523 // positive integer expression.
8524 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8525 if (Simdlen.isInvalid())
8526 return nullptr;
8527 return new (Context)
8528 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8529}
8530
Alexander Musman64d33f12014-06-04 07:53:32 +00008531OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8532 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008533 SourceLocation LParenLoc,
8534 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008535 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008536 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008537 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008538 // The parameter of the collapse clause must be a constant
8539 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008540 ExprResult NumForLoopsResult =
8541 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8542 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008543 return nullptr;
8544 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008545 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008546}
8547
Alexey Bataev10e775f2015-07-30 11:36:16 +00008548OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8549 SourceLocation EndLoc,
8550 SourceLocation LParenLoc,
8551 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008552 // OpenMP [2.7.1, loop construct, Description]
8553 // OpenMP [2.8.1, simd construct, Description]
8554 // OpenMP [2.9.6, distribute construct, Description]
8555 // The parameter of the ordered clause must be a constant
8556 // positive integer expression if any.
8557 if (NumForLoops && LParenLoc.isValid()) {
8558 ExprResult NumForLoopsResult =
8559 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8560 if (NumForLoopsResult.isInvalid())
8561 return nullptr;
8562 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008563 } else
8564 NumForLoops = nullptr;
8565 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008566 return new (Context)
8567 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8568}
8569
Alexey Bataeved09d242014-05-28 05:53:51 +00008570OMPClause *Sema::ActOnOpenMPSimpleClause(
8571 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8572 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008573 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008574 switch (Kind) {
8575 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008576 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008577 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8578 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008579 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008580 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008581 Res = ActOnOpenMPProcBindClause(
8582 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8583 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008584 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008585 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008586 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008587 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008588 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008589 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008590 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008591 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008592 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008593 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008594 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008595 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008596 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008597 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008598 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008599 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008600 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008601 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008602 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008603 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008604 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008605 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008606 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008607 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008608 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008609 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008610 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008611 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008612 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008613 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008614 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008615 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008616 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008617 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008618 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008619 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008620 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008621 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008622 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008623 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008624 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008625 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008626 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008627 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008628 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008629 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008630 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008631 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008632 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008633 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008634 llvm_unreachable("Clause is not allowed.");
8635 }
8636 return Res;
8637}
8638
Alexey Bataev6402bca2015-12-28 07:25:51 +00008639static std::string
8640getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8641 ArrayRef<unsigned> Exclude = llvm::None) {
8642 std::string Values;
8643 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8644 unsigned Skipped = Exclude.size();
8645 auto S = Exclude.begin(), E = Exclude.end();
8646 for (unsigned i = First; i < Last; ++i) {
8647 if (std::find(S, E, i) != E) {
8648 --Skipped;
8649 continue;
8650 }
8651 Values += "'";
8652 Values += getOpenMPSimpleClauseTypeName(K, i);
8653 Values += "'";
8654 if (i == Bound - Skipped)
8655 Values += " or ";
8656 else if (i != Bound + 1 - Skipped)
8657 Values += ", ";
8658 }
8659 return Values;
8660}
8661
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008662OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8663 SourceLocation KindKwLoc,
8664 SourceLocation StartLoc,
8665 SourceLocation LParenLoc,
8666 SourceLocation EndLoc) {
8667 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008668 static_assert(OMPC_DEFAULT_unknown > 0,
8669 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008670 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008671 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8672 /*Last=*/OMPC_DEFAULT_unknown)
8673 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008674 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008675 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008676 switch (Kind) {
8677 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008678 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008679 break;
8680 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008681 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008682 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008683 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008684 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008685 break;
8686 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008687 return new (Context)
8688 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008689}
8690
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008691OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8692 SourceLocation KindKwLoc,
8693 SourceLocation StartLoc,
8694 SourceLocation LParenLoc,
8695 SourceLocation EndLoc) {
8696 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008697 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008698 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8699 /*Last=*/OMPC_PROC_BIND_unknown)
8700 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008701 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008702 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008703 return new (Context)
8704 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008705}
8706
Alexey Bataev56dafe82014-06-20 07:16:17 +00008707OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008708 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008709 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008710 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008711 SourceLocation EndLoc) {
8712 OMPClause *Res = nullptr;
8713 switch (Kind) {
8714 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008715 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8716 assert(Argument.size() == NumberOfElements &&
8717 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008718 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008719 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8720 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8721 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8722 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8723 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008724 break;
8725 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008726 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8727 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8728 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8729 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008730 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008731 case OMPC_dist_schedule:
8732 Res = ActOnOpenMPDistScheduleClause(
8733 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8734 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8735 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008736 case OMPC_defaultmap:
8737 enum { Modifier, DefaultmapKind };
8738 Res = ActOnOpenMPDefaultmapClause(
8739 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8740 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008741 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8742 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008743 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008744 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008745 case OMPC_num_threads:
8746 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008747 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008748 case OMPC_collapse:
8749 case OMPC_default:
8750 case OMPC_proc_bind:
8751 case OMPC_private:
8752 case OMPC_firstprivate:
8753 case OMPC_lastprivate:
8754 case OMPC_shared:
8755 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008756 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008757 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008758 case OMPC_linear:
8759 case OMPC_aligned:
8760 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008761 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008762 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008763 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008764 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008765 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008766 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008767 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008768 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008769 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008770 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008771 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008772 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008773 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008774 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008775 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008776 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008777 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008778 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008779 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008780 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008781 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008782 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008783 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008784 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008785 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008786 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008787 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008788 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008789 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008790 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008791 llvm_unreachable("Clause is not allowed.");
8792 }
8793 return Res;
8794}
8795
Alexey Bataev6402bca2015-12-28 07:25:51 +00008796static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8797 OpenMPScheduleClauseModifier M2,
8798 SourceLocation M1Loc, SourceLocation M2Loc) {
8799 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8800 SmallVector<unsigned, 2> Excluded;
8801 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8802 Excluded.push_back(M2);
8803 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8804 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8805 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8806 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8807 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8808 << getListOfPossibleValues(OMPC_schedule,
8809 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8810 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8811 Excluded)
8812 << getOpenMPClauseName(OMPC_schedule);
8813 return true;
8814 }
8815 return false;
8816}
8817
Alexey Bataev56dafe82014-06-20 07:16:17 +00008818OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008819 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008820 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008821 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8822 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8823 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8824 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8825 return nullptr;
8826 // OpenMP, 2.7.1, Loop Construct, Restrictions
8827 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8828 // but not both.
8829 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8830 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8831 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8832 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8833 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8834 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8835 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8836 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8837 return nullptr;
8838 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008839 if (Kind == OMPC_SCHEDULE_unknown) {
8840 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008841 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8842 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8843 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8844 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8845 Exclude);
8846 } else {
8847 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8848 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008849 }
8850 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8851 << Values << getOpenMPClauseName(OMPC_schedule);
8852 return nullptr;
8853 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008854 // OpenMP, 2.7.1, Loop Construct, Restrictions
8855 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8856 // schedule(guided).
8857 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8858 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8859 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8860 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8861 diag::err_omp_schedule_nonmonotonic_static);
8862 return nullptr;
8863 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008864 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008865 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008866 if (ChunkSize) {
8867 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8868 !ChunkSize->isInstantiationDependent() &&
8869 !ChunkSize->containsUnexpandedParameterPack()) {
8870 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8871 ExprResult Val =
8872 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8873 if (Val.isInvalid())
8874 return nullptr;
8875
8876 ValExpr = Val.get();
8877
8878 // OpenMP [2.7.1, Restrictions]
8879 // chunk_size must be a loop invariant integer expression with a positive
8880 // value.
8881 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008882 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8883 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8884 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008885 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008886 return nullptr;
8887 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008888 } else if (getOpenMPCaptureRegionForClause(
8889 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8890 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008891 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008892 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008893 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8894 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8895 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008896 }
8897 }
8898 }
8899
Alexey Bataev6402bca2015-12-28 07:25:51 +00008900 return new (Context)
8901 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008902 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008903}
8904
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008905OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8906 SourceLocation StartLoc,
8907 SourceLocation EndLoc) {
8908 OMPClause *Res = nullptr;
8909 switch (Kind) {
8910 case OMPC_ordered:
8911 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8912 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008913 case OMPC_nowait:
8914 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8915 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008916 case OMPC_untied:
8917 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8918 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008919 case OMPC_mergeable:
8920 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8921 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008922 case OMPC_read:
8923 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8924 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008925 case OMPC_write:
8926 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8927 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008928 case OMPC_update:
8929 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8930 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008931 case OMPC_capture:
8932 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8933 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008934 case OMPC_seq_cst:
8935 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8936 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008937 case OMPC_threads:
8938 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8939 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008940 case OMPC_simd:
8941 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8942 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008943 case OMPC_nogroup:
8944 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8945 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008946 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008947 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008948 case OMPC_num_threads:
8949 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008950 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008951 case OMPC_collapse:
8952 case OMPC_schedule:
8953 case OMPC_private:
8954 case OMPC_firstprivate:
8955 case OMPC_lastprivate:
8956 case OMPC_shared:
8957 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008958 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008959 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008960 case OMPC_linear:
8961 case OMPC_aligned:
8962 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008963 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008964 case OMPC_default:
8965 case OMPC_proc_bind:
8966 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008967 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008968 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008969 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008970 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008971 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008972 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008973 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008974 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008975 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008976 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008977 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008978 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008979 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008980 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008981 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008982 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008983 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008984 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008985 llvm_unreachable("Clause is not allowed.");
8986 }
8987 return Res;
8988}
8989
Alexey Bataev236070f2014-06-20 11:19:47 +00008990OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8991 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008992 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008993 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8994}
8995
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008996OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8997 SourceLocation EndLoc) {
8998 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8999}
9000
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009001OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9002 SourceLocation EndLoc) {
9003 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9004}
9005
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009006OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9007 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009008 return new (Context) OMPReadClause(StartLoc, EndLoc);
9009}
9010
Alexey Bataevdea47612014-07-23 07:46:59 +00009011OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9012 SourceLocation EndLoc) {
9013 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9014}
9015
Alexey Bataev67a4f222014-07-23 10:25:33 +00009016OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9017 SourceLocation EndLoc) {
9018 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9019}
9020
Alexey Bataev459dec02014-07-24 06:46:57 +00009021OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9022 SourceLocation EndLoc) {
9023 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9024}
9025
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009026OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9027 SourceLocation EndLoc) {
9028 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9029}
9030
Alexey Bataev346265e2015-09-25 10:37:12 +00009031OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9032 SourceLocation EndLoc) {
9033 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9034}
9035
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009036OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9037 SourceLocation EndLoc) {
9038 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9039}
9040
Alexey Bataevb825de12015-12-07 10:51:44 +00009041OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9042 SourceLocation EndLoc) {
9043 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9044}
9045
Alexey Bataevc5e02582014-06-16 07:08:35 +00009046OMPClause *Sema::ActOnOpenMPVarListClause(
9047 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9048 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9049 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009050 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00009051 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9052 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9053 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009054 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009055 switch (Kind) {
9056 case OMPC_private:
9057 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9058 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009059 case OMPC_firstprivate:
9060 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9061 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009062 case OMPC_lastprivate:
9063 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9064 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009065 case OMPC_shared:
9066 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9067 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009068 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009069 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9070 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009071 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009072 case OMPC_task_reduction:
9073 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9074 EndLoc, ReductionIdScopeSpec,
9075 ReductionId);
9076 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009077 case OMPC_in_reduction:
9078 Res =
9079 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9080 EndLoc, ReductionIdScopeSpec, ReductionId);
9081 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009082 case OMPC_linear:
9083 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009084 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009085 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009086 case OMPC_aligned:
9087 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9088 ColonLoc, EndLoc);
9089 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009090 case OMPC_copyin:
9091 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9092 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009093 case OMPC_copyprivate:
9094 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9095 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009096 case OMPC_flush:
9097 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9098 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009099 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009100 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009101 StartLoc, LParenLoc, EndLoc);
9102 break;
9103 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00009104 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9105 DepLinMapLoc, ColonLoc, VarList, StartLoc,
9106 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009107 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009108 case OMPC_to:
9109 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9110 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009111 case OMPC_from:
9112 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9113 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009114 case OMPC_use_device_ptr:
9115 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9116 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009117 case OMPC_is_device_ptr:
9118 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9119 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009120 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009121 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009122 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009123 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009124 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009125 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009126 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009127 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009128 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009129 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009130 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009131 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009132 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009133 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009134 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009135 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009136 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009137 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009138 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009139 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009140 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009141 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009142 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009143 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009144 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009145 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009146 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009147 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009148 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009149 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009150 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009151 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009152 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009153 llvm_unreachable("Clause is not allowed.");
9154 }
9155 return Res;
9156}
9157
Alexey Bataev90c228f2016-02-08 09:29:13 +00009158ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009159 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009160 ExprResult Res = BuildDeclRefExpr(
9161 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9162 if (!Res.isUsable())
9163 return ExprError();
9164 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9165 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9166 if (!Res.isUsable())
9167 return ExprError();
9168 }
9169 if (VK != VK_LValue && Res.get()->isGLValue()) {
9170 Res = DefaultLvalueConversion(Res.get());
9171 if (!Res.isUsable())
9172 return ExprError();
9173 }
9174 return Res;
9175}
9176
Alexey Bataev60da77e2016-02-29 05:54:20 +00009177static std::pair<ValueDecl *, bool>
9178getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9179 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009180 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9181 RefExpr->containsUnexpandedParameterPack())
9182 return std::make_pair(nullptr, true);
9183
Alexey Bataevd985eda2016-02-10 11:29:16 +00009184 // OpenMP [3.1, C/C++]
9185 // A list item is a variable name.
9186 // OpenMP [2.9.3.3, Restrictions, p.1]
9187 // A variable that is part of another variable (as an array or
9188 // structure element) cannot appear in a private clause.
9189 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009190 enum {
9191 NoArrayExpr = -1,
9192 ArraySubscript = 0,
9193 OMPArraySection = 1
9194 } IsArrayExpr = NoArrayExpr;
9195 if (AllowArraySection) {
9196 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9197 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9198 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9199 Base = TempASE->getBase()->IgnoreParenImpCasts();
9200 RefExpr = Base;
9201 IsArrayExpr = ArraySubscript;
9202 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9203 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9204 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9205 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9206 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9207 Base = TempASE->getBase()->IgnoreParenImpCasts();
9208 RefExpr = Base;
9209 IsArrayExpr = OMPArraySection;
9210 }
9211 }
9212 ELoc = RefExpr->getExprLoc();
9213 ERange = RefExpr->getSourceRange();
9214 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009215 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9216 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9217 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9218 (S.getCurrentThisType().isNull() || !ME ||
9219 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9220 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009221 if (IsArrayExpr != NoArrayExpr)
9222 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9223 << ERange;
9224 else {
9225 S.Diag(ELoc,
9226 AllowArraySection
9227 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9228 : diag::err_omp_expected_var_name_member_expr)
9229 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9230 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009231 return std::make_pair(nullptr, false);
9232 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009233 return std::make_pair(
9234 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009235}
9236
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009237OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9238 SourceLocation StartLoc,
9239 SourceLocation LParenLoc,
9240 SourceLocation EndLoc) {
9241 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009242 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00009243 for (auto &RefExpr : VarList) {
9244 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009245 SourceLocation ELoc;
9246 SourceRange ERange;
9247 Expr *SimpleRefExpr = RefExpr;
9248 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009249 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009250 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009251 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009252 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009253 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009254 ValueDecl *D = Res.first;
9255 if (!D)
9256 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009257
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009258 QualType Type = D->getType();
9259 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009260
9261 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9262 // A variable that appears in a private clause must not have an incomplete
9263 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009264 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009265 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009266 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009267
Alexey Bataev758e55e2013-09-06 18:03:48 +00009268 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9269 // in a Construct]
9270 // Variables with the predetermined data-sharing attributes may not be
9271 // listed in data-sharing attributes clauses, except for the cases
9272 // listed below. For these exceptions only, listing a predetermined
9273 // variable in a data-sharing attribute clause is allowed and overrides
9274 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009275 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009276 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009277 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9278 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009279 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009280 continue;
9281 }
9282
Kelvin Libf594a52016-12-17 05:48:59 +00009283 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009284 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009285 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009286 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009287 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9288 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009289 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009290 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009291 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009292 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009293 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009294 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009295 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009296 continue;
9297 }
9298
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009299 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9300 // A list item cannot appear in both a map clause and a data-sharing
9301 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009302 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Alexey Bataev647dd842018-01-15 20:59:40 +00009303 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009304 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009305 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009306 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009307 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009308 CurrDir == OMPD_target_parallel_for_simd ||
9309 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009310 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009311 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009312 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009313 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9314 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9315 ConflictKind = WhereFoundClauseKind;
9316 return true;
9317 })) {
9318 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009319 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009320 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009321 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009322 ReportOriginalDSA(*this, DSAStack, D, DVar);
9323 continue;
9324 }
9325 }
9326
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009327 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9328 // A variable of class type (or array thereof) that appears in a private
9329 // clause requires an accessible, unambiguous default constructor for the
9330 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009331 // Generate helper private variable and initialize it with the default
9332 // value. The address of the original variable is replaced by the address of
9333 // the new private variable in CodeGen. This new variable is not added to
9334 // IdResolver, so the code in the OpenMP region uses original variable for
9335 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009336 Type = Type.getUnqualifiedType();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00009337 auto VDPrivate =
9338 buildVarDecl(*this, ELoc, Type, D->getName(),
9339 D->hasAttrs() ? &D->getAttrs() : nullptr,
9340 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009341 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009342 if (VDPrivate->isInvalidDecl())
9343 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009344 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009345 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009346
Alexey Bataev90c228f2016-02-08 09:29:13 +00009347 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009348 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009349 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009350 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009351 Vars.push_back((VD || CurContext->isDependentContext())
9352 ? RefExpr->IgnoreParens()
9353 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009354 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009355 }
9356
Alexey Bataeved09d242014-05-28 05:53:51 +00009357 if (Vars.empty())
9358 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009359
Alexey Bataev03b340a2014-10-21 03:16:40 +00009360 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9361 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009362}
9363
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009364namespace {
9365class DiagsUninitializedSeveretyRAII {
9366private:
9367 DiagnosticsEngine &Diags;
9368 SourceLocation SavedLoc;
9369 bool IsIgnored;
9370
9371public:
9372 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9373 bool IsIgnored)
9374 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9375 if (!IsIgnored) {
9376 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9377 /*Map*/ diag::Severity::Ignored, Loc);
9378 }
9379 }
9380 ~DiagsUninitializedSeveretyRAII() {
9381 if (!IsIgnored)
9382 Diags.popMappings(SavedLoc);
9383 }
9384};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009385}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009386
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009387OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9388 SourceLocation StartLoc,
9389 SourceLocation LParenLoc,
9390 SourceLocation EndLoc) {
9391 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009392 SmallVector<Expr *, 8> PrivateCopies;
9393 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009394 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009395 bool IsImplicitClause =
9396 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9397 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9398
Alexey Bataeved09d242014-05-28 05:53:51 +00009399 for (auto &RefExpr : VarList) {
9400 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009401 SourceLocation ELoc;
9402 SourceRange ERange;
9403 Expr *SimpleRefExpr = RefExpr;
9404 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009405 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009406 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009407 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009408 PrivateCopies.push_back(nullptr);
9409 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009410 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009411 ValueDecl *D = Res.first;
9412 if (!D)
9413 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009414
Alexey Bataev60da77e2016-02-29 05:54:20 +00009415 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009416 QualType Type = D->getType();
9417 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009418
9419 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9420 // A variable that appears in a private clause must not have an incomplete
9421 // type or a reference type.
9422 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009423 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009424 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009425 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009426
9427 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9428 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009429 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009430 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009431 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009432
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009433 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009434 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009435 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009436 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009437 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009438 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009439 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009440 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9441 // A list item that specifies a given variable may not appear in more
9442 // than one clause on the same directive, except that a variable may be
9443 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009444 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9445 // A list item may appear in a firstprivate or lastprivate clause but not
9446 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009447 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009448 (isOpenMPDistributeDirective(CurrDir) ||
9449 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009450 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009451 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009452 << getOpenMPClauseName(DVar.CKind)
9453 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009454 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009455 continue;
9456 }
9457
9458 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9459 // in a Construct]
9460 // Variables with the predetermined data-sharing attributes may not be
9461 // listed in data-sharing attributes clauses, except for the cases
9462 // listed below. For these exceptions only, listing a predetermined
9463 // variable in a data-sharing attribute clause is allowed and overrides
9464 // the variable's predetermined data-sharing attributes.
9465 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9466 // in a Construct, C/C++, p.2]
9467 // Variables with const-qualified type having no mutable member may be
9468 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009469 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009470 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9471 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009472 << getOpenMPClauseName(DVar.CKind)
9473 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009474 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009475 continue;
9476 }
9477
9478 // OpenMP [2.9.3.4, Restrictions, p.2]
9479 // A list item that is private within a parallel region must not appear
9480 // in a firstprivate clause on a worksharing construct if any of the
9481 // worksharing regions arising from the worksharing construct ever bind
9482 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009483 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9484 // A list item that is private within a teams region must not appear in a
9485 // firstprivate clause on a distribute construct if any of the distribute
9486 // regions arising from the distribute construct ever bind to any of the
9487 // teams regions arising from the teams construct.
9488 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9489 // A list item that appears in a reduction clause of a teams construct
9490 // must not appear in a firstprivate clause on a distribute construct if
9491 // any of the distribute regions arising from the distribute construct
9492 // ever bind to any of the teams regions arising from the teams construct.
9493 if ((isOpenMPWorksharingDirective(CurrDir) ||
9494 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009495 !isOpenMPParallelDirective(CurrDir) &&
9496 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009497 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009498 if (DVar.CKind != OMPC_shared &&
9499 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009500 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009501 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009502 Diag(ELoc, diag::err_omp_required_access)
9503 << getOpenMPClauseName(OMPC_firstprivate)
9504 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009505 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009506 continue;
9507 }
9508 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009509 // OpenMP [2.9.3.4, Restrictions, p.3]
9510 // A list item that appears in a reduction clause of a parallel construct
9511 // must not appear in a firstprivate clause on a worksharing or task
9512 // construct if any of the worksharing or task regions arising from the
9513 // worksharing or task construct ever bind to any of the parallel regions
9514 // arising from the parallel construct.
9515 // OpenMP [2.9.3.4, Restrictions, p.4]
9516 // A list item that appears in a reduction clause in worksharing
9517 // construct must not appear in a firstprivate clause in a task construct
9518 // encountered during execution of any of the worksharing regions arising
9519 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009520 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009521 DVar = DSAStack->hasInnermostDSA(
9522 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9523 [](OpenMPDirectiveKind K) -> bool {
9524 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009525 isOpenMPWorksharingDirective(K) ||
9526 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009527 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009528 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009529 if (DVar.CKind == OMPC_reduction &&
9530 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009531 isOpenMPWorksharingDirective(DVar.DKind) ||
9532 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009533 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9534 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009535 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009536 continue;
9537 }
9538 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009539
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009540 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9541 // A list item cannot appear in both a map clause and a data-sharing
9542 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009543 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009544 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009545 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009546 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009547 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9548 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9549 ConflictKind = WhereFoundClauseKind;
9550 return true;
9551 })) {
9552 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009553 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009554 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009555 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9556 ReportOriginalDSA(*this, DSAStack, D, DVar);
9557 continue;
9558 }
9559 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009560 }
9561
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009562 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009563 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009564 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009565 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9566 << getOpenMPClauseName(OMPC_firstprivate) << Type
9567 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9568 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009569 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009570 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009571 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009572 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009573 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009574 continue;
9575 }
9576
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009577 Type = Type.getUnqualifiedType();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00009578 auto VDPrivate =
9579 buildVarDecl(*this, ELoc, Type, D->getName(),
9580 D->hasAttrs() ? &D->getAttrs() : nullptr,
9581 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009582 // Generate helper private variable and initialize it with the value of the
9583 // original variable. The address of the original variable is replaced by
9584 // the address of the new private variable in the CodeGen. This new variable
9585 // is not added to IdResolver, so the code in the OpenMP region uses
9586 // original variable for proper diagnostics and variable capturing.
9587 Expr *VDInitRefExpr = nullptr;
9588 // For arrays generate initializer for single element and replace it by the
9589 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009590 if (Type->isArrayType()) {
9591 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009592 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009593 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009594 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009595 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009596 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009597 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009598 InitializedEntity Entity =
9599 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009600 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9601
9602 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9603 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9604 if (Result.isInvalid())
9605 VDPrivate->setInvalidDecl();
9606 else
9607 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009608 // Remove temp variable declaration.
9609 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009610 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009611 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9612 ".firstprivate.temp");
9613 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9614 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009615 AddInitializerToDecl(VDPrivate,
9616 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009617 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009618 }
9619 if (VDPrivate->isInvalidDecl()) {
9620 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009621 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009622 diag::note_omp_task_predetermined_firstprivate_here);
9623 }
9624 continue;
9625 }
9626 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009627 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009628 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9629 RefExpr->getExprLoc());
9630 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009631 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009632 if (TopDVar.CKind == OMPC_lastprivate)
9633 Ref = TopDVar.PrivateCopy;
9634 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009635 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009636 if (!IsOpenMPCapturedDecl(D))
9637 ExprCaptures.push_back(Ref->getDecl());
9638 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009639 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009640 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009641 Vars.push_back((VD || CurContext->isDependentContext())
9642 ? RefExpr->IgnoreParens()
9643 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009644 PrivateCopies.push_back(VDPrivateRefExpr);
9645 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009646 }
9647
Alexey Bataeved09d242014-05-28 05:53:51 +00009648 if (Vars.empty())
9649 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009650
9651 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009652 Vars, PrivateCopies, Inits,
9653 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009654}
9655
Alexander Musman1bb328c2014-06-04 13:06:39 +00009656OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9657 SourceLocation StartLoc,
9658 SourceLocation LParenLoc,
9659 SourceLocation EndLoc) {
9660 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009661 SmallVector<Expr *, 8> SrcExprs;
9662 SmallVector<Expr *, 8> DstExprs;
9663 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009664 SmallVector<Decl *, 4> ExprCaptures;
9665 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009666 for (auto &RefExpr : VarList) {
9667 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009668 SourceLocation ELoc;
9669 SourceRange ERange;
9670 Expr *SimpleRefExpr = RefExpr;
9671 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009672 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009673 // It will be analyzed later.
9674 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009675 SrcExprs.push_back(nullptr);
9676 DstExprs.push_back(nullptr);
9677 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009678 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009679 ValueDecl *D = Res.first;
9680 if (!D)
9681 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009682
Alexey Bataev74caaf22016-02-20 04:09:36 +00009683 QualType Type = D->getType();
9684 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009685
9686 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9687 // A variable that appears in a lastprivate clause must not have an
9688 // incomplete type or a reference type.
9689 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009690 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009691 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009692 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009693
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009694 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009695 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9696 // in a Construct]
9697 // Variables with the predetermined data-sharing attributes may not be
9698 // listed in data-sharing attributes clauses, except for the cases
9699 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009700 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9701 // A list item may appear in a firstprivate or lastprivate clause but not
9702 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009703 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009704 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009705 (isOpenMPDistributeDirective(CurrDir) ||
9706 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009707 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9708 Diag(ELoc, diag::err_omp_wrong_dsa)
9709 << getOpenMPClauseName(DVar.CKind)
9710 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009711 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009712 continue;
9713 }
9714
Alexey Bataevf29276e2014-06-18 04:14:57 +00009715 // OpenMP [2.14.3.5, Restrictions, p.2]
9716 // A list item that is private within a parallel region, or that appears in
9717 // the reduction clause of a parallel construct, must not appear in a
9718 // lastprivate clause on a worksharing construct if any of the corresponding
9719 // worksharing regions ever binds to any of the corresponding parallel
9720 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009721 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009722 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009723 !isOpenMPParallelDirective(CurrDir) &&
9724 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009725 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009726 if (DVar.CKind != OMPC_shared) {
9727 Diag(ELoc, diag::err_omp_required_access)
9728 << getOpenMPClauseName(OMPC_lastprivate)
9729 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009730 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009731 continue;
9732 }
9733 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009734
Alexander Musman1bb328c2014-06-04 13:06:39 +00009735 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009736 // A variable of class type (or array thereof) that appears in a
9737 // lastprivate clause requires an accessible, unambiguous default
9738 // constructor for the class type, unless the list item is also specified
9739 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009740 // A variable of class type (or array thereof) that appears in a
9741 // lastprivate clause requires an accessible, unambiguous copy assignment
9742 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009743 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009744 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009745 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009746 D->hasAttrs() ? &D->getAttrs() : nullptr);
9747 auto *PseudoSrcExpr =
9748 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009749 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009750 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009751 D->hasAttrs() ? &D->getAttrs() : nullptr);
9752 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009753 // For arrays generate assignment operation for single element and replace
9754 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009755 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009756 PseudoDstExpr, PseudoSrcExpr);
9757 if (AssignmentOp.isInvalid())
9758 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009759 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009760 /*DiscardedValue=*/true);
9761 if (AssignmentOp.isInvalid())
9762 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009763
Alexey Bataev74caaf22016-02-20 04:09:36 +00009764 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009765 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009766 if (TopDVar.CKind == OMPC_firstprivate)
9767 Ref = TopDVar.PrivateCopy;
9768 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009769 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009770 if (!IsOpenMPCapturedDecl(D))
9771 ExprCaptures.push_back(Ref->getDecl());
9772 }
9773 if (TopDVar.CKind == OMPC_firstprivate ||
9774 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009775 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009776 ExprResult RefRes = DefaultLvalueConversion(Ref);
9777 if (!RefRes.isUsable())
9778 continue;
9779 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009780 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9781 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009782 if (!PostUpdateRes.isUsable())
9783 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009784 ExprPostUpdates.push_back(
9785 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009786 }
9787 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009788 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009789 Vars.push_back((VD || CurContext->isDependentContext())
9790 ? RefExpr->IgnoreParens()
9791 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009792 SrcExprs.push_back(PseudoSrcExpr);
9793 DstExprs.push_back(PseudoDstExpr);
9794 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009795 }
9796
9797 if (Vars.empty())
9798 return nullptr;
9799
9800 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009801 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009802 buildPreInits(Context, ExprCaptures),
9803 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009804}
9805
Alexey Bataev758e55e2013-09-06 18:03:48 +00009806OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9807 SourceLocation StartLoc,
9808 SourceLocation LParenLoc,
9809 SourceLocation EndLoc) {
9810 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009811 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009812 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009813 SourceLocation ELoc;
9814 SourceRange ERange;
9815 Expr *SimpleRefExpr = RefExpr;
9816 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009817 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009818 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009819 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009820 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009821 ValueDecl *D = Res.first;
9822 if (!D)
9823 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009824
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009825 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009826 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9827 // in a Construct]
9828 // Variables with the predetermined data-sharing attributes may not be
9829 // listed in data-sharing attributes clauses, except for the cases
9830 // listed below. For these exceptions only, listing a predetermined
9831 // variable in a data-sharing attribute clause is allowed and overrides
9832 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009833 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009834 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9835 DVar.RefExpr) {
9836 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9837 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009838 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009839 continue;
9840 }
9841
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009842 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009843 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009844 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009845 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009846 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9847 ? RefExpr->IgnoreParens()
9848 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009849 }
9850
Alexey Bataeved09d242014-05-28 05:53:51 +00009851 if (Vars.empty())
9852 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009853
9854 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9855}
9856
Alexey Bataevc5e02582014-06-16 07:08:35 +00009857namespace {
9858class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9859 DSAStackTy *Stack;
9860
9861public:
9862 bool VisitDeclRefExpr(DeclRefExpr *E) {
9863 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009864 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009865 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9866 return false;
9867 if (DVar.CKind != OMPC_unknown)
9868 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009869 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9870 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009871 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009872 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009873 return true;
9874 return false;
9875 }
9876 return false;
9877 }
9878 bool VisitStmt(Stmt *S) {
9879 for (auto Child : S->children()) {
9880 if (Child && Visit(Child))
9881 return true;
9882 }
9883 return false;
9884 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009885 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009886};
Alexey Bataev23b69422014-06-18 07:08:49 +00009887} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009888
Alexey Bataev60da77e2016-02-29 05:54:20 +00009889namespace {
9890// Transform MemberExpression for specified FieldDecl of current class to
9891// DeclRefExpr to specified OMPCapturedExprDecl.
9892class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9893 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9894 ValueDecl *Field;
9895 DeclRefExpr *CapturedExpr;
9896
9897public:
9898 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9899 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9900
9901 ExprResult TransformMemberExpr(MemberExpr *E) {
9902 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9903 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009904 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009905 return CapturedExpr;
9906 }
9907 return BaseTransform::TransformMemberExpr(E);
9908 }
9909 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9910};
9911} // namespace
9912
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009913template <typename T>
9914static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9915 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9916 for (auto &Set : Lookups) {
9917 for (auto *D : Set) {
9918 if (auto Res = Gen(cast<ValueDecl>(D)))
9919 return Res;
9920 }
9921 }
9922 return T();
9923}
9924
9925static ExprResult
9926buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9927 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9928 const DeclarationNameInfo &ReductionId, QualType Ty,
9929 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9930 if (ReductionIdScopeSpec.isInvalid())
9931 return ExprError();
9932 SmallVector<UnresolvedSet<8>, 4> Lookups;
9933 if (S) {
9934 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9935 Lookup.suppressDiagnostics();
9936 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9937 auto *D = Lookup.getRepresentativeDecl();
9938 do {
9939 S = S->getParent();
9940 } while (S && !S->isDeclScope(D));
9941 if (S)
9942 S = S->getParent();
9943 Lookups.push_back(UnresolvedSet<8>());
9944 Lookups.back().append(Lookup.begin(), Lookup.end());
9945 Lookup.clear();
9946 }
9947 } else if (auto *ULE =
9948 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9949 Lookups.push_back(UnresolvedSet<8>());
9950 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009951 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009952 if (D == PrevD)
9953 Lookups.push_back(UnresolvedSet<8>());
9954 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9955 Lookups.back().addDecl(DRD);
9956 PrevD = D;
9957 }
9958 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009959 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9960 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009961 Ty->containsUnexpandedParameterPack() ||
9962 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9963 return !D->isInvalidDecl() &&
9964 (D->getType()->isDependentType() ||
9965 D->getType()->isInstantiationDependentType() ||
9966 D->getType()->containsUnexpandedParameterPack());
9967 })) {
9968 UnresolvedSet<8> ResSet;
9969 for (auto &Set : Lookups) {
9970 ResSet.append(Set.begin(), Set.end());
9971 // The last item marks the end of all declarations at the specified scope.
9972 ResSet.addDecl(Set[Set.size() - 1]);
9973 }
9974 return UnresolvedLookupExpr::Create(
9975 SemaRef.Context, /*NamingClass=*/nullptr,
9976 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9977 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9978 }
9979 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9980 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9981 if (!D->isInvalidDecl() &&
9982 SemaRef.Context.hasSameType(D->getType(), Ty))
9983 return D;
9984 return nullptr;
9985 }))
9986 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9987 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9988 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9989 if (!D->isInvalidDecl() &&
9990 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9991 !Ty.isMoreQualifiedThan(D->getType()))
9992 return D;
9993 return nullptr;
9994 })) {
9995 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9996 /*DetectVirtual=*/false);
9997 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9998 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9999 VD->getType().getUnqualifiedType()))) {
10000 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10001 /*DiagID=*/0) !=
10002 Sema::AR_inaccessible) {
10003 SemaRef.BuildBasePathArray(Paths, BasePath);
10004 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10005 }
10006 }
10007 }
10008 }
10009 if (ReductionIdScopeSpec.isSet()) {
10010 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10011 return ExprError();
10012 }
10013 return ExprEmpty();
10014}
10015
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010016namespace {
10017/// Data for the reduction-based clauses.
10018struct ReductionData {
10019 /// List of original reduction items.
10020 SmallVector<Expr *, 8> Vars;
10021 /// List of private copies of the reduction items.
10022 SmallVector<Expr *, 8> Privates;
10023 /// LHS expressions for the reduction_op expressions.
10024 SmallVector<Expr *, 8> LHSs;
10025 /// RHS expressions for the reduction_op expressions.
10026 SmallVector<Expr *, 8> RHSs;
10027 /// Reduction operation expression.
10028 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010029 /// Taskgroup descriptors for the corresponding reduction items in
10030 /// in_reduction clauses.
10031 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010032 /// List of captures for clause.
10033 SmallVector<Decl *, 4> ExprCaptures;
10034 /// List of postupdate expressions.
10035 SmallVector<Expr *, 4> ExprPostUpdates;
10036 ReductionData() = delete;
10037 /// Reserves required memory for the reduction data.
10038 ReductionData(unsigned Size) {
10039 Vars.reserve(Size);
10040 Privates.reserve(Size);
10041 LHSs.reserve(Size);
10042 RHSs.reserve(Size);
10043 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010044 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010045 ExprCaptures.reserve(Size);
10046 ExprPostUpdates.reserve(Size);
10047 }
10048 /// Stores reduction item and reduction operation only (required for dependent
10049 /// reduction item).
10050 void push(Expr *Item, Expr *ReductionOp) {
10051 Vars.emplace_back(Item);
10052 Privates.emplace_back(nullptr);
10053 LHSs.emplace_back(nullptr);
10054 RHSs.emplace_back(nullptr);
10055 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010056 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010057 }
10058 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010059 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10060 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010061 Vars.emplace_back(Item);
10062 Privates.emplace_back(Private);
10063 LHSs.emplace_back(LHS);
10064 RHSs.emplace_back(RHS);
10065 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010066 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010067 }
10068};
10069} // namespace
10070
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010071static bool CheckOMPArraySectionConstantForReduction(
10072 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10073 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10074 const Expr *Length = OASE->getLength();
10075 if (Length == nullptr) {
10076 // For array sections of the form [1:] or [:], we would need to analyze
10077 // the lower bound...
10078 if (OASE->getColonLoc().isValid())
10079 return false;
10080
10081 // This is an array subscript which has implicit length 1!
10082 SingleElement = true;
10083 ArraySizes.push_back(llvm::APSInt::get(1));
10084 } else {
10085 llvm::APSInt ConstantLengthValue;
10086 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10087 return false;
10088
10089 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10090 ArraySizes.push_back(ConstantLengthValue);
10091 }
10092
10093 // Get the base of this array section and walk up from there.
10094 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10095
10096 // We require length = 1 for all array sections except the right-most to
10097 // guarantee that the memory region is contiguous and has no holes in it.
10098 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10099 Length = TempOASE->getLength();
10100 if (Length == nullptr) {
10101 // For array sections of the form [1:] or [:], we would need to analyze
10102 // the lower bound...
10103 if (OASE->getColonLoc().isValid())
10104 return false;
10105
10106 // This is an array subscript which has implicit length 1!
10107 ArraySizes.push_back(llvm::APSInt::get(1));
10108 } else {
10109 llvm::APSInt ConstantLengthValue;
10110 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10111 ConstantLengthValue.getSExtValue() != 1)
10112 return false;
10113
10114 ArraySizes.push_back(ConstantLengthValue);
10115 }
10116 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10117 }
10118
10119 // If we have a single element, we don't need to add the implicit lengths.
10120 if (!SingleElement) {
10121 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10122 // Has implicit length 1!
10123 ArraySizes.push_back(llvm::APSInt::get(1));
10124 Base = TempASE->getBase()->IgnoreParenImpCasts();
10125 }
10126 }
10127
10128 // This array section can be privatized as a single value or as a constant
10129 // sized array.
10130 return true;
10131}
10132
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010133static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010134 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10135 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10136 SourceLocation ColonLoc, SourceLocation EndLoc,
10137 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010138 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010139 auto DN = ReductionId.getName();
10140 auto OOK = DN.getCXXOverloadedOperator();
10141 BinaryOperatorKind BOK = BO_Comma;
10142
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010143 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010144 // OpenMP [2.14.3.6, reduction clause]
10145 // C
10146 // reduction-identifier is either an identifier or one of the following
10147 // operators: +, -, *, &, |, ^, && and ||
10148 // C++
10149 // reduction-identifier is either an id-expression or one of the following
10150 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010151 switch (OOK) {
10152 case OO_Plus:
10153 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010154 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010155 break;
10156 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010157 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010158 break;
10159 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010160 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010161 break;
10162 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010163 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010164 break;
10165 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010166 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010167 break;
10168 case OO_AmpAmp:
10169 BOK = BO_LAnd;
10170 break;
10171 case OO_PipePipe:
10172 BOK = BO_LOr;
10173 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010174 case OO_New:
10175 case OO_Delete:
10176 case OO_Array_New:
10177 case OO_Array_Delete:
10178 case OO_Slash:
10179 case OO_Percent:
10180 case OO_Tilde:
10181 case OO_Exclaim:
10182 case OO_Equal:
10183 case OO_Less:
10184 case OO_Greater:
10185 case OO_LessEqual:
10186 case OO_GreaterEqual:
10187 case OO_PlusEqual:
10188 case OO_MinusEqual:
10189 case OO_StarEqual:
10190 case OO_SlashEqual:
10191 case OO_PercentEqual:
10192 case OO_CaretEqual:
10193 case OO_AmpEqual:
10194 case OO_PipeEqual:
10195 case OO_LessLess:
10196 case OO_GreaterGreater:
10197 case OO_LessLessEqual:
10198 case OO_GreaterGreaterEqual:
10199 case OO_EqualEqual:
10200 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010201 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010202 case OO_PlusPlus:
10203 case OO_MinusMinus:
10204 case OO_Comma:
10205 case OO_ArrowStar:
10206 case OO_Arrow:
10207 case OO_Call:
10208 case OO_Subscript:
10209 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010210 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010211 case NUM_OVERLOADED_OPERATORS:
10212 llvm_unreachable("Unexpected reduction identifier");
10213 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010214 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010215 if (II->isStr("max"))
10216 BOK = BO_GT;
10217 else if (II->isStr("min"))
10218 BOK = BO_LT;
10219 }
10220 break;
10221 }
10222 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010223 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010224 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010225 else
10226 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010227 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010228
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010229 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10230 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010231 for (auto RefExpr : VarList) {
10232 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010233 // OpenMP [2.1, C/C++]
10234 // A list item is a variable or array section, subject to the restrictions
10235 // specified in Section 2.4 on page 42 and in each of the sections
10236 // describing clauses and directives for which a list appears.
10237 // OpenMP [2.14.3.3, Restrictions, p.1]
10238 // A variable that is part of another variable (as an array or
10239 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010240 if (!FirstIter && IR != ER)
10241 ++IR;
10242 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010243 SourceLocation ELoc;
10244 SourceRange ERange;
10245 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010246 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010247 /*AllowArraySection=*/true);
10248 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010249 // Try to find 'declare reduction' corresponding construct before using
10250 // builtin/overloaded operators.
10251 QualType Type = Context.DependentTy;
10252 CXXCastPath BasePath;
10253 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010254 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010255 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010256 Expr *ReductionOp = nullptr;
10257 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010258 (DeclareReductionRef.isUnset() ||
10259 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010260 ReductionOp = DeclareReductionRef.get();
10261 // It will be analyzed later.
10262 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010263 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010264 ValueDecl *D = Res.first;
10265 if (!D)
10266 continue;
10267
Alexey Bataev88202be2017-07-27 13:20:36 +000010268 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010269 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010270 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10271 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10272 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +000010273 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010274 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010275 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10276 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10277 Type = ATy->getElementType();
10278 else
10279 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010280 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010281 } else
10282 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10283 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010284
Alexey Bataevc5e02582014-06-16 07:08:35 +000010285 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10286 // A variable that appears in a private clause must not have an incomplete
10287 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010288 if (S.RequireCompleteType(ELoc, Type,
10289 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010290 continue;
10291 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010292 // A list item that appears in a reduction clause must not be
10293 // const-qualified.
10294 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010295 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010296 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010297 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10298 VarDecl::DeclarationOnly;
10299 S.Diag(D->getLocation(),
10300 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010301 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010302 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010303 continue;
10304 }
10305 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10306 // If a list-item is a reference type then it must bind to the same object
10307 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010308 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010309 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010310 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010311 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010312 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010313 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10314 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010315 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010316 continue;
10317 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010318 }
10319 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010320
Alexey Bataevc5e02582014-06-16 07:08:35 +000010321 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10322 // in a Construct]
10323 // Variables with the predetermined data-sharing attributes may not be
10324 // listed in data-sharing attributes clauses, except for the cases
10325 // listed below. For these exceptions only, listing a predetermined
10326 // variable in a data-sharing attribute clause is allowed and overrides
10327 // the variable's predetermined data-sharing attributes.
10328 // OpenMP [2.14.3.6, Restrictions, p.3]
10329 // Any number of reduction clauses can be specified on the directive,
10330 // but a list item can appear only once in the reduction clauses for that
10331 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010332 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010333 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010334 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010335 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010336 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010337 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010338 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010339 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010340 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010341 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010342 << getOpenMPClauseName(DVar.CKind)
10343 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010344 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010345 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010346 }
10347
10348 // OpenMP [2.14.3.6, Restrictions, p.1]
10349 // A list item that appears in a reduction clause of a worksharing
10350 // construct must be shared in the parallel regions to which any of the
10351 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010352 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010353 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010354 !isOpenMPParallelDirective(CurrDir) &&
10355 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010356 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010357 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010358 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010359 << getOpenMPClauseName(OMPC_reduction)
10360 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010361 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010362 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010363 }
10364 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010365
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010366 // Try to find 'declare reduction' corresponding construct before using
10367 // builtin/overloaded operators.
10368 CXXCastPath BasePath;
10369 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010370 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010371 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10372 if (DeclareReductionRef.isInvalid())
10373 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010374 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010375 (DeclareReductionRef.isUnset() ||
10376 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010377 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010378 continue;
10379 }
10380 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10381 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010382 S.Diag(ReductionId.getLocStart(),
10383 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010384 << Type << ReductionIdRange;
10385 continue;
10386 }
10387
10388 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10389 // The type of a list item that appears in a reduction clause must be valid
10390 // for the reduction-identifier. For a max or min reduction in C, the type
10391 // of the list item must be an allowed arithmetic data type: char, int,
10392 // float, double, or _Bool, possibly modified with long, short, signed, or
10393 // unsigned. For a max or min reduction in C++, the type of the list item
10394 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10395 // double, or bool, possibly modified with long, short, signed, or unsigned.
10396 if (DeclareReductionRef.isUnset()) {
10397 if ((BOK == BO_GT || BOK == BO_LT) &&
10398 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010399 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10400 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010401 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010402 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010403 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10404 VarDecl::DeclarationOnly;
10405 S.Diag(D->getLocation(),
10406 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010407 << D;
10408 }
10409 continue;
10410 }
10411 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010412 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010413 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10414 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010415 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010416 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10417 VarDecl::DeclarationOnly;
10418 S.Diag(D->getLocation(),
10419 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010420 << D;
10421 }
10422 continue;
10423 }
10424 }
10425
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010426 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010427 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010428 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010429 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010430 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010431 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010432
10433 // Try if we can determine constant lengths for all array sections and avoid
10434 // the VLA.
10435 bool ConstantLengthOASE = false;
10436 if (OASE) {
10437 bool SingleElement;
10438 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10439 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10440 Context, OASE, SingleElement, ArraySizes);
10441
10442 // If we don't have a single element, we must emit a constant array type.
10443 if (ConstantLengthOASE && !SingleElement) {
10444 for (auto &Size : ArraySizes) {
10445 PrivateTy = Context.getConstantArrayType(
10446 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10447 }
10448 }
10449 }
10450
10451 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010452 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010453 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010454 if (!Context.getTargetInfo().isVLASupported() &&
10455 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10456 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10457 S.Diag(ELoc, diag::note_vla_unsupported);
10458 continue;
10459 }
David Majnemer9d168222016-08-05 17:44:54 +000010460 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010461 // Create pseudo array type for private copy. The size for this array will
10462 // be generated during codegen.
10463 // For array subscripts or single variables Private Ty is the same as Type
10464 // (type of the variable or single array element).
10465 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010466 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010467 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010468 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010469 } else if (!ASE && !OASE &&
10470 Context.getAsArrayType(D->getType().getNonReferenceType()))
10471 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010472 // Private copy.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010473 auto *PrivateVD =
10474 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10475 D->hasAttrs() ? &D->getAttrs() : nullptr,
10476 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010477 // Add initializer for private variable.
10478 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010479 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10480 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010481 if (DeclareReductionRef.isUsable()) {
10482 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10483 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10484 if (DRD->getInitializer()) {
10485 Init = DRDRef;
10486 RHSVD->setInit(DRDRef);
10487 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010488 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010489 } else {
10490 switch (BOK) {
10491 case BO_Add:
10492 case BO_Xor:
10493 case BO_Or:
10494 case BO_LOr:
10495 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10496 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010497 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010498 break;
10499 case BO_Mul:
10500 case BO_LAnd:
10501 if (Type->isScalarType() || Type->isAnyComplexType()) {
10502 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010503 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010504 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010505 break;
10506 case BO_And: {
10507 // '&' reduction op - initializer is '~0'.
10508 QualType OrigType = Type;
10509 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10510 Type = ComplexTy->getElementType();
10511 if (Type->isRealFloatingType()) {
10512 llvm::APFloat InitValue =
10513 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10514 /*isIEEE=*/true);
10515 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10516 Type, ELoc);
10517 } else if (Type->isScalarType()) {
10518 auto Size = Context.getTypeSize(Type);
10519 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10520 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10521 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10522 }
10523 if (Init && OrigType->isAnyComplexType()) {
10524 // Init = 0xFFFF + 0xFFFFi;
10525 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010526 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010527 }
10528 Type = OrigType;
10529 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010530 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010531 case BO_LT:
10532 case BO_GT: {
10533 // 'min' reduction op - initializer is 'Largest representable number in
10534 // the reduction list item type'.
10535 // 'max' reduction op - initializer is 'Least representable number in
10536 // the reduction list item type'.
10537 if (Type->isIntegerType() || Type->isPointerType()) {
10538 bool IsSigned = Type->hasSignedIntegerRepresentation();
10539 auto Size = Context.getTypeSize(Type);
10540 QualType IntTy =
10541 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10542 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010543 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10544 : llvm::APInt::getMinValue(Size)
10545 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10546 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010547 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10548 if (Type->isPointerType()) {
10549 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010550 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010551 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010552 if (CastExpr.isInvalid())
10553 continue;
10554 Init = CastExpr.get();
10555 }
10556 } else if (Type->isRealFloatingType()) {
10557 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10558 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10559 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10560 Type, ELoc);
10561 }
10562 break;
10563 }
10564 case BO_PtrMemD:
10565 case BO_PtrMemI:
10566 case BO_MulAssign:
10567 case BO_Div:
10568 case BO_Rem:
10569 case BO_Sub:
10570 case BO_Shl:
10571 case BO_Shr:
10572 case BO_LE:
10573 case BO_GE:
10574 case BO_EQ:
10575 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000010576 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010577 case BO_AndAssign:
10578 case BO_XorAssign:
10579 case BO_OrAssign:
10580 case BO_Assign:
10581 case BO_AddAssign:
10582 case BO_SubAssign:
10583 case BO_DivAssign:
10584 case BO_RemAssign:
10585 case BO_ShlAssign:
10586 case BO_ShrAssign:
10587 case BO_Comma:
10588 llvm_unreachable("Unexpected reduction operation");
10589 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010590 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010591 if (Init && DeclareReductionRef.isUnset())
10592 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10593 else if (!Init)
10594 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010595 if (RHSVD->isInvalidDecl())
10596 continue;
10597 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010598 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10599 << Type << ReductionIdRange;
10600 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10601 VarDecl::DeclarationOnly;
10602 S.Diag(D->getLocation(),
10603 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010604 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010605 continue;
10606 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010607 // Store initializer for single element in private copy. Will be used during
10608 // codegen.
10609 PrivateVD->setInit(RHSVD->getInit());
10610 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010611 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010612 ExprResult ReductionOp;
10613 if (DeclareReductionRef.isUsable()) {
10614 QualType RedTy = DeclareReductionRef.get()->getType();
10615 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010616 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10617 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010618 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010619 LHS = S.DefaultLvalueConversion(LHS.get());
10620 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010621 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10622 CK_UncheckedDerivedToBase, LHS.get(),
10623 &BasePath, LHS.get()->getValueKind());
10624 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10625 CK_UncheckedDerivedToBase, RHS.get(),
10626 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010627 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010628 FunctionProtoType::ExtProtoInfo EPI;
10629 QualType Params[] = {PtrRedTy, PtrRedTy};
10630 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10631 auto *OVE = new (Context) OpaqueValueExpr(
10632 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010633 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010634 Expr *Args[] = {LHS.get(), RHS.get()};
10635 ReductionOp = new (Context)
10636 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10637 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010638 ReductionOp = S.BuildBinOp(
10639 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010640 if (ReductionOp.isUsable()) {
10641 if (BOK != BO_LT && BOK != BO_GT) {
10642 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010643 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10644 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010645 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010646 auto *ConditionalOp = new (Context)
10647 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10648 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010649 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010650 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10651 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010652 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010653 if (ReductionOp.isUsable())
10654 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010655 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010656 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010657 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010658 }
10659
Alexey Bataevfa312f32017-07-21 18:48:21 +000010660 // OpenMP [2.15.4.6, Restrictions, p.2]
10661 // A list item that appears in an in_reduction clause of a task construct
10662 // must appear in a task_reduction clause of a construct associated with a
10663 // taskgroup region that includes the participating task in its taskgroup
10664 // set. The construct associated with the innermost region that meets this
10665 // condition must specify the same reduction-identifier as the in_reduction
10666 // clause.
10667 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010668 SourceRange ParentSR;
10669 BinaryOperatorKind ParentBOK;
10670 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010671 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010672 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010673 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10674 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010675 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010676 Stack->getTopMostTaskgroupReductionData(
10677 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010678 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10679 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10680 if (!IsParentBOK && !IsParentReductionOp) {
10681 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10682 continue;
10683 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010684 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10685 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10686 IsParentReductionOp) {
10687 bool EmitError = true;
10688 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10689 llvm::FoldingSetNodeID RedId, ParentRedId;
10690 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10691 DeclareReductionRef.get()->Profile(RedId, Context,
10692 /*Canonical=*/true);
10693 EmitError = RedId != ParentRedId;
10694 }
10695 if (EmitError) {
10696 S.Diag(ReductionId.getLocStart(),
10697 diag::err_omp_reduction_identifier_mismatch)
10698 << ReductionIdRange << RefExpr->getSourceRange();
10699 S.Diag(ParentSR.getBegin(),
10700 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010701 << ParentSR
10702 << (IsParentBOK ? ParentBOKDSA.RefExpr
10703 : ParentReductionOpDSA.RefExpr)
10704 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010705 continue;
10706 }
10707 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010708 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10709 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010710 }
10711
Alexey Bataev60da77e2016-02-29 05:54:20 +000010712 DeclRefExpr *Ref = nullptr;
10713 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010714 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010715 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010716 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010717 VarsExpr =
10718 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10719 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010720 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010721 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010722 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010723 if (!S.IsOpenMPCapturedDecl(D)) {
10724 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010725 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010726 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010727 if (!RefRes.isUsable())
10728 continue;
10729 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010730 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10731 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010732 if (!PostUpdateRes.isUsable())
10733 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010734 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10735 Stack->getCurrentDirective() == OMPD_taskgroup) {
10736 S.Diag(RefExpr->getExprLoc(),
10737 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010738 << RefExpr->getSourceRange();
10739 continue;
10740 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010741 RD.ExprPostUpdates.emplace_back(
10742 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010743 }
10744 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010745 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010746 // All reduction items are still marked as reduction (to do not increase
10747 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010748 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010749 if (CurrDir == OMPD_taskgroup) {
10750 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010751 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10752 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010753 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010754 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010755 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010756 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10757 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010758 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010759 return RD.Vars.empty();
10760}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010761
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010762OMPClause *Sema::ActOnOpenMPReductionClause(
10763 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10764 SourceLocation ColonLoc, SourceLocation EndLoc,
10765 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10766 ArrayRef<Expr *> UnresolvedReductions) {
10767 ReductionData RD(VarList.size());
10768
Alexey Bataev169d96a2017-07-18 20:17:46 +000010769 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10770 StartLoc, LParenLoc, ColonLoc, EndLoc,
10771 ReductionIdScopeSpec, ReductionId,
10772 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010773 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010774
Alexey Bataevc5e02582014-06-16 07:08:35 +000010775 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010776 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10777 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10778 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10779 buildPreInits(Context, RD.ExprCaptures),
10780 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010781}
10782
Alexey Bataev169d96a2017-07-18 20:17:46 +000010783OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10784 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10785 SourceLocation ColonLoc, SourceLocation EndLoc,
10786 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10787 ArrayRef<Expr *> UnresolvedReductions) {
10788 ReductionData RD(VarList.size());
10789
10790 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10791 VarList, StartLoc, LParenLoc, ColonLoc,
10792 EndLoc, ReductionIdScopeSpec, ReductionId,
10793 UnresolvedReductions, RD))
10794 return nullptr;
10795
10796 return OMPTaskReductionClause::Create(
10797 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10798 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10799 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10800 buildPreInits(Context, RD.ExprCaptures),
10801 buildPostUpdate(*this, RD.ExprPostUpdates));
10802}
10803
Alexey Bataevfa312f32017-07-21 18:48:21 +000010804OMPClause *Sema::ActOnOpenMPInReductionClause(
10805 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10806 SourceLocation ColonLoc, SourceLocation EndLoc,
10807 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10808 ArrayRef<Expr *> UnresolvedReductions) {
10809 ReductionData RD(VarList.size());
10810
10811 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10812 StartLoc, LParenLoc, ColonLoc, EndLoc,
10813 ReductionIdScopeSpec, ReductionId,
10814 UnresolvedReductions, RD))
10815 return nullptr;
10816
10817 return OMPInReductionClause::Create(
10818 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10819 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010820 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010821 buildPreInits(Context, RD.ExprCaptures),
10822 buildPostUpdate(*this, RD.ExprPostUpdates));
10823}
10824
Alexey Bataevecba70f2016-04-12 11:02:11 +000010825bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10826 SourceLocation LinLoc) {
10827 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10828 LinKind == OMPC_LINEAR_unknown) {
10829 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10830 return true;
10831 }
10832 return false;
10833}
10834
10835bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10836 OpenMPLinearClauseKind LinKind,
10837 QualType Type) {
10838 auto *VD = dyn_cast_or_null<VarDecl>(D);
10839 // A variable must not have an incomplete type or a reference type.
10840 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10841 return true;
10842 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10843 !Type->isReferenceType()) {
10844 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10845 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10846 return true;
10847 }
10848 Type = Type.getNonReferenceType();
10849
10850 // A list item must not be const-qualified.
10851 if (Type.isConstant(Context)) {
10852 Diag(ELoc, diag::err_omp_const_variable)
10853 << getOpenMPClauseName(OMPC_linear);
10854 if (D) {
10855 bool IsDecl =
10856 !VD ||
10857 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10858 Diag(D->getLocation(),
10859 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10860 << D;
10861 }
10862 return true;
10863 }
10864
10865 // A list item must be of integral or pointer type.
10866 Type = Type.getUnqualifiedType().getCanonicalType();
10867 const auto *Ty = Type.getTypePtrOrNull();
10868 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10869 !Ty->isPointerType())) {
10870 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10871 if (D) {
10872 bool IsDecl =
10873 !VD ||
10874 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10875 Diag(D->getLocation(),
10876 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10877 << D;
10878 }
10879 return true;
10880 }
10881 return false;
10882}
10883
Alexey Bataev182227b2015-08-20 10:54:39 +000010884OMPClause *Sema::ActOnOpenMPLinearClause(
10885 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10886 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10887 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010888 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010889 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010890 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010891 SmallVector<Decl *, 4> ExprCaptures;
10892 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010893 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010894 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010895 for (auto &RefExpr : VarList) {
10896 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010897 SourceLocation ELoc;
10898 SourceRange ERange;
10899 Expr *SimpleRefExpr = RefExpr;
10900 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10901 /*AllowArraySection=*/false);
10902 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010903 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010904 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010905 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010906 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010907 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010908 ValueDecl *D = Res.first;
10909 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010910 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010911
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010912 QualType Type = D->getType();
10913 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010914
10915 // OpenMP [2.14.3.7, linear clause]
10916 // A list-item cannot appear in more than one linear clause.
10917 // A list-item that appears in a linear clause cannot appear in any
10918 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010919 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010920 if (DVar.RefExpr) {
10921 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10922 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010923 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010924 continue;
10925 }
10926
Alexey Bataevecba70f2016-04-12 11:02:11 +000010927 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010928 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010929 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010930
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010931 // Build private copy of original var.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010932 auto *Private =
10933 buildVarDecl(*this, ELoc, Type, D->getName(),
10934 D->hasAttrs() ? &D->getAttrs() : nullptr,
10935 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010936 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010937 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010938 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010939 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010940 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010941 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010942 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10943 if (!IsOpenMPCapturedDecl(D)) {
10944 ExprCaptures.push_back(Ref->getDecl());
10945 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10946 ExprResult RefRes = DefaultLvalueConversion(Ref);
10947 if (!RefRes.isUsable())
10948 continue;
10949 ExprResult PostUpdateRes =
10950 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10951 SimpleRefExpr, RefRes.get());
10952 if (!PostUpdateRes.isUsable())
10953 continue;
10954 ExprPostUpdates.push_back(
10955 IgnoredValueConversions(PostUpdateRes.get()).get());
10956 }
10957 }
10958 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010959 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010960 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010961 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010962 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010963 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010964 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010965 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10966
10967 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010968 Vars.push_back((VD || CurContext->isDependentContext())
10969 ? RefExpr->IgnoreParens()
10970 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010971 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010972 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010973 }
10974
10975 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010976 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010977
10978 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010979 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010980 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10981 !Step->isInstantiationDependent() &&
10982 !Step->containsUnexpandedParameterPack()) {
10983 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010984 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010985 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010986 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010987 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010988
Alexander Musman3276a272015-03-21 10:12:56 +000010989 // Build var to save the step value.
10990 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010991 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010992 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010993 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010994 ExprResult CalcStep =
10995 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010996 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010997
Alexander Musman8dba6642014-04-22 13:09:42 +000010998 // Warn about zero linear step (it would be probably better specified as
10999 // making corresponding variables 'const').
11000 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011001 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11002 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011003 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11004 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011005 if (!IsConstant && CalcStep.isUsable()) {
11006 // Calculate the step beforehand instead of doing this on each iteration.
11007 // (This is not used if the number of iterations may be kfold-ed).
11008 CalcStepExpr = CalcStep.get();
11009 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011010 }
11011
Alexey Bataev182227b2015-08-20 10:54:39 +000011012 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11013 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011014 StepExpr, CalcStepExpr,
11015 buildPreInits(Context, ExprCaptures),
11016 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011017}
11018
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011019static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11020 Expr *NumIterations, Sema &SemaRef,
11021 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011022 // Walk the vars and build update/final expressions for the CodeGen.
11023 SmallVector<Expr *, 8> Updates;
11024 SmallVector<Expr *, 8> Finals;
11025 Expr *Step = Clause.getStep();
11026 Expr *CalcStep = Clause.getCalcStep();
11027 // OpenMP [2.14.3.7, linear clause]
11028 // If linear-step is not specified it is assumed to be 1.
11029 if (Step == nullptr)
11030 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011031 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000011032 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011033 }
Alexander Musman3276a272015-03-21 10:12:56 +000011034 bool HasErrors = false;
11035 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011036 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011037 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000011038 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011039 SourceLocation ELoc;
11040 SourceRange ERange;
11041 Expr *SimpleRefExpr = RefExpr;
11042 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
11043 /*AllowArraySection=*/false);
11044 ValueDecl *D = Res.first;
11045 if (Res.second || !D) {
11046 Updates.push_back(nullptr);
11047 Finals.push_back(nullptr);
11048 HasErrors = true;
11049 continue;
11050 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011051 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011052 // OpenMP [2.15.11, distribute simd Construct]
11053 // A list item may not appear in a linear clause, unless it is the loop
11054 // iteration variable.
11055 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11056 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11057 SemaRef.Diag(ELoc,
11058 diag::err_omp_linear_distribute_var_non_loop_iteration);
11059 Updates.push_back(nullptr);
11060 Finals.push_back(nullptr);
11061 HasErrors = true;
11062 continue;
11063 }
Alexander Musman3276a272015-03-21 10:12:56 +000011064 Expr *InitExpr = *CurInit;
11065
11066 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011067 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011068 Expr *CapturedRef;
11069 if (LinKind == OMPC_LINEAR_uval)
11070 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11071 else
11072 CapturedRef =
11073 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11074 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11075 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011076
11077 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011078 ExprResult Update;
11079 if (!Info.first) {
11080 Update =
11081 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11082 InitExpr, IV, Step, /* Subtract */ false);
11083 } else
11084 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011085 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11086 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011087
11088 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011089 ExprResult Final;
11090 if (!Info.first) {
11091 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11092 InitExpr, NumIterations, Step,
11093 /* Subtract */ false);
11094 } else
11095 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011096 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11097 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011098
Alexander Musman3276a272015-03-21 10:12:56 +000011099 if (!Update.isUsable() || !Final.isUsable()) {
11100 Updates.push_back(nullptr);
11101 Finals.push_back(nullptr);
11102 HasErrors = true;
11103 } else {
11104 Updates.push_back(Update.get());
11105 Finals.push_back(Final.get());
11106 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011107 ++CurInit;
11108 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011109 }
11110 Clause.setUpdates(Updates);
11111 Clause.setFinals(Finals);
11112 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011113}
11114
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011115OMPClause *Sema::ActOnOpenMPAlignedClause(
11116 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11117 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11118
11119 SmallVector<Expr *, 8> Vars;
11120 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011121 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11122 SourceLocation ELoc;
11123 SourceRange ERange;
11124 Expr *SimpleRefExpr = RefExpr;
11125 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11126 /*AllowArraySection=*/false);
11127 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011128 // It will be analyzed later.
11129 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011130 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011131 ValueDecl *D = Res.first;
11132 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011133 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011134
Alexey Bataev1efd1662016-03-29 10:59:56 +000011135 QualType QType = D->getType();
11136 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011137
11138 // OpenMP [2.8.1, simd construct, Restrictions]
11139 // The type of list items appearing in the aligned clause must be
11140 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011141 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011142 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011143 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011144 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011145 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011146 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011147 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011148 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011149 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011150 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011151 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011152 continue;
11153 }
11154
11155 // OpenMP [2.8.1, simd construct, Restrictions]
11156 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000011157 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011158 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011159 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11160 << getOpenMPClauseName(OMPC_aligned);
11161 continue;
11162 }
11163
Alexey Bataev1efd1662016-03-29 10:59:56 +000011164 DeclRefExpr *Ref = nullptr;
11165 if (!VD && IsOpenMPCapturedDecl(D))
11166 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11167 Vars.push_back(DefaultFunctionArrayConversion(
11168 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11169 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011170 }
11171
11172 // OpenMP [2.8.1, simd construct, Description]
11173 // The parameter of the aligned clause, alignment, must be a constant
11174 // positive integer expression.
11175 // If no optional parameter is specified, implementation-defined default
11176 // alignments for SIMD instructions on the target platforms are assumed.
11177 if (Alignment != nullptr) {
11178 ExprResult AlignResult =
11179 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11180 if (AlignResult.isInvalid())
11181 return nullptr;
11182 Alignment = AlignResult.get();
11183 }
11184 if (Vars.empty())
11185 return nullptr;
11186
11187 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11188 EndLoc, Vars, Alignment);
11189}
11190
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011191OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11192 SourceLocation StartLoc,
11193 SourceLocation LParenLoc,
11194 SourceLocation EndLoc) {
11195 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011196 SmallVector<Expr *, 8> SrcExprs;
11197 SmallVector<Expr *, 8> DstExprs;
11198 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000011199 for (auto &RefExpr : VarList) {
11200 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11201 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011202 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011203 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011204 SrcExprs.push_back(nullptr);
11205 DstExprs.push_back(nullptr);
11206 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011207 continue;
11208 }
11209
Alexey Bataeved09d242014-05-28 05:53:51 +000011210 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011211 // OpenMP [2.1, C/C++]
11212 // A list item is a variable name.
11213 // OpenMP [2.14.4.1, Restrictions, p.1]
11214 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000011215 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011216 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011217 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11218 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011219 continue;
11220 }
11221
11222 Decl *D = DE->getDecl();
11223 VarDecl *VD = cast<VarDecl>(D);
11224
11225 QualType Type = VD->getType();
11226 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11227 // It will be analyzed later.
11228 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011229 SrcExprs.push_back(nullptr);
11230 DstExprs.push_back(nullptr);
11231 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011232 continue;
11233 }
11234
11235 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11236 // A list item that appears in a copyin clause must be threadprivate.
11237 if (!DSAStack->isThreadPrivate(VD)) {
11238 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011239 << getOpenMPClauseName(OMPC_copyin)
11240 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011241 continue;
11242 }
11243
11244 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11245 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011246 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011247 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011248 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011249 auto *SrcVD =
11250 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11251 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000011252 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011253 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11254 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011255 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11256 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011257 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011258 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011259 // For arrays generate assignment operation for single element and replace
11260 // it by the original array element in CodeGen.
11261 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11262 PseudoDstExpr, PseudoSrcExpr);
11263 if (AssignmentOp.isInvalid())
11264 continue;
11265 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11266 /*DiscardedValue=*/true);
11267 if (AssignmentOp.isInvalid())
11268 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011269
11270 DSAStack->addDSA(VD, DE, OMPC_copyin);
11271 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011272 SrcExprs.push_back(PseudoSrcExpr);
11273 DstExprs.push_back(PseudoDstExpr);
11274 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011275 }
11276
Alexey Bataeved09d242014-05-28 05:53:51 +000011277 if (Vars.empty())
11278 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011279
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011280 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11281 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011282}
11283
Alexey Bataevbae9a792014-06-27 10:37:06 +000011284OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11285 SourceLocation StartLoc,
11286 SourceLocation LParenLoc,
11287 SourceLocation EndLoc) {
11288 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011289 SmallVector<Expr *, 8> SrcExprs;
11290 SmallVector<Expr *, 8> DstExprs;
11291 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011292 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011293 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11294 SourceLocation ELoc;
11295 SourceRange ERange;
11296 Expr *SimpleRefExpr = RefExpr;
11297 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11298 /*AllowArraySection=*/false);
11299 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011300 // It will be analyzed later.
11301 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011302 SrcExprs.push_back(nullptr);
11303 DstExprs.push_back(nullptr);
11304 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011305 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011306 ValueDecl *D = Res.first;
11307 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011308 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011309
Alexey Bataeve122da12016-03-17 10:50:17 +000011310 QualType Type = D->getType();
11311 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011312
11313 // OpenMP [2.14.4.2, Restrictions, p.2]
11314 // A list item that appears in a copyprivate clause may not appear in a
11315 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011316 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11317 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011318 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11319 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011320 Diag(ELoc, diag::err_omp_wrong_dsa)
11321 << getOpenMPClauseName(DVar.CKind)
11322 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011323 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011324 continue;
11325 }
11326
11327 // OpenMP [2.11.4.2, Restrictions, p.1]
11328 // All list items that appear in a copyprivate clause must be either
11329 // threadprivate or private in the enclosing context.
11330 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011331 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011332 if (DVar.CKind == OMPC_shared) {
11333 Diag(ELoc, diag::err_omp_required_access)
11334 << getOpenMPClauseName(OMPC_copyprivate)
11335 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011336 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011337 continue;
11338 }
11339 }
11340 }
11341
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011342 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011343 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011344 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011345 << getOpenMPClauseName(OMPC_copyprivate) << Type
11346 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011347 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011348 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011349 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011350 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011351 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011352 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011353 continue;
11354 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011355
Alexey Bataevbae9a792014-06-27 10:37:06 +000011356 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11357 // A variable of class type (or array thereof) that appears in a
11358 // copyin clause requires an accessible, unambiguous copy assignment
11359 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011360 Type = Context.getBaseElementType(Type.getNonReferenceType())
11361 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011362 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011363 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11364 D->hasAttrs() ? &D->getAttrs() : nullptr);
11365 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011366 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011367 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11368 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011369 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011370 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011371 PseudoDstExpr, PseudoSrcExpr);
11372 if (AssignmentOp.isInvalid())
11373 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011374 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011375 /*DiscardedValue=*/true);
11376 if (AssignmentOp.isInvalid())
11377 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011378
11379 // No need to mark vars as copyprivate, they are already threadprivate or
11380 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011381 assert(VD || IsOpenMPCapturedDecl(D));
11382 Vars.push_back(
11383 VD ? RefExpr->IgnoreParens()
11384 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011385 SrcExprs.push_back(PseudoSrcExpr);
11386 DstExprs.push_back(PseudoDstExpr);
11387 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011388 }
11389
11390 if (Vars.empty())
11391 return nullptr;
11392
Alexey Bataeva63048e2015-03-23 06:18:07 +000011393 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11394 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011395}
11396
Alexey Bataev6125da92014-07-21 11:26:11 +000011397OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11398 SourceLocation StartLoc,
11399 SourceLocation LParenLoc,
11400 SourceLocation EndLoc) {
11401 if (VarList.empty())
11402 return nullptr;
11403
11404 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11405}
Alexey Bataevdea47612014-07-23 07:46:59 +000011406
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011407OMPClause *
11408Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11409 SourceLocation DepLoc, SourceLocation ColonLoc,
11410 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11411 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011412 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011413 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011414 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011415 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011416 return nullptr;
11417 }
11418 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011419 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11420 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011421 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011422 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011423 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11424 /*Last=*/OMPC_DEPEND_unknown, Except)
11425 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011426 return nullptr;
11427 }
11428 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011429 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011430 llvm::APSInt DepCounter(/*BitWidth=*/32);
11431 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11432 if (DepKind == OMPC_DEPEND_sink) {
11433 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11434 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11435 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011436 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011437 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011438 for (auto &RefExpr : VarList) {
11439 assert(RefExpr && "NULL expr in OpenMP shared clause.");
11440 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11441 // It will be analyzed later.
11442 Vars.push_back(RefExpr);
11443 continue;
11444 }
11445
11446 SourceLocation ELoc = RefExpr->getExprLoc();
11447 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11448 if (DepKind == OMPC_DEPEND_sink) {
11449 if (DSAStack->getParentOrderedRegionParam() &&
11450 DepCounter >= TotalDepCount) {
11451 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11452 continue;
11453 }
11454 ++DepCounter;
11455 // OpenMP [2.13.9, Summary]
11456 // depend(dependence-type : vec), where dependence-type is:
11457 // 'sink' and where vec is the iteration vector, which has the form:
11458 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11459 // where n is the value specified by the ordered clause in the loop
11460 // directive, xi denotes the loop iteration variable of the i-th nested
11461 // loop associated with the loop directive, and di is a constant
11462 // non-negative integer.
11463 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011464 // It will be analyzed later.
11465 Vars.push_back(RefExpr);
11466 continue;
11467 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011468 SimpleExpr = SimpleExpr->IgnoreImplicit();
11469 OverloadedOperatorKind OOK = OO_None;
11470 SourceLocation OOLoc;
11471 Expr *LHS = SimpleExpr;
11472 Expr *RHS = nullptr;
11473 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11474 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11475 OOLoc = BO->getOperatorLoc();
11476 LHS = BO->getLHS()->IgnoreParenImpCasts();
11477 RHS = BO->getRHS()->IgnoreParenImpCasts();
11478 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11479 OOK = OCE->getOperator();
11480 OOLoc = OCE->getOperatorLoc();
11481 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11482 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11483 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11484 OOK = MCE->getMethodDecl()
11485 ->getNameInfo()
11486 .getName()
11487 .getCXXOverloadedOperator();
11488 OOLoc = MCE->getCallee()->getExprLoc();
11489 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11490 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011491 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011492 SourceLocation ELoc;
11493 SourceRange ERange;
11494 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11495 /*AllowArraySection=*/false);
11496 if (Res.second) {
11497 // It will be analyzed later.
11498 Vars.push_back(RefExpr);
11499 }
11500 ValueDecl *D = Res.first;
11501 if (!D)
11502 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011503
Alexey Bataev17daedf2018-02-15 22:42:57 +000011504 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11505 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11506 continue;
11507 }
11508 if (RHS) {
11509 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11510 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11511 if (RHSRes.isInvalid())
11512 continue;
11513 }
11514 if (!CurContext->isDependentContext() &&
11515 DSAStack->getParentOrderedRegionParam() &&
11516 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11517 ValueDecl *VD =
11518 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
11519 if (VD) {
11520 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11521 << 1 << VD;
11522 } else {
11523 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11524 }
11525 continue;
11526 }
11527 OpsOffs.push_back({RHS, OOK});
11528 } else {
11529 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11530 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11531 (ASE &&
11532 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
11533 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11534 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11535 << RefExpr->getSourceRange();
11536 continue;
11537 }
11538 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11539 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11540 ExprResult Res =
11541 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
11542 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11543 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11544 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11545 << RefExpr->getSourceRange();
11546 continue;
11547 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011548 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011549 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011550 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011551
11552 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11553 TotalDepCount > VarList.size() &&
11554 DSAStack->getParentOrderedRegionParam() &&
11555 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11556 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
11557 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11558 }
11559 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11560 Vars.empty())
11561 return nullptr;
11562
Alexey Bataev8b427062016-05-25 12:36:08 +000011563 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11564 DepKind, DepLoc, ColonLoc, Vars);
Alexey Bataev17daedf2018-02-15 22:42:57 +000011565 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
11566 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000011567 DSAStack->addDoacrossDependClause(C, OpsOffs);
11568 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011569}
Michael Wonge710d542015-08-07 16:16:36 +000011570
11571OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11572 SourceLocation LParenLoc,
11573 SourceLocation EndLoc) {
11574 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011575 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011576
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011577 // OpenMP [2.9.1, Restrictions]
11578 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011579 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11580 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011581 return nullptr;
11582
Alexey Bataev931e19b2017-10-02 16:32:39 +000011583 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011584 OpenMPDirectiveKind CaptureRegion =
11585 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11586 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011587 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev931e19b2017-10-02 16:32:39 +000011588 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11589 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11590 HelperValStmt = buildPreInits(Context, Captures);
11591 }
11592
Alexey Bataev8451efa2018-01-15 19:06:12 +000011593 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11594 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011595}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011596
Kelvin Li0bff7af2015-11-23 05:32:03 +000011597static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000011598 DSAStackTy *Stack, QualType QTy,
11599 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000011600 NamedDecl *ND;
11601 if (QTy->isIncompleteType(&ND)) {
11602 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11603 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011604 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000011605 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
11606 !QTy.isTrivialType(SemaRef.Context))
11607 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011608 return true;
11609}
11610
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011611/// \brief Return true if it can be proven that the provided array expression
11612/// (array section or array subscript) does NOT specify the whole size of the
11613/// array whose base type is \a BaseQTy.
11614static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11615 const Expr *E,
11616 QualType BaseQTy) {
11617 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11618
11619 // If this is an array subscript, it refers to the whole size if the size of
11620 // the dimension is constant and equals 1. Also, an array section assumes the
11621 // format of an array subscript if no colon is used.
11622 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11623 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11624 return ATy->getSize().getSExtValue() != 1;
11625 // Size can't be evaluated statically.
11626 return false;
11627 }
11628
11629 assert(OASE && "Expecting array section if not an array subscript.");
11630 auto *LowerBound = OASE->getLowerBound();
11631 auto *Length = OASE->getLength();
11632
11633 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011634 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011635 if (LowerBound) {
11636 llvm::APSInt ConstLowerBound;
11637 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11638 return false; // Can't get the integer value as a constant.
11639 if (ConstLowerBound.getSExtValue())
11640 return true;
11641 }
11642
11643 // If we don't have a length we covering the whole dimension.
11644 if (!Length)
11645 return false;
11646
11647 // If the base is a pointer, we don't have a way to get the size of the
11648 // pointee.
11649 if (BaseQTy->isPointerType())
11650 return false;
11651
11652 // We can only check if the length is the same as the size of the dimension
11653 // if we have a constant array.
11654 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11655 if (!CATy)
11656 return false;
11657
11658 llvm::APSInt ConstLength;
11659 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11660 return false; // Can't get the integer value as a constant.
11661
11662 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11663}
11664
11665// Return true if it can be proven that the provided array expression (array
11666// section or array subscript) does NOT specify a single element of the array
11667// whose base type is \a BaseQTy.
11668static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011669 const Expr *E,
11670 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011671 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11672
11673 // An array subscript always refer to a single element. Also, an array section
11674 // assumes the format of an array subscript if no colon is used.
11675 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11676 return false;
11677
11678 assert(OASE && "Expecting array section if not an array subscript.");
11679 auto *Length = OASE->getLength();
11680
11681 // If we don't have a length we have to check if the array has unitary size
11682 // for this dimension. Also, we should always expect a length if the base type
11683 // is pointer.
11684 if (!Length) {
11685 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11686 return ATy->getSize().getSExtValue() != 1;
11687 // We cannot assume anything.
11688 return false;
11689 }
11690
11691 // Check if the length evaluates to 1.
11692 llvm::APSInt ConstLength;
11693 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11694 return false; // Can't get the integer value as a constant.
11695
11696 return ConstLength.getSExtValue() != 1;
11697}
11698
Samuel Antao661c0902016-05-26 17:39:58 +000011699// Return the expression of the base of the mappable expression or null if it
11700// cannot be determined and do all the necessary checks to see if the expression
11701// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011702// components of the expression.
11703static Expr *CheckMapClauseExpressionBase(
11704 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011705 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011706 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011707 SourceLocation ELoc = E->getExprLoc();
11708 SourceRange ERange = E->getSourceRange();
11709
11710 // The base of elements of list in a map clause have to be either:
11711 // - a reference to variable or field.
11712 // - a member expression.
11713 // - an array expression.
11714 //
11715 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11716 // reference to 'r'.
11717 //
11718 // If we have:
11719 //
11720 // struct SS {
11721 // Bla S;
11722 // foo() {
11723 // #pragma omp target map (S.Arr[:12]);
11724 // }
11725 // }
11726 //
11727 // We want to retrieve the member expression 'this->S';
11728
11729 Expr *RelevantExpr = nullptr;
11730
Samuel Antao5de996e2016-01-22 20:21:36 +000011731 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11732 // If a list item is an array section, it must specify contiguous storage.
11733 //
11734 // For this restriction it is sufficient that we make sure only references
11735 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011736 // exist except in the rightmost expression (unless they cover the whole
11737 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011738 //
11739 // r.ArrS[3:5].Arr[6:7]
11740 //
11741 // r.ArrS[3:5].x
11742 //
11743 // but these would be valid:
11744 // r.ArrS[3].Arr[6:7]
11745 //
11746 // r.ArrS[3].x
11747
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011748 bool AllowUnitySizeArraySection = true;
11749 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011750
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011751 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011752 E = E->IgnoreParenImpCasts();
11753
11754 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11755 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011756 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011757
11758 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011759
11760 // If we got a reference to a declaration, we should not expect any array
11761 // section before that.
11762 AllowUnitySizeArraySection = false;
11763 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011764
11765 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011766 CurComponents.emplace_back(CurE, CurE->getDecl());
11767 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011768 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11769
11770 if (isa<CXXThisExpr>(BaseE))
11771 // We found a base expression: this->Val.
11772 RelevantExpr = CurE;
11773 else
11774 E = BaseE;
11775
11776 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011777 if (!NoDiagnose) {
11778 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11779 << CurE->getSourceRange();
11780 return nullptr;
11781 }
11782 if (RelevantExpr)
11783 return nullptr;
11784 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011785 }
11786
11787 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11788
11789 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11790 // A bit-field cannot appear in a map clause.
11791 //
11792 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011793 if (!NoDiagnose) {
11794 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11795 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11796 return nullptr;
11797 }
11798 if (RelevantExpr)
11799 return nullptr;
11800 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011801 }
11802
11803 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11804 // If the type of a list item is a reference to a type T then the type
11805 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011806 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011807
11808 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11809 // A list item cannot be a variable that is a member of a structure with
11810 // a union type.
11811 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011812 if (auto *RT = CurType->getAs<RecordType>()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011813 if (RT->isUnionType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011814 if (!NoDiagnose) {
11815 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11816 << CurE->getSourceRange();
11817 return nullptr;
11818 }
11819 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011820 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011821 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011822
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011823 // If we got a member expression, we should not expect any array section
11824 // before that:
11825 //
11826 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11827 // If a list item is an element of a structure, only the rightmost symbol
11828 // of the variable reference can be an array section.
11829 //
11830 AllowUnitySizeArraySection = false;
11831 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011832
11833 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011834 CurComponents.emplace_back(CurE, FD);
11835 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011836 E = CurE->getBase()->IgnoreParenImpCasts();
11837
11838 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011839 if (!NoDiagnose) {
11840 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11841 << 0 << CurE->getSourceRange();
11842 return nullptr;
11843 }
11844 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011845 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011846
11847 // If we got an array subscript that express the whole dimension we
11848 // can have any array expressions before. If it only expressing part of
11849 // the dimension, we can only have unitary-size array expressions.
11850 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11851 E->getType()))
11852 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011853
11854 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011855 CurComponents.emplace_back(CurE, nullptr);
11856 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011857 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011858 E = CurE->getBase()->IgnoreParenImpCasts();
11859
Alexey Bataev27041fa2017-12-05 15:22:49 +000011860 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011861 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11862
Samuel Antao5de996e2016-01-22 20:21:36 +000011863 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11864 // If the type of a list item is a reference to a type T then the type
11865 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011866 if (CurType->isReferenceType())
11867 CurType = CurType->getPointeeType();
11868
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011869 bool IsPointer = CurType->isAnyPointerType();
11870
11871 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011872 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11873 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011874 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011875 }
11876
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011877 bool NotWhole =
11878 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11879 bool NotUnity =
11880 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11881
Samuel Antaodab51bb2016-07-18 23:22:11 +000011882 if (AllowWholeSizeArraySection) {
11883 // Any array section is currently allowed. Allowing a whole size array
11884 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011885 //
11886 // If this array section refers to the whole dimension we can still
11887 // accept other array sections before this one, except if the base is a
11888 // pointer. Otherwise, only unitary sections are accepted.
11889 if (NotWhole || IsPointer)
11890 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011891 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011892 // A unity or whole array section is not allowed and that is not
11893 // compatible with the properties of the current array section.
11894 SemaRef.Diag(
11895 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11896 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011897 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011898 }
Samuel Antao90927002016-04-26 14:54:23 +000011899
11900 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011901 CurComponents.emplace_back(CurE, nullptr);
11902 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011903 if (!NoDiagnose) {
11904 // If nothing else worked, this is not a valid map clause expression.
11905 SemaRef.Diag(
11906 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11907 << ERange;
11908 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011909 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011910 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011911 }
11912
11913 return RelevantExpr;
11914}
11915
11916// Return true if expression E associated with value VD has conflicts with other
11917// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011918static bool CheckMapConflicts(
11919 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11920 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011921 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11922 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011923 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011924 SourceLocation ELoc = E->getExprLoc();
11925 SourceRange ERange = E->getSourceRange();
11926
11927 // In order to easily check the conflicts we need to match each component of
11928 // the expression under test with the components of the expressions that are
11929 // already in the stack.
11930
Samuel Antao5de996e2016-01-22 20:21:36 +000011931 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011932 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011933 "Map clause expression with unexpected base!");
11934
11935 // Variables to help detecting enclosing problems in data environment nests.
11936 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011937 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011938
Samuel Antao90927002016-04-26 14:54:23 +000011939 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11940 VD, CurrentRegionOnly,
11941 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011942 StackComponents,
11943 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011944
Samuel Antao5de996e2016-01-22 20:21:36 +000011945 assert(!StackComponents.empty() &&
11946 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011947 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011948 "Map clause expression with unexpected base!");
11949
Samuel Antao90927002016-04-26 14:54:23 +000011950 // The whole expression in the stack.
11951 auto *RE = StackComponents.front().getAssociatedExpression();
11952
Samuel Antao5de996e2016-01-22 20:21:36 +000011953 // Expressions must start from the same base. Here we detect at which
11954 // point both expressions diverge from each other and see if we can
11955 // detect if the memory referred to both expressions is contiguous and
11956 // do not overlap.
11957 auto CI = CurComponents.rbegin();
11958 auto CE = CurComponents.rend();
11959 auto SI = StackComponents.rbegin();
11960 auto SE = StackComponents.rend();
11961 for (; CI != CE && SI != SE; ++CI, ++SI) {
11962
11963 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11964 // At most one list item can be an array item derived from a given
11965 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011966 if (CurrentRegionOnly &&
11967 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11968 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11969 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11970 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11971 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011972 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011973 << CI->getAssociatedExpression()->getSourceRange();
11974 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11975 diag::note_used_here)
11976 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011977 return true;
11978 }
11979
11980 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011981 if (CI->getAssociatedExpression()->getStmtClass() !=
11982 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011983 break;
11984
11985 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011986 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011987 break;
11988 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011989 // Check if the extra components of the expressions in the enclosing
11990 // data environment are redundant for the current base declaration.
11991 // If they are, the maps completely overlap, which is legal.
11992 for (; SI != SE; ++SI) {
11993 QualType Type;
11994 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011995 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011996 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011997 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11998 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011999 auto *E = OASE->getBase()->IgnoreParenImpCasts();
12000 Type =
12001 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12002 }
12003 if (Type.isNull() || Type->isAnyPointerType() ||
12004 CheckArrayExpressionDoesNotReferToWholeSize(
12005 SemaRef, SI->getAssociatedExpression(), Type))
12006 break;
12007 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012008
12009 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12010 // List items of map clauses in the same construct must not share
12011 // original storage.
12012 //
12013 // If the expressions are exactly the same or one is a subset of the
12014 // other, it means they are sharing storage.
12015 if (CI == CE && SI == SE) {
12016 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000012017 if (CKind == OMPC_map)
12018 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12019 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012020 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012021 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12022 << ERange;
12023 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012024 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12025 << RE->getSourceRange();
12026 return true;
12027 } else {
12028 // If we find the same expression in the enclosing data environment,
12029 // that is legal.
12030 IsEnclosedByDataEnvironmentExpr = true;
12031 return false;
12032 }
12033 }
12034
Samuel Antao90927002016-04-26 14:54:23 +000012035 QualType DerivedType =
12036 std::prev(CI)->getAssociatedDeclaration()->getType();
12037 SourceLocation DerivedLoc =
12038 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012039
12040 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12041 // If the type of a list item is a reference to a type T then the type
12042 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012043 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012044
12045 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12046 // A variable for which the type is pointer and an array section
12047 // derived from that variable must not appear as list items of map
12048 // clauses of the same construct.
12049 //
12050 // Also, cover one of the cases in:
12051 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12052 // If any part of the original storage of a list item has corresponding
12053 // storage in the device data environment, all of the original storage
12054 // must have corresponding storage in the device data environment.
12055 //
12056 if (DerivedType->isAnyPointerType()) {
12057 if (CI == CE || SI == SE) {
12058 SemaRef.Diag(
12059 DerivedLoc,
12060 diag::err_omp_pointer_mapped_along_with_derived_section)
12061 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012062 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12063 << RE->getSourceRange();
12064 return true;
12065 } else if (CI->getAssociatedExpression()->getStmtClass() !=
12066 SI->getAssociatedExpression()->getStmtClass() ||
12067 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12068 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012069 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012070 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012071 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012072 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12073 << RE->getSourceRange();
12074 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012075 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012076 }
12077
12078 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12079 // List items of map clauses in the same construct must not share
12080 // original storage.
12081 //
12082 // An expression is a subset of the other.
12083 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000012084 if (CKind == OMPC_map)
12085 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12086 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012087 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012088 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12089 << ERange;
12090 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012091 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12092 << RE->getSourceRange();
12093 return true;
12094 }
12095
12096 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012097 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012098 if (!CurrentRegionOnly && SI != SE)
12099 EnclosingExpr = RE;
12100
12101 // The current expression is a subset of the expression in the data
12102 // environment.
12103 IsEnclosedByDataEnvironmentExpr |=
12104 (!CurrentRegionOnly && CI != CE && SI == SE);
12105
12106 return false;
12107 });
12108
12109 if (CurrentRegionOnly)
12110 return FoundError;
12111
12112 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12113 // If any part of the original storage of a list item has corresponding
12114 // storage in the device data environment, all of the original storage must
12115 // have corresponding storage in the device data environment.
12116 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12117 // If a list item is an element of a structure, and a different element of
12118 // the structure has a corresponding list item in the device data environment
12119 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012120 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012121 // data environment prior to the task encountering the construct.
12122 //
12123 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12124 SemaRef.Diag(ELoc,
12125 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12126 << ERange;
12127 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12128 << EnclosingExpr->getSourceRange();
12129 return true;
12130 }
12131
12132 return FoundError;
12133}
12134
Samuel Antao661c0902016-05-26 17:39:58 +000012135namespace {
12136// Utility struct that gathers all the related lists associated with a mappable
12137// expression.
12138struct MappableVarListInfo final {
12139 // The list of expressions.
12140 ArrayRef<Expr *> VarList;
12141 // The list of processed expressions.
12142 SmallVector<Expr *, 16> ProcessedVarList;
12143 // The mappble components for each expression.
12144 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12145 // The base declaration of the variable.
12146 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12147
12148 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12149 // We have a list of components and base declarations for each entry in the
12150 // variable list.
12151 VarComponents.reserve(VarList.size());
12152 VarBaseDeclarations.reserve(VarList.size());
12153 }
12154};
12155}
12156
12157// Check the validity of the provided variable list for the provided clause kind
12158// \a CKind. In the check process the valid expressions, and mappable expression
12159// components and variables are extracted and used to fill \a Vars,
12160// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12161// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12162static void
12163checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12164 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12165 SourceLocation StartLoc,
12166 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12167 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012168 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12169 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012170 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012171
Samuel Antao90927002016-04-26 14:54:23 +000012172 // Keep track of the mappable components and base declarations in this clause.
12173 // Each entry in the list is going to have a list of components associated. We
12174 // record each set of the components so that we can build the clause later on.
12175 // In the end we should have the same amount of declarations and component
12176 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012177
Samuel Antao661c0902016-05-26 17:39:58 +000012178 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012179 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012180 SourceLocation ELoc = RE->getExprLoc();
12181
Kelvin Li0bff7af2015-11-23 05:32:03 +000012182 auto *VE = RE->IgnoreParenLValueCasts();
12183
12184 if (VE->isValueDependent() || VE->isTypeDependent() ||
12185 VE->isInstantiationDependent() ||
12186 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012187 // We can only analyze this information once the missing information is
12188 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012189 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012190 continue;
12191 }
12192
12193 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012194
Samuel Antao5de996e2016-01-22 20:21:36 +000012195 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012196 SemaRef.Diag(ELoc,
12197 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012198 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012199 continue;
12200 }
12201
Samuel Antao90927002016-04-26 14:54:23 +000012202 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12203 ValueDecl *CurDeclaration = nullptr;
12204
12205 // Obtain the array or member expression bases if required. Also, fill the
12206 // components array with all the components identified in the process.
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012207 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12208 CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012209 if (!BE)
12210 continue;
12211
Samuel Antao90927002016-04-26 14:54:23 +000012212 assert(!CurComponents.empty() &&
12213 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012214
Samuel Antao90927002016-04-26 14:54:23 +000012215 // For the following checks, we rely on the base declaration which is
12216 // expected to be associated with the last component. The declaration is
12217 // expected to be a variable or a field (if 'this' is being mapped).
12218 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12219 assert(CurDeclaration && "Null decl on map clause.");
12220 assert(
12221 CurDeclaration->isCanonicalDecl() &&
12222 "Expecting components to have associated only canonical declarations.");
12223
12224 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12225 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012226
12227 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012228 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012229
12230 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012231 // threadprivate variables cannot appear in a map clause.
12232 // OpenMP 4.5 [2.10.5, target update Construct]
12233 // threadprivate variables cannot appear in a from clause.
12234 if (VD && DSAS->isThreadPrivate(VD)) {
12235 auto DVar = DSAS->getTopDSA(VD, false);
12236 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12237 << getOpenMPClauseName(CKind);
12238 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012239 continue;
12240 }
12241
Samuel Antao5de996e2016-01-22 20:21:36 +000012242 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12243 // A list item cannot appear in both a map clause and a data-sharing
12244 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000012245
Samuel Antao5de996e2016-01-22 20:21:36 +000012246 // Check conflicts with other map clause expressions. We check the conflicts
12247 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000012248 // environment, because the restrictions are different. We only have to
12249 // check conflicts across regions for the map clauses.
12250 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12251 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012252 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012253 if (CKind == OMPC_map &&
12254 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12255 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012256 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012257
Samuel Antao661c0902016-05-26 17:39:58 +000012258 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000012259 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12260 // If the type of a list item is a reference to a type T then the type will
12261 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012262 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012263
Samuel Antao661c0902016-05-26 17:39:58 +000012264 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12265 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000012266 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000012267 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000012268 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12269 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000012270 continue;
12271
Samuel Antao661c0902016-05-26 17:39:58 +000012272 if (CKind == OMPC_map) {
12273 // target enter data
12274 // OpenMP [2.10.2, Restrictions, p. 99]
12275 // A map-type must be specified in all map clauses and must be either
12276 // to or alloc.
12277 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12278 if (DKind == OMPD_target_enter_data &&
12279 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12280 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12281 << (IsMapTypeImplicit ? 1 : 0)
12282 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12283 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012284 continue;
12285 }
Samuel Antao661c0902016-05-26 17:39:58 +000012286
12287 // target exit_data
12288 // OpenMP [2.10.3, Restrictions, p. 102]
12289 // A map-type must be specified in all map clauses and must be either
12290 // from, release, or delete.
12291 if (DKind == OMPD_target_exit_data &&
12292 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12293 MapType == OMPC_MAP_delete)) {
12294 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12295 << (IsMapTypeImplicit ? 1 : 0)
12296 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12297 << getOpenMPDirectiveName(DKind);
12298 continue;
12299 }
12300
12301 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12302 // A list item cannot appear in both a map clause and a data-sharing
12303 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000012304 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000012305 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000012306 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000012307 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12308 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000012309 auto DVar = DSAS->getTopDSA(VD, false);
12310 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012311 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012312 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012313 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012314 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12315 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12316 continue;
12317 }
12318 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012319 }
12320
Samuel Antao90927002016-04-26 14:54:23 +000012321 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012322 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012323
12324 // Store the components in the stack so that they can be used to check
12325 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012326 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12327 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012328
12329 // Save the components and declaration to create the clause. For purposes of
12330 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012331 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012332 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12333 MVLI.VarComponents.back().append(CurComponents.begin(),
12334 CurComponents.end());
12335 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12336 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012337 }
Samuel Antao661c0902016-05-26 17:39:58 +000012338}
12339
12340OMPClause *
12341Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12342 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12343 SourceLocation MapLoc, SourceLocation ColonLoc,
12344 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12345 SourceLocation LParenLoc, SourceLocation EndLoc) {
12346 MappableVarListInfo MVLI(VarList);
12347 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12348 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012349
Samuel Antao5de996e2016-01-22 20:21:36 +000012350 // We need to produce a map clause even if we don't have variables so that
12351 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012352 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12353 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12354 MVLI.VarComponents, MapTypeModifier, MapType,
12355 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012356}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012357
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012358QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12359 TypeResult ParsedType) {
12360 assert(ParsedType.isUsable());
12361
12362 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12363 if (ReductionType.isNull())
12364 return QualType();
12365
12366 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12367 // A type name in a declare reduction directive cannot be a function type, an
12368 // array type, a reference type, or a type qualified with const, volatile or
12369 // restrict.
12370 if (ReductionType.hasQualifiers()) {
12371 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12372 return QualType();
12373 }
12374
12375 if (ReductionType->isFunctionType()) {
12376 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12377 return QualType();
12378 }
12379 if (ReductionType->isReferenceType()) {
12380 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12381 return QualType();
12382 }
12383 if (ReductionType->isArrayType()) {
12384 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12385 return QualType();
12386 }
12387 return ReductionType;
12388}
12389
12390Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12391 Scope *S, DeclContext *DC, DeclarationName Name,
12392 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12393 AccessSpecifier AS, Decl *PrevDeclInScope) {
12394 SmallVector<Decl *, 8> Decls;
12395 Decls.reserve(ReductionTypes.size());
12396
12397 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012398 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012399 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12400 // A reduction-identifier may not be re-declared in the current scope for the
12401 // same type or for a type that is compatible according to the base language
12402 // rules.
12403 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12404 OMPDeclareReductionDecl *PrevDRD = nullptr;
12405 bool InCompoundScope = true;
12406 if (S != nullptr) {
12407 // Find previous declaration with the same name not referenced in other
12408 // declarations.
12409 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12410 InCompoundScope =
12411 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12412 LookupName(Lookup, S);
12413 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12414 /*AllowInlineNamespace=*/false);
12415 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12416 auto Filter = Lookup.makeFilter();
12417 while (Filter.hasNext()) {
12418 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12419 if (InCompoundScope) {
12420 auto I = UsedAsPrevious.find(PrevDecl);
12421 if (I == UsedAsPrevious.end())
12422 UsedAsPrevious[PrevDecl] = false;
12423 if (auto *D = PrevDecl->getPrevDeclInScope())
12424 UsedAsPrevious[D] = true;
12425 }
12426 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12427 PrevDecl->getLocation();
12428 }
12429 Filter.done();
12430 if (InCompoundScope) {
12431 for (auto &PrevData : UsedAsPrevious) {
12432 if (!PrevData.second) {
12433 PrevDRD = PrevData.first;
12434 break;
12435 }
12436 }
12437 }
12438 } else if (PrevDeclInScope != nullptr) {
12439 auto *PrevDRDInScope = PrevDRD =
12440 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12441 do {
12442 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12443 PrevDRDInScope->getLocation();
12444 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12445 } while (PrevDRDInScope != nullptr);
12446 }
12447 for (auto &TyData : ReductionTypes) {
12448 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12449 bool Invalid = false;
12450 if (I != PreviousRedeclTypes.end()) {
12451 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12452 << TyData.first;
12453 Diag(I->second, diag::note_previous_definition);
12454 Invalid = true;
12455 }
12456 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12457 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12458 Name, TyData.first, PrevDRD);
12459 DC->addDecl(DRD);
12460 DRD->setAccess(AS);
12461 Decls.push_back(DRD);
12462 if (Invalid)
12463 DRD->setInvalidDecl();
12464 else
12465 PrevDRD = DRD;
12466 }
12467
12468 return DeclGroupPtrTy::make(
12469 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12470}
12471
12472void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12473 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12474
12475 // Enter new function scope.
12476 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012477 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012478 getCurFunction()->setHasOMPDeclareReductionCombiner();
12479
12480 if (S != nullptr)
12481 PushDeclContext(S, DRD);
12482 else
12483 CurContext = DRD;
12484
Faisal Valid143a0c2017-04-01 21:30:49 +000012485 PushExpressionEvaluationContext(
12486 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012487
12488 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012489 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12490 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12491 // uses semantics of argument handles by value, but it should be passed by
12492 // reference. C lang does not support references, so pass all parameters as
12493 // pointers.
12494 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012495 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012496 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012497 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12498 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12499 // uses semantics of argument handles by value, but it should be passed by
12500 // reference. C lang does not support references, so pass all parameters as
12501 // pointers.
12502 // Create 'T omp_out;' variable.
12503 auto *OmpOutParm =
12504 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12505 if (S != nullptr) {
12506 PushOnScopeChains(OmpInParm, S);
12507 PushOnScopeChains(OmpOutParm, S);
12508 } else {
12509 DRD->addDecl(OmpInParm);
12510 DRD->addDecl(OmpOutParm);
12511 }
12512}
12513
12514void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12515 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12516 DiscardCleanupsInEvaluationContext();
12517 PopExpressionEvaluationContext();
12518
12519 PopDeclContext();
12520 PopFunctionScopeInfo();
12521
12522 if (Combiner != nullptr)
12523 DRD->setCombiner(Combiner);
12524 else
12525 DRD->setInvalidDecl();
12526}
12527
Alexey Bataev070f43a2017-09-06 14:49:58 +000012528VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012529 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12530
12531 // Enter new function scope.
12532 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012533 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012534
12535 if (S != nullptr)
12536 PushDeclContext(S, DRD);
12537 else
12538 CurContext = DRD;
12539
Faisal Valid143a0c2017-04-01 21:30:49 +000012540 PushExpressionEvaluationContext(
12541 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012542
12543 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012544 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12545 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12546 // uses semantics of argument handles by value, but it should be passed by
12547 // reference. C lang does not support references, so pass all parameters as
12548 // pointers.
12549 // Create 'T omp_priv;' variable.
12550 auto *OmpPrivParm =
12551 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012552 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12553 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12554 // uses semantics of argument handles by value, but it should be passed by
12555 // reference. C lang does not support references, so pass all parameters as
12556 // pointers.
12557 // Create 'T omp_orig;' variable.
12558 auto *OmpOrigParm =
12559 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012560 if (S != nullptr) {
12561 PushOnScopeChains(OmpPrivParm, S);
12562 PushOnScopeChains(OmpOrigParm, S);
12563 } else {
12564 DRD->addDecl(OmpPrivParm);
12565 DRD->addDecl(OmpOrigParm);
12566 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012567 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012568}
12569
Alexey Bataev070f43a2017-09-06 14:49:58 +000012570void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12571 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012572 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12573 DiscardCleanupsInEvaluationContext();
12574 PopExpressionEvaluationContext();
12575
12576 PopDeclContext();
12577 PopFunctionScopeInfo();
12578
Alexey Bataev070f43a2017-09-06 14:49:58 +000012579 if (Initializer != nullptr) {
12580 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12581 } else if (OmpPrivParm->hasInit()) {
12582 DRD->setInitializer(OmpPrivParm->getInit(),
12583 OmpPrivParm->isDirectInit()
12584 ? OMPDeclareReductionDecl::DirectInit
12585 : OMPDeclareReductionDecl::CopyInit);
12586 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012587 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012588 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012589}
12590
12591Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12592 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12593 for (auto *D : DeclReductions.get()) {
12594 if (IsValid) {
12595 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12596 if (S != nullptr)
12597 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12598 } else
12599 D->setInvalidDecl();
12600 }
12601 return DeclReductions;
12602}
12603
David Majnemer9d168222016-08-05 17:44:54 +000012604OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012605 SourceLocation StartLoc,
12606 SourceLocation LParenLoc,
12607 SourceLocation EndLoc) {
12608 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012609 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012610
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012611 // OpenMP [teams Constrcut, Restrictions]
12612 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012613 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12614 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012615 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012616
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012617 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012618 OpenMPDirectiveKind CaptureRegion =
12619 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12620 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012621 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012622 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12623 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12624 HelperValStmt = buildPreInits(Context, Captures);
12625 }
12626
12627 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12628 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012629}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012630
12631OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12632 SourceLocation StartLoc,
12633 SourceLocation LParenLoc,
12634 SourceLocation EndLoc) {
12635 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012636 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012637
12638 // OpenMP [teams Constrcut, Restrictions]
12639 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012640 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12641 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012642 return nullptr;
12643
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012644 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012645 OpenMPDirectiveKind CaptureRegion =
12646 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12647 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012648 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012649 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12650 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12651 HelperValStmt = buildPreInits(Context, Captures);
12652 }
12653
12654 return new (Context) OMPThreadLimitClause(
12655 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012656}
Alexey Bataeva0569352015-12-01 10:17:31 +000012657
12658OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12659 SourceLocation StartLoc,
12660 SourceLocation LParenLoc,
12661 SourceLocation EndLoc) {
12662 Expr *ValExpr = Priority;
12663
12664 // OpenMP [2.9.1, task Constrcut]
12665 // The priority-value is a non-negative numerical scalar expression.
12666 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12667 /*StrictlyPositive=*/false))
12668 return nullptr;
12669
12670 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12671}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012672
12673OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12674 SourceLocation StartLoc,
12675 SourceLocation LParenLoc,
12676 SourceLocation EndLoc) {
12677 Expr *ValExpr = Grainsize;
12678
12679 // OpenMP [2.9.2, taskloop Constrcut]
12680 // The parameter of the grainsize clause must be a positive integer
12681 // expression.
12682 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12683 /*StrictlyPositive=*/true))
12684 return nullptr;
12685
12686 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12687}
Alexey Bataev382967a2015-12-08 12:06:20 +000012688
12689OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12690 SourceLocation StartLoc,
12691 SourceLocation LParenLoc,
12692 SourceLocation EndLoc) {
12693 Expr *ValExpr = NumTasks;
12694
12695 // OpenMP [2.9.2, taskloop Constrcut]
12696 // The parameter of the num_tasks clause must be a positive integer
12697 // expression.
12698 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12699 /*StrictlyPositive=*/true))
12700 return nullptr;
12701
12702 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12703}
12704
Alexey Bataev28c75412015-12-15 08:19:24 +000012705OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12706 SourceLocation LParenLoc,
12707 SourceLocation EndLoc) {
12708 // OpenMP [2.13.2, critical construct, Description]
12709 // ... where hint-expression is an integer constant expression that evaluates
12710 // to a valid lock hint.
12711 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12712 if (HintExpr.isInvalid())
12713 return nullptr;
12714 return new (Context)
12715 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12716}
12717
Carlo Bertollib4adf552016-01-15 18:50:31 +000012718OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12719 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12720 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12721 SourceLocation EndLoc) {
12722 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12723 std::string Values;
12724 Values += "'";
12725 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12726 Values += "'";
12727 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12728 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12729 return nullptr;
12730 }
12731 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012732 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012733 if (ChunkSize) {
12734 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12735 !ChunkSize->isInstantiationDependent() &&
12736 !ChunkSize->containsUnexpandedParameterPack()) {
12737 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12738 ExprResult Val =
12739 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12740 if (Val.isInvalid())
12741 return nullptr;
12742
12743 ValExpr = Val.get();
12744
12745 // OpenMP [2.7.1, Restrictions]
12746 // chunk_size must be a loop invariant integer expression with a positive
12747 // value.
12748 llvm::APSInt Result;
12749 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12750 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12751 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12752 << "dist_schedule" << ChunkSize->getSourceRange();
12753 return nullptr;
12754 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012755 } else if (getOpenMPCaptureRegionForClause(
12756 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12757 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012758 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012759 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000012760 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12761 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12762 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012763 }
12764 }
12765 }
12766
12767 return new (Context)
12768 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012769 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012770}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012771
12772OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12773 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12774 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12775 SourceLocation KindLoc, SourceLocation EndLoc) {
12776 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012777 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012778 std::string Value;
12779 SourceLocation Loc;
12780 Value += "'";
12781 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12782 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012783 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012784 Loc = MLoc;
12785 } else {
12786 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012787 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012788 Loc = KindLoc;
12789 }
12790 Value += "'";
12791 Diag(Loc, diag::err_omp_unexpected_clause_value)
12792 << Value << getOpenMPClauseName(OMPC_defaultmap);
12793 return nullptr;
12794 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012795 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012796
12797 return new (Context)
12798 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12799}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012800
12801bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12802 DeclContext *CurLexicalContext = getCurLexicalContext();
12803 if (!CurLexicalContext->isFileContext() &&
12804 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012805 !CurLexicalContext->isExternCXXContext() &&
12806 !isa<CXXRecordDecl>(CurLexicalContext) &&
12807 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12808 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12809 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012810 Diag(Loc, diag::err_omp_region_not_file_context);
12811 return false;
12812 }
12813 if (IsInOpenMPDeclareTargetContext) {
12814 Diag(Loc, diag::err_omp_enclosed_declare_target);
12815 return false;
12816 }
12817
12818 IsInOpenMPDeclareTargetContext = true;
12819 return true;
12820}
12821
12822void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12823 assert(IsInOpenMPDeclareTargetContext &&
12824 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12825
12826 IsInOpenMPDeclareTargetContext = false;
12827}
12828
David Majnemer9d168222016-08-05 17:44:54 +000012829void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12830 CXXScopeSpec &ScopeSpec,
12831 const DeclarationNameInfo &Id,
12832 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12833 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012834 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12835 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12836
12837 if (Lookup.isAmbiguous())
12838 return;
12839 Lookup.suppressDiagnostics();
12840
12841 if (!Lookup.isSingleResult()) {
12842 if (TypoCorrection Corrected =
12843 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12844 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12845 CTK_ErrorRecovery)) {
12846 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12847 << Id.getName());
12848 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12849 return;
12850 }
12851
12852 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12853 return;
12854 }
12855
12856 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12857 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12858 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12859 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12860
12861 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12862 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12863 ND->addAttr(A);
12864 if (ASTMutationListener *ML = Context.getASTMutationListener())
12865 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000012866 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012867 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12868 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12869 << Id.getName();
12870 }
12871 } else
12872 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12873}
12874
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012875static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12876 Sema &SemaRef, Decl *D) {
12877 if (!D)
12878 return;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012879 const Decl *LD = nullptr;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012880 if (isa<TagDecl>(D)) {
12881 LD = cast<TagDecl>(D)->getDefinition();
12882 } else if (isa<VarDecl>(D)) {
12883 LD = cast<VarDecl>(D)->getDefinition();
12884
12885 // If this is an implicit variable that is legal and we do not need to do
12886 // anything.
12887 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012888 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12889 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12890 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012891 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012892 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012893 return;
12894 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000012895 } else if (auto *F = dyn_cast<FunctionDecl>(D)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012896 const FunctionDecl *FD = nullptr;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012897 if (cast<FunctionDecl>(D)->hasBody(FD)) {
12898 LD = FD;
12899 // If the definition is associated with the current declaration in the
12900 // target region (it can be e.g. a lambda) that is legal and we do not
12901 // need to do anything else.
12902 if (LD == D) {
12903 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12904 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12905 D->addAttr(A);
12906 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12907 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12908 return;
12909 }
12910 } else if (F->isFunctionTemplateSpecialization() &&
12911 F->getTemplateSpecializationKind() ==
12912 TSK_ImplicitInstantiation) {
12913 // Check if the function is implicitly instantiated from the template
12914 // defined in the declare target region.
12915 const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
12916 if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
12917 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012918 }
12919 }
12920 if (!LD)
12921 LD = D;
12922 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12923 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12924 // Outlined declaration is not declared target.
12925 if (LD->isOutOfLine()) {
12926 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12927 SemaRef.Diag(SL, diag::note_used_here) << SR;
12928 } else {
Alexey Bataev8e39c342018-02-16 21:23:23 +000012929 const DeclContext *DC = LD->getDeclContext();
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012930 while (DC) {
12931 if (isa<FunctionDecl>(DC) &&
12932 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12933 break;
12934 DC = DC->getParent();
12935 }
12936 if (DC)
12937 return;
12938
12939 // Is not declared in target context.
12940 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12941 SemaRef.Diag(SL, diag::note_used_here) << SR;
12942 }
12943 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012944 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12945 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12946 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012947 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012948 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012949 }
12950}
12951
12952static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12953 Sema &SemaRef, DSAStackTy *Stack,
12954 ValueDecl *VD) {
12955 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12956 return true;
Alexey Bataev95c23e72018-02-27 21:31:11 +000012957 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
12958 /*FullCheck=*/false))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012959 return false;
12960 return true;
12961}
12962
Kelvin Li1ce87c72017-12-12 20:08:12 +000012963void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12964 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012965 if (!D || D->isInvalidDecl())
12966 return;
12967 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12968 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12969 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12970 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12971 if (DSAStack->isThreadPrivate(VD)) {
12972 Diag(SL, diag::err_omp_threadprivate_in_target);
12973 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12974 return;
12975 }
12976 }
12977 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12978 // Problem if any with var declared with incomplete type will be reported
12979 // as normal, so no need to check it here.
12980 if ((E || !VD->getType()->isIncompleteType()) &&
12981 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12982 // Mark decl as declared target to prevent further diagnostic.
Alexey Bataev8e39c342018-02-16 21:23:23 +000012983 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
12984 isa<FunctionTemplateDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012985 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12986 Context, OMPDeclareTargetDeclAttr::MT_To);
12987 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012988 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012989 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012990 }
12991 return;
12992 }
12993 }
Kelvin Li1ce87c72017-12-12 20:08:12 +000012994 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12995 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12996 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12997 OMPDeclareTargetDeclAttr::MT_Link)) {
12998 assert(IdLoc.isValid() && "Source location is expected");
12999 Diag(IdLoc, diag::err_omp_function_in_link_clause);
13000 Diag(FD->getLocation(), diag::note_defined_here) << FD;
13001 return;
13002 }
13003 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000013004 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
13005 if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13006 (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13007 OMPDeclareTargetDeclAttr::MT_Link)) {
13008 assert(IdLoc.isValid() && "Source location is expected");
13009 Diag(IdLoc, diag::err_omp_function_in_link_clause);
13010 Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
13011 return;
13012 }
13013 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013014 if (!E) {
13015 // Checking declaration inside declare target region.
13016 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
Alexey Bataev8e39c342018-02-16 21:23:23 +000013017 (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13018 isa<FunctionTemplateDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013019 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13020 Context, OMPDeclareTargetDeclAttr::MT_To);
13021 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013022 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013023 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013024 }
13025 return;
13026 }
13027 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13028}
Samuel Antao661c0902016-05-26 17:39:58 +000013029
13030OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13031 SourceLocation StartLoc,
13032 SourceLocation LParenLoc,
13033 SourceLocation EndLoc) {
13034 MappableVarListInfo MVLI(VarList);
13035 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13036 if (MVLI.ProcessedVarList.empty())
13037 return nullptr;
13038
13039 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13040 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13041 MVLI.VarComponents);
13042}
Samuel Antaoec172c62016-05-26 17:49:04 +000013043
13044OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13045 SourceLocation StartLoc,
13046 SourceLocation LParenLoc,
13047 SourceLocation EndLoc) {
13048 MappableVarListInfo MVLI(VarList);
13049 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13050 if (MVLI.ProcessedVarList.empty())
13051 return nullptr;
13052
13053 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13054 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13055 MVLI.VarComponents);
13056}
Carlo Bertolli2404b172016-07-13 15:37:16 +000013057
13058OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13059 SourceLocation StartLoc,
13060 SourceLocation LParenLoc,
13061 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000013062 MappableVarListInfo MVLI(VarList);
13063 SmallVector<Expr *, 8> PrivateCopies;
13064 SmallVector<Expr *, 8> Inits;
13065
Carlo Bertolli2404b172016-07-13 15:37:16 +000013066 for (auto &RefExpr : VarList) {
13067 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13068 SourceLocation ELoc;
13069 SourceRange ERange;
13070 Expr *SimpleRefExpr = RefExpr;
13071 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13072 if (Res.second) {
13073 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000013074 MVLI.ProcessedVarList.push_back(RefExpr);
13075 PrivateCopies.push_back(nullptr);
13076 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013077 }
13078 ValueDecl *D = Res.first;
13079 if (!D)
13080 continue;
13081
13082 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000013083 Type = Type.getNonReferenceType().getUnqualifiedType();
13084
13085 auto *VD = dyn_cast<VarDecl>(D);
13086
13087 // Item should be a pointer or reference to pointer.
13088 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013089 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13090 << 0 << RefExpr->getSourceRange();
13091 continue;
13092 }
Samuel Antaocc10b852016-07-28 14:23:26 +000013093
13094 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013095 auto VDPrivate =
13096 buildVarDecl(*this, ELoc, Type, D->getName(),
13097 D->hasAttrs() ? &D->getAttrs() : nullptr,
13098 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000013099 if (VDPrivate->isInvalidDecl())
13100 continue;
13101
13102 CurContext->addDecl(VDPrivate);
13103 auto VDPrivateRefExpr = buildDeclRefExpr(
13104 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13105
13106 // Add temporary variable to initialize the private copy of the pointer.
13107 auto *VDInit =
13108 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13109 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13110 RefExpr->getExprLoc());
13111 AddInitializerToDecl(VDPrivate,
13112 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013113 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013114
13115 // If required, build a capture to implement the privatization initialized
13116 // with the current list item value.
13117 DeclRefExpr *Ref = nullptr;
13118 if (!VD)
13119 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13120 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13121 PrivateCopies.push_back(VDPrivateRefExpr);
13122 Inits.push_back(VDInitRefExpr);
13123
13124 // We need to add a data sharing attribute for this variable to make sure it
13125 // is correctly captured. A variable that shows up in a use_device_ptr has
13126 // similar properties of a first private variable.
13127 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13128
13129 // Create a mappable component for the list item. List items in this clause
13130 // only need a component.
13131 MVLI.VarBaseDeclarations.push_back(D);
13132 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13133 MVLI.VarComponents.back().push_back(
13134 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013135 }
13136
Samuel Antaocc10b852016-07-28 14:23:26 +000013137 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013138 return nullptr;
13139
Samuel Antaocc10b852016-07-28 14:23:26 +000013140 return OMPUseDevicePtrClause::Create(
13141 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13142 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013143}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013144
13145OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13146 SourceLocation StartLoc,
13147 SourceLocation LParenLoc,
13148 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013149 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013150 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013151 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013152 SourceLocation ELoc;
13153 SourceRange ERange;
13154 Expr *SimpleRefExpr = RefExpr;
13155 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13156 if (Res.second) {
13157 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013158 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013159 }
13160 ValueDecl *D = Res.first;
13161 if (!D)
13162 continue;
13163
13164 QualType Type = D->getType();
13165 // item should be a pointer or array or reference to pointer or array
13166 if (!Type.getNonReferenceType()->isPointerType() &&
13167 !Type.getNonReferenceType()->isArrayType()) {
13168 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13169 << 0 << RefExpr->getSourceRange();
13170 continue;
13171 }
Samuel Antao6890b092016-07-28 14:25:09 +000013172
13173 // Check if the declaration in the clause does not show up in any data
13174 // sharing attribute.
13175 auto DVar = DSAStack->getTopDSA(D, false);
13176 if (isOpenMPPrivate(DVar.CKind)) {
13177 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13178 << getOpenMPClauseName(DVar.CKind)
13179 << getOpenMPClauseName(OMPC_is_device_ptr)
13180 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13181 ReportOriginalDSA(*this, DSAStack, D, DVar);
13182 continue;
13183 }
13184
13185 Expr *ConflictExpr;
13186 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013187 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013188 [&ConflictExpr](
13189 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13190 OpenMPClauseKind) -> bool {
13191 ConflictExpr = R.front().getAssociatedExpression();
13192 return true;
13193 })) {
13194 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13195 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13196 << ConflictExpr->getSourceRange();
13197 continue;
13198 }
13199
13200 // Store the components in the stack so that they can be used to check
13201 // against other clauses later on.
13202 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13203 DSAStack->addMappableExpressionComponents(
13204 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13205
13206 // Record the expression we've just processed.
13207 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13208
13209 // Create a mappable component for the list item. List items in this clause
13210 // only need a component. We use a null declaration to signal fields in
13211 // 'this'.
13212 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13213 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13214 "Unexpected device pointer expression!");
13215 MVLI.VarBaseDeclarations.push_back(
13216 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13217 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13218 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013219 }
13220
Samuel Antao6890b092016-07-28 14:25:09 +000013221 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013222 return nullptr;
13223
Samuel Antao6890b092016-07-28 14:25:09 +000013224 return OMPIsDevicePtrClause::Create(
13225 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13226 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013227}