blob: 342bd6dce87b8bb85716c29d85d4f19998f892d2 [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
38namespace {
39/// \brief Default data sharing attributes, which can be applied to directive.
40enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000041 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
42 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
43 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000044};
Alexey Bataev7ff55242014-06-19 09:13:45 +000045
Alexey Bataev758e55e2013-09-06 18:03:48 +000046/// \brief Stack for tracking declarations used in OpenMP directives and
47/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000048class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000049public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050 struct DSAVarData final {
51 OpenMPDirectiveKind DKind = OMPD_unknown;
52 OpenMPClauseKind CKind = OMPC_unknown;
53 Expr *RefExpr = nullptr;
54 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000055 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000056 DSAVarData() = default;
Alexey Bataevf189cb72017-07-24 14:52:13 +000057 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
58 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
59 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
60 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000061 };
Alexey Bataev8b427062016-05-25 12:36:08 +000062 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
63 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000064
Alexey Bataev758e55e2013-09-06 18:03:48 +000065private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000066 struct DSAInfo final {
67 OpenMPClauseKind Attributes = OMPC_unknown;
68 /// Pointer to a reference expression and a flag which shows that the
69 /// variable is marked as lastprivate(true) or not (false).
70 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
71 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000073 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
74 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000075 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
76 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000077 /// Struct that associates a component with the clause kind where they are
78 /// found.
79 struct MappedExprComponentTy {
80 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
81 OpenMPClauseKind Kind = OMPC_unknown;
82 };
83 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000084 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000085 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
86 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000087 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
88 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +000089 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +000090 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +000091 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +000092 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +000093 ReductionData() = default;
94 void set(BinaryOperatorKind BO, SourceRange RR) {
95 ReductionRange = RR;
96 ReductionOp = BO;
97 }
98 void set(const Expr *RefExpr, SourceRange RR) {
99 ReductionRange = RR;
100 ReductionOp = RefExpr;
101 }
102 };
103 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000104
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000105 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000107 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000108 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000109 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000110 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000111 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000114 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000115 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000116 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000117 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
118 /// get the data (loop counters etc.) about enclosing loop-based construct.
119 /// This data is required during codegen.
120 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000121 /// \brief first argument (Expr *) contains optional argument of the
122 /// 'ordered' clause, the second one is true if the regions has 'ordered'
123 /// clause, false otherwise.
124 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 bool NowaitRegion = false;
126 bool CancelRegion = false;
127 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000128 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000129 /// Reference to the taskgroup task_reduction reference expression.
130 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000131 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000133 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
134 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000135 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136 };
137
Axel Naumann323862e2016-02-03 10:45:22 +0000138 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000139
140 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000141 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000142 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
143 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000144 /// \brief true, if check for DSA must be from parent directive, false, if
145 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000146 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000147 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000148 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000149 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000150
151 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
152
David Majnemer9d168222016-08-05 17:44:54 +0000153 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000154
155 /// \brief Checks if the variable is a local for OpenMP region.
156 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000157
Alexey Bataev4b465392017-04-26 15:06:24 +0000158 bool isStackEmpty() const {
159 return Stack.empty() ||
160 Stack.back().second != CurrentNonCapturingFunctionScope ||
161 Stack.back().first.empty();
162 }
163
Alexey Bataev758e55e2013-09-06 18:03:48 +0000164public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000165 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000166
Alexey Bataevaac108a2015-06-23 04:51:00 +0000167 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
168 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000169
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000170 bool isForceVarCapturing() const { return ForceCapturing; }
171 void setForceVarCapturing(bool V) { ForceCapturing = V; }
172
Alexey Bataev758e55e2013-09-06 18:03:48 +0000173 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000174 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000175 if (Stack.empty() ||
176 Stack.back().second != CurrentNonCapturingFunctionScope)
177 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
178 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
179 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000180 }
181
182 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000183 assert(!Stack.back().first.empty() &&
184 "Data-sharing attributes stack is empty!");
185 Stack.back().first.pop_back();
186 }
187
188 /// Start new OpenMP region stack in new non-capturing function.
189 void pushFunction() {
190 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
191 assert(!isa<CapturingScopeInfo>(CurFnScope));
192 CurrentNonCapturingFunctionScope = CurFnScope;
193 }
194 /// Pop region stack for non-capturing function.
195 void popFunction(const FunctionScopeInfo *OldFSI) {
196 if (!Stack.empty() && Stack.back().second == OldFSI) {
197 assert(Stack.back().first.empty());
198 Stack.pop_back();
199 }
200 CurrentNonCapturingFunctionScope = nullptr;
201 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
202 if (!isa<CapturingScopeInfo>(FSI)) {
203 CurrentNonCapturingFunctionScope = FSI;
204 break;
205 }
206 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000207 }
208
Alexey Bataev28c75412015-12-15 08:19:24 +0000209 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
210 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
211 }
212 const std::pair<OMPCriticalDirective *, llvm::APSInt>
213 getCriticalWithHint(const DeclarationNameInfo &Name) const {
214 auto I = Criticals.find(Name.getAsString());
215 if (I != Criticals.end())
216 return I->second;
217 return std::make_pair(nullptr, llvm::APSInt());
218 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000219 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000220 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000221 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000222 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000223
Alexey Bataev9c821032015-04-30 04:23:23 +0000224 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000225 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000226 /// \brief Check if the specified variable is a loop control variable for
227 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000228 /// \return The index of the loop control variable in the list of associated
229 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000230 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000231 /// \brief Check if the specified variable is a loop control variable for
232 /// parent region.
233 /// \return The index of the loop control variable in the list of associated
234 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000235 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000236 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
237 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000238 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000239
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000241 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
242 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000243
Alexey Bataevfa312f32017-07-21 18:48:21 +0000244 /// Adds additional information for the reduction items with the reduction id
245 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000246 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
247 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000248 /// Adds additional information for the reduction items with the reduction id
249 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000250 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
251 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000252 /// Returns the location and reduction operation from the innermost parent
253 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000254 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000255 BinaryOperatorKind &BOK,
256 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000257 /// Returns the location and reduction operation from the innermost parent
258 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000259 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000260 const Expr *&ReductionRef,
261 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000262 /// Return reduction reference expression for the current taskgroup.
263 Expr *getTaskgroupReductionRef() const {
264 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
265 "taskgroup reference expression requested for non taskgroup "
266 "directive.");
267 return Stack.back().first.back().TaskgroupReductionRef;
268 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000269 /// Checks if the given \p VD declaration is actually a taskgroup reduction
270 /// descriptor variable at the \p Level of OpenMP regions.
271 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
272 return Stack.back().first[Level].TaskgroupReductionRef &&
273 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
274 ->getDecl() == VD;
275 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000276
Alexey Bataev758e55e2013-09-06 18:03:48 +0000277 /// \brief Returns data sharing attributes from top of the stack for the
278 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000279 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000280 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000281 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000282 /// \brief Checks if the specified variables has data-sharing attributes which
283 /// match specified \a CPred predicate in any directive which matches \a DPred
284 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000285 DSAVarData hasDSA(ValueDecl *D,
286 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
287 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
288 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000289 /// \brief Checks if the specified variables has data-sharing attributes which
290 /// match specified \a CPred predicate in any innermost directive which
291 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000292 DSAVarData
293 hasInnermostDSA(ValueDecl *D,
294 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
295 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
296 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000297 /// \brief Checks if the specified variables has explicit data-sharing
298 /// attributes which match specified \a CPred predicate at the specified
299 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000300 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000301 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000302 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000303
304 /// \brief Returns true if the directive at level \Level matches in the
305 /// specified \a DPred predicate.
306 bool hasExplicitDirective(
307 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
308 unsigned Level);
309
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000310 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000311 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
312 const DeclarationNameInfo &,
313 SourceLocation)> &DPred,
314 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000315
Alexey Bataev758e55e2013-09-06 18:03:48 +0000316 /// \brief Returns currently analyzed directive.
317 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000318 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000319 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000320 /// \brief Returns parent directive.
321 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000322 if (isStackEmpty() || Stack.back().first.size() == 1)
323 return OMPD_unknown;
324 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000325 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326
327 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000328 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000329 assert(!isStackEmpty());
330 Stack.back().first.back().DefaultAttr = DSA_none;
331 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000332 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000333 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000334 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 assert(!isStackEmpty());
336 Stack.back().first.back().DefaultAttr = DSA_shared;
337 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000338 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000339
340 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000341 return isStackEmpty() ? DSA_unspecified
342 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000344 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000345 return isStackEmpty() ? SourceLocation()
346 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000347 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000348
Alexey Bataevf29276e2014-06-18 04:14:57 +0000349 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000350 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000351 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000352 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000353 }
354
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000355 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000356 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000357 assert(!isStackEmpty());
358 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
359 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000360 }
361 /// \brief Returns true, if parent region is ordered (has associated
362 /// 'ordered' clause), false - otherwise.
363 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000364 if (isStackEmpty() || Stack.back().first.size() == 1)
365 return false;
366 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000367 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000368 /// \brief Returns optional parameter for the ordered region.
369 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000370 if (isStackEmpty() || Stack.back().first.size() == 1)
371 return nullptr;
372 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000373 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000374 /// \brief Marks current region as nowait (it has a 'nowait' clause).
375 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000376 assert(!isStackEmpty());
377 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000378 }
379 /// \brief Returns true, if parent region is nowait (has associated
380 /// 'nowait' clause), false - otherwise.
381 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000382 if (isStackEmpty() || Stack.back().first.size() == 1)
383 return false;
384 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000385 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000386 /// \brief Marks parent region as cancel region.
387 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000388 if (!isStackEmpty() && Stack.back().first.size() > 1) {
389 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
390 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
391 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000392 }
393 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000394 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000395 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000396 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000397
Alexey Bataev9c821032015-04-30 04:23:23 +0000398 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000399 void setAssociatedLoops(unsigned Val) {
400 assert(!isStackEmpty());
401 Stack.back().first.back().AssociatedLoops = Val;
402 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000403 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000404 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000405 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000406 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000407
Alexey Bataev13314bf2014-10-09 04:18:56 +0000408 /// \brief Marks current target region as one with closely nested teams
409 /// region.
410 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000411 if (!isStackEmpty() && Stack.back().first.size() > 1) {
412 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
413 TeamsRegionLoc;
414 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000415 }
416 /// \brief Returns true, if current region has closely nested teams region.
417 bool hasInnerTeamsRegion() const {
418 return getInnerTeamsRegionLoc().isValid();
419 }
420 /// \brief Returns location of the nested teams region (if any).
421 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000422 return isStackEmpty() ? SourceLocation()
423 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000424 }
425
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000426 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000428 }
429 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000430 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000431 }
432 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000433 return isStackEmpty() ? SourceLocation()
434 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000435 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000436
Samuel Antao4c8035b2016-12-12 18:00:20 +0000437 /// Do the check specified in \a Check to all component lists and return true
438 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000439 bool checkMappableExprComponentListsForDecl(
440 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000441 const llvm::function_ref<
442 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
443 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000444 if (isStackEmpty())
445 return false;
446 auto SI = Stack.back().first.rbegin();
447 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000448
449 if (SI == SE)
450 return false;
451
452 if (CurrentRegionOnly) {
453 SE = std::next(SI);
454 } else {
455 ++SI;
456 }
457
458 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000459 auto MI = SI->MappedExprComponents.find(VD);
460 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000461 for (auto &L : MI->second.Components)
462 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000463 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000464 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000465 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000466 }
467
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000468 /// Do the check specified in \a Check to all component lists at a given level
469 /// and return true if any issue is found.
470 bool checkMappableExprComponentListsForDeclAtLevel(
471 ValueDecl *VD, unsigned Level,
472 const llvm::function_ref<
473 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
474 OpenMPClauseKind)> &Check) {
475 if (isStackEmpty())
476 return false;
477
478 auto StartI = Stack.back().first.begin();
479 auto EndI = Stack.back().first.end();
480 if (std::distance(StartI, EndI) <= (int)Level)
481 return false;
482 std::advance(StartI, Level);
483
484 auto MI = StartI->MappedExprComponents.find(VD);
485 if (MI != StartI->MappedExprComponents.end())
486 for (auto &L : MI->second.Components)
487 if (Check(L, MI->second.Kind))
488 return true;
489 return false;
490 }
491
Samuel Antao4c8035b2016-12-12 18:00:20 +0000492 /// Create a new mappable expression component list associated with a given
493 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000494 void addMappableExpressionComponents(
495 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000496 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
497 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000498 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000499 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000500 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000501 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000502 MEC.Components.resize(MEC.Components.size() + 1);
503 MEC.Components.back().append(Components.begin(), Components.end());
504 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000505 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000506
507 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000508 assert(!isStackEmpty());
509 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000510 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000511 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000512 assert(!isStackEmpty() && Stack.back().first.size() > 1);
513 auto &StackElem = *std::next(Stack.back().first.rbegin());
514 assert(isOpenMPWorksharingDirective(StackElem.Directive));
515 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000516 }
517 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
518 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000519 assert(!isStackEmpty());
520 auto &StackElem = Stack.back().first.back();
521 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
522 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000523 return llvm::make_range(Ref.begin(), Ref.end());
524 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000525 return llvm::make_range(StackElem.DoacrossDepends.end(),
526 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000527 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000528};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000529bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000530 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
531 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000532}
Alexey Bataeved09d242014-05-28 05:53:51 +0000533} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000534
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000535static Expr *getExprAsWritten(Expr *E) {
536 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
537 E = ExprTemp->getSubExpr();
538
539 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
540 E = MTE->GetTemporaryExpr();
541
542 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
543 E = Binder->getSubExpr();
544
545 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
546 E = ICE->getSubExprAsWritten();
547 return E->IgnoreParens();
548}
549
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000550static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000551 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
552 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
553 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000554 auto *VD = dyn_cast<VarDecl>(D);
555 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000556 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000557 VD = VD->getCanonicalDecl();
558 D = VD;
559 } else {
560 assert(FD);
561 FD = FD->getCanonicalDecl();
562 D = FD;
563 }
564 return D;
565}
566
David Majnemer9d168222016-08-05 17:44:54 +0000567DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000568 ValueDecl *D) {
569 D = getCanonicalDecl(D);
570 auto *VD = dyn_cast<VarDecl>(D);
571 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000572 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000573 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000574 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
575 // in a region but not in construct]
576 // File-scope or namespace-scope variables referenced in called routines
577 // in the region are shared unless they appear in a threadprivate
578 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000579 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000580 DVar.CKind = OMPC_shared;
581
582 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
583 // in a region but not in construct]
584 // Variables with static storage duration that are declared in called
585 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000586 if (VD && VD->hasGlobalStorage())
587 DVar.CKind = OMPC_shared;
588
589 // Non-static data members are shared by default.
590 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000591 DVar.CKind = OMPC_shared;
592
Alexey Bataev758e55e2013-09-06 18:03:48 +0000593 return DVar;
594 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000595
Alexey Bataevec3da872014-01-31 05:15:34 +0000596 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
597 // in a Construct, C/C++, predetermined, p.1]
598 // Variables with automatic storage duration that are declared in a scope
599 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000600 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
601 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000602 DVar.CKind = OMPC_private;
603 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000604 }
605
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000606 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000607 // Explicitly specified attributes and local variables with predetermined
608 // attributes.
609 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000610 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000611 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000612 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000613 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000614 return DVar;
615 }
616
617 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
618 // in a Construct, C/C++, implicitly determined, p.1]
619 // In a parallel or task construct, the data-sharing attributes of these
620 // variables are determined by the default clause, if present.
621 switch (Iter->DefaultAttr) {
622 case DSA_shared:
623 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000624 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000625 return DVar;
626 case DSA_none:
627 return DVar;
628 case DSA_unspecified:
629 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
630 // in a Construct, implicitly determined, p.2]
631 // In a parallel construct, if no default clause is present, these
632 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000633 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000634 if (isOpenMPParallelDirective(DVar.DKind) ||
635 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000636 DVar.CKind = OMPC_shared;
637 return DVar;
638 }
639
640 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
641 // in a Construct, implicitly determined, p.4]
642 // In a task construct, if no default clause is present, a variable that in
643 // the enclosing context is determined to be shared by all implicit tasks
644 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000645 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000646 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000647 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000648 do {
649 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000650 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000651 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 // In a task construct, if no default clause is present, a variable
653 // whose data-sharing attribute is not determined by the rules above is
654 // firstprivate.
655 DVarTemp = getDSA(I, D);
656 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000657 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000658 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000659 return DVar;
660 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000661 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000662 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000663 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000664 return DVar;
665 }
666 }
667 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
668 // in a Construct, implicitly determined, p.3]
669 // For constructs other than task, if no default clause is present, these
670 // variables inherit their data-sharing attributes from the enclosing
671 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000672 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000673}
674
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000675Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000676 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000677 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000678 auto &StackElem = Stack.back().first.back();
679 auto It = StackElem.AlignedMap.find(D);
680 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000681 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000682 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000683 return nullptr;
684 } else {
685 assert(It->second && "Unexpected nullptr expr in the aligned map");
686 return It->second;
687 }
688 return nullptr;
689}
690
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000691void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000692 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000693 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000694 auto &StackElem = Stack.back().first.back();
695 StackElem.LCVMap.insert(
696 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000697}
698
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000699DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000700 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000701 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000702 auto &StackElem = Stack.back().first.back();
703 auto It = StackElem.LCVMap.find(D);
704 if (It != StackElem.LCVMap.end())
705 return It->second;
706 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000707}
708
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000709DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000710 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
711 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000712 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000713 auto &StackElem = *std::next(Stack.back().first.rbegin());
714 auto It = StackElem.LCVMap.find(D);
715 if (It != StackElem.LCVMap.end())
716 return It->second;
717 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000718}
719
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000720ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000721 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
722 "Data-sharing attributes stack is empty");
723 auto &StackElem = *std::next(Stack.back().first.rbegin());
724 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000725 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000726 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000727 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000728 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000729 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000730}
731
Alexey Bataev90c228f2016-02-08 09:29:13 +0000732void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
733 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000734 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000735 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000736 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000737 Data.Attributes = A;
738 Data.RefExpr.setPointer(E);
739 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000740 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000741 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
742 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000743 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
744 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
745 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
746 (isLoopControlVariable(D).first && A == OMPC_private));
747 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
748 Data.RefExpr.setInt(/*IntVal=*/true);
749 return;
750 }
751 const bool IsLastprivate =
752 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
753 Data.Attributes = A;
754 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
755 Data.PrivateCopy = PrivateCopy;
756 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000757 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000758 Data.Attributes = A;
759 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
760 Data.PrivateCopy = nullptr;
761 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000762 }
763}
764
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000765/// \brief Build a variable declaration for OpenMP loop iteration variable.
766static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
767 StringRef Name, const AttrVec *Attrs = nullptr) {
768 DeclContext *DC = SemaRef.CurContext;
769 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
770 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
771 VarDecl *Decl =
772 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
773 if (Attrs) {
774 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
775 I != E; ++I)
776 Decl->addAttr(*I);
777 }
778 Decl->setImplicit();
779 return Decl;
780}
781
782static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
783 SourceLocation Loc,
784 bool RefersToCapture = false) {
785 D->setReferenced();
786 D->markUsed(S.Context);
787 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
788 SourceLocation(), D, RefersToCapture, Loc, Ty,
789 VK_LValue);
790}
791
792void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
793 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000794 D = getCanonicalDecl(D);
795 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000796 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000797 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000798 "Additional reduction info may be specified only for reduction items.");
799 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
800 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000801 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000802 "Additional reduction info may be specified only once for reduction "
803 "items.");
804 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000805 Expr *&TaskgroupReductionRef =
806 Stack.back().first.back().TaskgroupReductionRef;
807 if (!TaskgroupReductionRef) {
808 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
809 SemaRef.Context.VoidPtrTy, ".task_red.");
810 TaskgroupReductionRef = buildDeclRefExpr(
811 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
812 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000813}
814
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000815void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
816 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000817 D = getCanonicalDecl(D);
818 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000819 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000820 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000821 "Additional reduction info may be specified only for reduction items.");
822 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
823 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000824 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000825 "Additional reduction info may be specified only once for reduction "
826 "items.");
827 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000828 Expr *&TaskgroupReductionRef =
829 Stack.back().first.back().TaskgroupReductionRef;
830 if (!TaskgroupReductionRef) {
831 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
832 SemaRef.Context.VoidPtrTy, ".task_red.");
833 TaskgroupReductionRef = buildDeclRefExpr(
834 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
835 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000836}
837
Alexey Bataevf189cb72017-07-24 14:52:13 +0000838DSAStackTy::DSAVarData
839DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000840 BinaryOperatorKind &BOK,
841 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000842 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000843 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
844 if (Stack.back().first.empty())
845 return DSAVarData();
846 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000847 E = Stack.back().first.rend();
848 I != E; std::advance(I, 1)) {
849 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000850 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000851 continue;
852 auto &ReductionData = I->ReductionMap[D];
853 if (!ReductionData.ReductionOp ||
854 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000855 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000856 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000857 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000858 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
859 "expression for the descriptor is not "
860 "set.");
861 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000862 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
863 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000864 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000865 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000866}
867
Alexey Bataevf189cb72017-07-24 14:52:13 +0000868DSAStackTy::DSAVarData
869DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000870 const Expr *&ReductionRef,
871 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000872 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000873 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
874 if (Stack.back().first.empty())
875 return DSAVarData();
876 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000877 E = Stack.back().first.rend();
878 I != E; std::advance(I, 1)) {
879 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000880 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000881 continue;
882 auto &ReductionData = I->ReductionMap[D];
883 if (!ReductionData.ReductionOp ||
884 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000885 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 SR = ReductionData.ReductionRange;
887 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000888 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
889 "expression for the descriptor is not "
890 "set.");
891 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000892 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
893 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000894 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000895 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000896}
897
Alexey Bataeved09d242014-05-28 05:53:51 +0000898bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000899 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000900 if (!isStackEmpty() && Stack.back().first.size() > 1) {
901 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000902 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000903 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000904 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000905 if (I == E)
906 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000907 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000908 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000909 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000910 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000911 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000912 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000913 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000914}
915
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000916DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
917 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000918 DSAVarData DVar;
919
920 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
921 // in a Construct, C/C++, predetermined, p.1]
922 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000923 auto *VD = dyn_cast<VarDecl>(D);
924 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
925 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000926 SemaRef.getLangOpts().OpenMPUseTLS &&
927 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000928 (VD && VD->getStorageClass() == SC_Register &&
929 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
930 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000931 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000932 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000933 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000934 auto TI = Threadprivates.find(D);
935 if (TI != Threadprivates.end()) {
936 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000937 DVar.CKind = OMPC_threadprivate;
938 return DVar;
939 }
940
Alexey Bataev4b465392017-04-26 15:06:24 +0000941 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000942 // Not in OpenMP execution region and top scope was already checked.
943 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000944
Alexey Bataev758e55e2013-09-06 18:03:48 +0000945 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000946 // in a Construct, C/C++, predetermined, p.4]
947 // Static data members are shared.
948 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
949 // in a Construct, C/C++, predetermined, p.7]
950 // Variables with static storage duration that are declared in a scope
951 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000952 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000953 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000954 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000955 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000956 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000957
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000958 DVar.CKind = OMPC_shared;
959 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000960 }
961
962 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000963 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
964 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000965 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
966 // in a Construct, C/C++, predetermined, p.6]
967 // Variables with const qualified type having no mutable member are
968 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000969 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000970 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000971 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
972 if (auto *CTD = CTSD->getSpecializedTemplate())
973 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000974 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000975 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
976 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000977 // Variables with const-qualified type having no mutable member may be
978 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000979 DSAVarData DVarTemp = hasDSA(
980 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
981 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000982 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
983 return DVar;
984
Alexey Bataev758e55e2013-09-06 18:03:48 +0000985 DVar.CKind = OMPC_shared;
986 return DVar;
987 }
988
Alexey Bataev758e55e2013-09-06 18:03:48 +0000989 // Explicitly specified attributes and local variables with predetermined
990 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000991 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000992 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000993 if (FromParent && I != EndI)
994 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000995 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000996 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000997 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000998 DVar.CKind = I->SharingMap[D].Attributes;
999 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001000 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001001 }
1002
1003 return DVar;
1004}
1005
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001006DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1007 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001008 if (isStackEmpty()) {
1009 StackTy::reverse_iterator I;
1010 return getDSA(I, D);
1011 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001012 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001013 auto StartI = Stack.back().first.rbegin();
1014 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001015 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001016 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001017 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001018}
1019
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001020DSAStackTy::DSAVarData
1021DSAStackTy::hasDSA(ValueDecl *D,
1022 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1023 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1024 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001025 if (isStackEmpty())
1026 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001027 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001028 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001029 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001030 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001031 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001032 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001033 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001034 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001035 auto NewI = I;
1036 DSAVarData DVar = getDSA(NewI, D);
1037 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001038 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001039 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001040 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001041}
1042
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001043DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1044 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1045 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1046 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001047 if (isStackEmpty())
1048 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001049 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001050 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001051 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001052 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001053 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001054 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001055 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001056 auto NewI = StartI;
1057 DSAVarData DVar = getDSA(NewI, D);
1058 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001059}
1060
Alexey Bataevaac108a2015-06-23 04:51:00 +00001061bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001062 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001063 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001064 if (CPred(ClauseKindMode))
1065 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001066 if (isStackEmpty())
1067 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001068 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001069 auto StartI = Stack.back().first.begin();
1070 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001071 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001072 return false;
1073 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001074 return (StartI->SharingMap.count(D) > 0) &&
1075 StartI->SharingMap[D].RefExpr.getPointer() &&
1076 CPred(StartI->SharingMap[D].Attributes) &&
1077 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001078}
1079
Samuel Antao4be30e92015-10-02 17:14:03 +00001080bool DSAStackTy::hasExplicitDirective(
1081 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1082 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001083 if (isStackEmpty())
1084 return false;
1085 auto StartI = Stack.back().first.begin();
1086 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001087 if (std::distance(StartI, EndI) <= (int)Level)
1088 return false;
1089 std::advance(StartI, Level);
1090 return DPred(StartI->Directive);
1091}
1092
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001093bool DSAStackTy::hasDirective(
1094 const llvm::function_ref<bool(OpenMPDirectiveKind,
1095 const DeclarationNameInfo &, SourceLocation)>
1096 &DPred,
1097 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001098 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001099 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001100 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001101 auto StartI = std::next(Stack.back().first.rbegin());
1102 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001103 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001104 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001105 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1106 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1107 return true;
1108 }
1109 return false;
1110}
1111
Alexey Bataev758e55e2013-09-06 18:03:48 +00001112void Sema::InitDataSharingAttributesStack() {
1113 VarDataSharingAttributesStack = new DSAStackTy(*this);
1114}
1115
1116#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1117
Alexey Bataev4b465392017-04-26 15:06:24 +00001118void Sema::pushOpenMPFunctionRegion() {
1119 DSAStack->pushFunction();
1120}
1121
1122void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1123 DSAStack->popFunction(OldFSI);
1124}
1125
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001126bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001127 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1128
1129 auto &Ctx = getASTContext();
1130 bool IsByRef = true;
1131
1132 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001133 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001134
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001135 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001136 // This table summarizes how a given variable should be passed to the device
1137 // given its type and the clauses where it appears. This table is based on
1138 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1139 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1140 //
1141 // =========================================================================
1142 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1143 // | |(tofrom:scalar)| | pvt | | | |
1144 // =========================================================================
1145 // | scl | | | | - | | bycopy|
1146 // | scl | | - | x | - | - | bycopy|
1147 // | scl | | x | - | - | - | null |
1148 // | scl | x | | | - | | byref |
1149 // | scl | x | - | x | - | - | bycopy|
1150 // | scl | x | x | - | - | - | null |
1151 // | scl | | - | - | - | x | byref |
1152 // | scl | x | - | - | - | x | byref |
1153 //
1154 // | agg | n.a. | | | - | | byref |
1155 // | agg | n.a. | - | x | - | - | byref |
1156 // | agg | n.a. | x | - | - | - | null |
1157 // | agg | n.a. | - | - | - | x | byref |
1158 // | agg | n.a. | - | - | - | x[] | byref |
1159 //
1160 // | ptr | n.a. | | | - | | bycopy|
1161 // | ptr | n.a. | - | x | - | - | bycopy|
1162 // | ptr | n.a. | x | - | - | - | null |
1163 // | ptr | n.a. | - | - | - | x | byref |
1164 // | ptr | n.a. | - | - | - | x[] | bycopy|
1165 // | ptr | n.a. | - | - | x | | bycopy|
1166 // | ptr | n.a. | - | - | x | x | bycopy|
1167 // | ptr | n.a. | - | - | x | x[] | bycopy|
1168 // =========================================================================
1169 // Legend:
1170 // scl - scalar
1171 // ptr - pointer
1172 // agg - aggregate
1173 // x - applies
1174 // - - invalid in this combination
1175 // [] - mapped with an array section
1176 // byref - should be mapped by reference
1177 // byval - should be mapped by value
1178 // null - initialize a local variable to null on the device
1179 //
1180 // Observations:
1181 // - All scalar declarations that show up in a map clause have to be passed
1182 // by reference, because they may have been mapped in the enclosing data
1183 // environment.
1184 // - If the scalar value does not fit the size of uintptr, it has to be
1185 // passed by reference, regardless the result in the table above.
1186 // - For pointers mapped by value that have either an implicit map or an
1187 // array section, the runtime library may pass the NULL value to the
1188 // device instead of the value passed to it by the compiler.
1189
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001190 if (Ty->isReferenceType())
1191 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001192
1193 // Locate map clauses and see if the variable being captured is referred to
1194 // in any of those clauses. Here we only care about variables, not fields,
1195 // because fields are part of aggregates.
1196 bool IsVariableUsedInMapClause = false;
1197 bool IsVariableAssociatedWithSection = false;
1198
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001199 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1200 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001201 MapExprComponents,
1202 OpenMPClauseKind WhereFoundClauseKind) {
1203 // Only the map clause information influences how a variable is
1204 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001205 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001206 if (WhereFoundClauseKind != OMPC_map)
1207 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001208
1209 auto EI = MapExprComponents.rbegin();
1210 auto EE = MapExprComponents.rend();
1211
1212 assert(EI != EE && "Invalid map expression!");
1213
1214 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1215 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1216
1217 ++EI;
1218 if (EI == EE)
1219 return false;
1220
1221 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1222 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1223 isa<MemberExpr>(EI->getAssociatedExpression())) {
1224 IsVariableAssociatedWithSection = true;
1225 // There is nothing more we need to know about this variable.
1226 return true;
1227 }
1228
1229 // Keep looking for more map info.
1230 return false;
1231 });
1232
1233 if (IsVariableUsedInMapClause) {
1234 // If variable is identified in a map clause it is always captured by
1235 // reference except if it is a pointer that is dereferenced somehow.
1236 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1237 } else {
1238 // By default, all the data that has a scalar type is mapped by copy.
1239 IsByRef = !Ty->isScalarType();
1240 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001241 }
1242
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001243 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1244 IsByRef = !DSAStack->hasExplicitDSA(
1245 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1246 Level, /*NotLastprivate=*/true);
1247 }
1248
Samuel Antao86ace552016-04-27 22:40:57 +00001249 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001250 // and alignment, because the runtime library only deals with uintptr types.
1251 // If it does not fit the uintptr size, we need to pass the data by reference
1252 // instead.
1253 if (!IsByRef &&
1254 (Ctx.getTypeSizeInChars(Ty) >
1255 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001256 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001257 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001258 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001259
1260 return IsByRef;
1261}
1262
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001263unsigned Sema::getOpenMPNestingLevel() const {
1264 assert(getLangOpts().OpenMP);
1265 return DSAStack->getNestingLevel();
1266}
1267
Alexey Bataev90c228f2016-02-08 09:29:13 +00001268VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001269 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001270 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001271
1272 // If we are attempting to capture a global variable in a directive with
1273 // 'target' we return true so that this global is also mapped to the device.
1274 //
1275 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1276 // then it should not be captured. Therefore, an extra check has to be
1277 // inserted here once support for 'declare target' is added.
1278 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001279 auto *VD = dyn_cast<VarDecl>(D);
1280 if (VD && !VD->hasLocalStorage()) {
Alexey Bataev61498fb2017-08-29 19:30:57 +00001281 if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001282 !DSAStack->isClauseParsingMode())
1283 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001284 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001285 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1286 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001287 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001288 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001289 false))
1290 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001291 }
1292
Alexey Bataev48977c32015-08-04 08:10:48 +00001293 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1294 (!DSAStack->isClauseParsingMode() ||
1295 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001296 auto &&Info = DSAStack->isLoopControlVariable(D);
1297 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001298 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001299 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001300 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001301 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001302 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001303 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001304 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001305 DVarPrivate = DSAStack->hasDSA(
1306 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1307 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001308 if (DVarPrivate.CKind != OMPC_unknown)
1309 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001310 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001311 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001312}
1313
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001314bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001315 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1316 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001317 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1318 Level) ||
1319 // Consider taskgroup reduction descriptor variable a private to avoid
1320 // possible capture in the region.
1321 (DSAStack->hasExplicitDirective(
1322 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1323 Level) &&
1324 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001325}
1326
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001327void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1328 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1329 D = getCanonicalDecl(D);
1330 OpenMPClauseKind OMPC = OMPC_unknown;
1331 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1332 const unsigned NewLevel = I - 1;
1333 if (DSAStack->hasExplicitDSA(D,
1334 [&OMPC](const OpenMPClauseKind K) {
1335 if (isOpenMPPrivate(K)) {
1336 OMPC = K;
1337 return true;
1338 }
1339 return false;
1340 },
1341 NewLevel))
1342 break;
1343 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1344 D, NewLevel,
1345 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1346 OpenMPClauseKind) { return true; })) {
1347 OMPC = OMPC_map;
1348 break;
1349 }
1350 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1351 NewLevel)) {
1352 OMPC = OMPC_firstprivate;
1353 break;
1354 }
1355 }
1356 if (OMPC != OMPC_unknown)
1357 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1358}
1359
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001360bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001361 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1362 // Return true if the current level is no longer enclosed in a target region.
1363
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001364 auto *VD = dyn_cast<VarDecl>(D);
1365 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001366 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1367 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001368}
1369
Alexey Bataeved09d242014-05-28 05:53:51 +00001370void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001371
1372void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1373 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001374 Scope *CurScope, SourceLocation Loc) {
1375 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001376 PushExpressionEvaluationContext(
1377 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001378}
1379
Alexey Bataevaac108a2015-06-23 04:51:00 +00001380void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1381 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001382}
1383
Alexey Bataevaac108a2015-06-23 04:51:00 +00001384void Sema::EndOpenMPClause() {
1385 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001386}
1387
Alexey Bataev758e55e2013-09-06 18:03:48 +00001388void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001389 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1390 // A variable of class type (or array thereof) that appears in a lastprivate
1391 // clause requires an accessible, unambiguous default constructor for the
1392 // class type, unless the list item is also specified in a firstprivate
1393 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001394 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001395 for (auto *C : D->clauses()) {
1396 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1397 SmallVector<Expr *, 8> PrivateCopies;
1398 for (auto *DE : Clause->varlists()) {
1399 if (DE->isValueDependent() || DE->isTypeDependent()) {
1400 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001401 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001402 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001403 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001404 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1405 QualType Type = VD->getType().getNonReferenceType();
1406 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001407 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001408 // Generate helper private variable and initialize it with the
1409 // default value. The address of the original variable is replaced
1410 // by the address of the new private variable in CodeGen. This new
1411 // variable is not added to IdResolver, so the code in the OpenMP
1412 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001413 auto *VDPrivate = buildVarDecl(
1414 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001415 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001416 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001417 if (VDPrivate->isInvalidDecl())
1418 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001419 PrivateCopies.push_back(buildDeclRefExpr(
1420 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001421 } else {
1422 // The variable is also a firstprivate, so initialization sequence
1423 // for private copy is generated already.
1424 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001425 }
1426 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001427 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001428 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001429 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001430 }
1431 }
1432 }
1433
Alexey Bataev758e55e2013-09-06 18:03:48 +00001434 DSAStack->pop();
1435 DiscardCleanupsInEvaluationContext();
1436 PopExpressionEvaluationContext();
1437}
1438
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001439static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1440 Expr *NumIterations, Sema &SemaRef,
1441 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001442
Alexey Bataeva769e072013-03-22 06:34:35 +00001443namespace {
1444
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001445class VarDeclFilterCCC : public CorrectionCandidateCallback {
1446private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001447 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001448
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001449public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001450 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001451 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001452 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001453 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001454 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001455 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1456 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001457 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001458 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001459 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001460};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001461
1462class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1463private:
1464 Sema &SemaRef;
1465
1466public:
1467 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1468 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1469 NamedDecl *ND = Candidate.getCorrectionDecl();
1470 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1471 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1472 SemaRef.getCurScope());
1473 }
1474 return false;
1475 }
1476};
1477
Alexey Bataeved09d242014-05-28 05:53:51 +00001478} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001479
1480ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1481 CXXScopeSpec &ScopeSpec,
1482 const DeclarationNameInfo &Id) {
1483 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1484 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1485
1486 if (Lookup.isAmbiguous())
1487 return ExprError();
1488
1489 VarDecl *VD;
1490 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001491 if (TypoCorrection Corrected = CorrectTypo(
1492 Id, LookupOrdinaryName, CurScope, nullptr,
1493 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001494 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001495 PDiag(Lookup.empty()
1496 ? diag::err_undeclared_var_use_suggest
1497 : diag::err_omp_expected_var_arg_suggest)
1498 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001499 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001500 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001501 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1502 : diag::err_omp_expected_var_arg)
1503 << Id.getName();
1504 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001505 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001506 } else {
1507 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001508 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001509 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1510 return ExprError();
1511 }
1512 }
1513 Lookup.suppressDiagnostics();
1514
1515 // OpenMP [2.9.2, Syntax, C/C++]
1516 // Variables must be file-scope, namespace-scope, or static block-scope.
1517 if (!VD->hasGlobalStorage()) {
1518 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001519 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1520 bool IsDecl =
1521 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001522 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001523 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1524 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001525 return ExprError();
1526 }
1527
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001528 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1529 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001530 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1531 // A threadprivate directive for file-scope variables must appear outside
1532 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001533 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1534 !getCurLexicalContext()->isTranslationUnit()) {
1535 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001536 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1537 bool IsDecl =
1538 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1539 Diag(VD->getLocation(),
1540 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1541 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001542 return ExprError();
1543 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001544 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1545 // A threadprivate directive for static class member variables must appear
1546 // in the class definition, in the same scope in which the member
1547 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001548 if (CanonicalVD->isStaticDataMember() &&
1549 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1550 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001551 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1552 bool IsDecl =
1553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1554 Diag(VD->getLocation(),
1555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1556 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001557 return ExprError();
1558 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001559 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1560 // A threadprivate directive for namespace-scope variables must appear
1561 // outside any definition or declaration other than the namespace
1562 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001563 if (CanonicalVD->getDeclContext()->isNamespace() &&
1564 (!getCurLexicalContext()->isFileContext() ||
1565 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1566 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001567 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1568 bool IsDecl =
1569 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1570 Diag(VD->getLocation(),
1571 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1572 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001573 return ExprError();
1574 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001575 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1576 // A threadprivate directive for static block-scope variables must appear
1577 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001578 if (CanonicalVD->isStaticLocal() && CurScope &&
1579 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001580 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001581 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1582 bool IsDecl =
1583 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1584 Diag(VD->getLocation(),
1585 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1586 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001587 return ExprError();
1588 }
1589
1590 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1591 // A threadprivate directive must lexically precede all references to any
1592 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001593 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001594 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001595 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001596 return ExprError();
1597 }
1598
1599 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001600 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1601 SourceLocation(), VD,
1602 /*RefersToEnclosingVariableOrCapture=*/false,
1603 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001604}
1605
Alexey Bataeved09d242014-05-28 05:53:51 +00001606Sema::DeclGroupPtrTy
1607Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1608 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001609 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001610 CurContext->addDecl(D);
1611 return DeclGroupPtrTy::make(DeclGroupRef(D));
1612 }
David Blaikie0403cb12016-01-15 23:43:25 +00001613 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001614}
1615
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001616namespace {
1617class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1618 Sema &SemaRef;
1619
1620public:
1621 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001622 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001623 if (VD->hasLocalStorage()) {
1624 SemaRef.Diag(E->getLocStart(),
1625 diag::err_omp_local_var_in_threadprivate_init)
1626 << E->getSourceRange();
1627 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1628 << VD << VD->getSourceRange();
1629 return true;
1630 }
1631 }
1632 return false;
1633 }
1634 bool VisitStmt(const Stmt *S) {
1635 for (auto Child : S->children()) {
1636 if (Child && Visit(Child))
1637 return true;
1638 }
1639 return false;
1640 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001641 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001642};
1643} // namespace
1644
Alexey Bataeved09d242014-05-28 05:53:51 +00001645OMPThreadPrivateDecl *
1646Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001647 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001648 for (auto &RefExpr : VarList) {
1649 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001650 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1651 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001652
Alexey Bataev376b4a42016-02-09 09:41:09 +00001653 // Mark variable as used.
1654 VD->setReferenced();
1655 VD->markUsed(Context);
1656
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001657 QualType QType = VD->getType();
1658 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1659 // It will be analyzed later.
1660 Vars.push_back(DE);
1661 continue;
1662 }
1663
Alexey Bataeva769e072013-03-22 06:34:35 +00001664 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1665 // A threadprivate variable must not have an incomplete type.
1666 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001667 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001668 continue;
1669 }
1670
1671 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1672 // A threadprivate variable must not have a reference type.
1673 if (VD->getType()->isReferenceType()) {
1674 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001675 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1676 bool IsDecl =
1677 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1678 Diag(VD->getLocation(),
1679 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1680 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001681 continue;
1682 }
1683
Samuel Antaof8b50122015-07-13 22:54:53 +00001684 // Check if this is a TLS variable. If TLS is not being supported, produce
1685 // the corresponding diagnostic.
1686 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1687 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1688 getLangOpts().OpenMPUseTLS &&
1689 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001690 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1691 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001692 Diag(ILoc, diag::err_omp_var_thread_local)
1693 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001694 bool IsDecl =
1695 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1696 Diag(VD->getLocation(),
1697 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1698 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001699 continue;
1700 }
1701
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001702 // Check if initial value of threadprivate variable reference variable with
1703 // local storage (it is not supported by runtime).
1704 if (auto Init = VD->getAnyInitializer()) {
1705 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001706 if (Checker.Visit(Init))
1707 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001708 }
1709
Alexey Bataeved09d242014-05-28 05:53:51 +00001710 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001711 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001712 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1713 Context, SourceRange(Loc, Loc)));
1714 if (auto *ML = Context.getASTMutationListener())
1715 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001716 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001717 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001718 if (!Vars.empty()) {
1719 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1720 Vars);
1721 D->setAccess(AS_public);
1722 }
1723 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001724}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001725
Alexey Bataev7ff55242014-06-19 09:13:45 +00001726static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001727 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001728 bool IsLoopIterVar = false) {
1729 if (DVar.RefExpr) {
1730 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1731 << getOpenMPClauseName(DVar.CKind);
1732 return;
1733 }
1734 enum {
1735 PDSA_StaticMemberShared,
1736 PDSA_StaticLocalVarShared,
1737 PDSA_LoopIterVarPrivate,
1738 PDSA_LoopIterVarLinear,
1739 PDSA_LoopIterVarLastprivate,
1740 PDSA_ConstVarShared,
1741 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001742 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001743 PDSA_LocalVarPrivate,
1744 PDSA_Implicit
1745 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001746 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001747 auto ReportLoc = D->getLocation();
1748 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001749 if (IsLoopIterVar) {
1750 if (DVar.CKind == OMPC_private)
1751 Reason = PDSA_LoopIterVarPrivate;
1752 else if (DVar.CKind == OMPC_lastprivate)
1753 Reason = PDSA_LoopIterVarLastprivate;
1754 else
1755 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001756 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1757 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001758 Reason = PDSA_TaskVarFirstprivate;
1759 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001760 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001761 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001762 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001763 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001764 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001765 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001766 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001767 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001768 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001769 ReportHint = true;
1770 Reason = PDSA_LocalVarPrivate;
1771 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001772 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001773 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001774 << Reason << ReportHint
1775 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1776 } else if (DVar.ImplicitDSALoc.isValid()) {
1777 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1778 << getOpenMPClauseName(DVar.CKind);
1779 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001780}
1781
Alexey Bataev758e55e2013-09-06 18:03:48 +00001782namespace {
1783class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1784 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001785 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001786 bool ErrorFound;
1787 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001788 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001789 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001790
Alexey Bataev758e55e2013-09-06 18:03:48 +00001791public:
1792 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001793 if (E->isTypeDependent() || E->isValueDependent() ||
1794 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1795 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001796 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001797 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001798 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1799 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001800
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001801 auto DVar = Stack->getTopDSA(VD, false);
1802 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001803 if (DVar.RefExpr)
1804 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001805
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001806 auto ELoc = E->getExprLoc();
1807 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001808 // The default(none) clause requires that each variable that is referenced
1809 // in the construct, and does not have a predetermined data-sharing
1810 // attribute, must have its data-sharing attribute explicitly determined
1811 // by being listed in a data-sharing attribute clause.
1812 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001813 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001814 VarsWithInheritedDSA.count(VD) == 0) {
1815 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001816 return;
1817 }
1818
1819 // OpenMP [2.9.3.6, Restrictions, p.2]
1820 // A list item that appears in a reduction clause of the innermost
1821 // enclosing worksharing or parallel construct may not be accessed in an
1822 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001823 DVar = Stack->hasInnermostDSA(
1824 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1825 [](OpenMPDirectiveKind K) -> bool {
1826 return isOpenMPParallelDirective(K) ||
1827 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1828 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001829 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001830 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001831 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001832 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1833 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001834 return;
1835 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001836
1837 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001838 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001839 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1840 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001841 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001842 }
1843 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001844 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001845 if (E->isTypeDependent() || E->isValueDependent() ||
1846 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1847 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001848 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1849 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1850 auto DVar = Stack->getTopDSA(FD, false);
1851 // Check if the variable has explicit DSA set and stop analysis if it
1852 // so.
1853 if (DVar.RefExpr)
1854 return;
1855
1856 auto ELoc = E->getExprLoc();
1857 auto DKind = Stack->getCurrentDirective();
1858 // OpenMP [2.9.3.6, Restrictions, p.2]
1859 // A list item that appears in a reduction clause of the innermost
1860 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001861 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001862 DVar = Stack->hasInnermostDSA(
1863 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1864 [](OpenMPDirectiveKind K) -> bool {
1865 return isOpenMPParallelDirective(K) ||
1866 isOpenMPWorksharingDirective(K) ||
1867 isOpenMPTeamsDirective(K);
1868 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001869 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001870 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001871 ErrorFound = true;
1872 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1873 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1874 return;
1875 }
1876
1877 // Define implicit data-sharing attributes for task.
1878 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001879 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1880 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001881 ImplicitFirstprivate.push_back(E);
1882 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001883 } else
1884 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001885 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001886 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001887 for (auto *C : S->clauses()) {
1888 // Skip analysis of arguments of implicitly defined firstprivate clause
1889 // for task directives.
1890 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1891 for (auto *CC : C->children()) {
1892 if (CC)
1893 Visit(CC);
1894 }
1895 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001896 }
1897 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001898 for (auto *C : S->children()) {
1899 if (C && !isa<OMPExecutableDirective>(C))
1900 Visit(C);
1901 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001902 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001903
1904 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001905 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001906 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001907 return VarsWithInheritedDSA;
1908 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001909
Alexey Bataev7ff55242014-06-19 09:13:45 +00001910 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1911 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001912};
Alexey Bataeved09d242014-05-28 05:53:51 +00001913} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001914
Alexey Bataevbae9a792014-06-27 10:37:06 +00001915void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001916 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001917 case OMPD_parallel:
1918 case OMPD_parallel_for:
1919 case OMPD_parallel_for_simd:
1920 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001921 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001922 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001923 QualType KmpInt32PtrTy =
1924 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001925 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001926 std::make_pair(".global_tid.", KmpInt32PtrTy),
1927 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1928 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001929 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001930 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1931 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001932 break;
1933 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001934 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001935 case OMPD_target_parallel: {
1936 Sema::CapturedParamNameType ParamsTarget[] = {
1937 std::make_pair(StringRef(), QualType()) // __context with shared vars
1938 };
1939 // Start a captured region for 'target' with no implicit parameters.
1940 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1941 ParamsTarget);
1942 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1943 QualType KmpInt32PtrTy =
1944 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001945 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001946 std::make_pair(".global_tid.", KmpInt32PtrTy),
1947 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1948 std::make_pair(StringRef(), QualType()) // __context with shared vars
1949 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001950 // Start a captured region for 'teams' or 'parallel'. Both regions have
1951 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001952 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001953 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001954 break;
1955 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001956 case OMPD_simd:
1957 case OMPD_for:
1958 case OMPD_for_simd:
1959 case OMPD_sections:
1960 case OMPD_section:
1961 case OMPD_single:
1962 case OMPD_master:
1963 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001964 case OMPD_taskgroup:
1965 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001966 case OMPD_ordered:
1967 case OMPD_atomic:
1968 case OMPD_target_data:
1969 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001970 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001971 case OMPD_target_parallel_for_simd:
1972 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001973 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001974 std::make_pair(StringRef(), QualType()) // __context with shared vars
1975 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001976 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1977 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001978 break;
1979 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001980 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001981 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001982 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1983 FunctionProtoType::ExtProtoInfo EPI;
1984 EPI.Variadic = true;
1985 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001986 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001987 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001988 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1989 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1990 std::make_pair(".copy_fn.",
1991 Context.getPointerType(CopyFnType).withConst()),
1992 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001993 std::make_pair(StringRef(), QualType()) // __context with shared vars
1994 };
1995 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1996 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001997 // Mark this captured region as inlined, because we don't use outlined
1998 // function directly.
1999 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2000 AlwaysInlineAttr::CreateImplicit(
2001 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002002 break;
2003 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002004 case OMPD_taskloop:
2005 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002006 QualType KmpInt32Ty =
2007 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2008 QualType KmpUInt64Ty =
2009 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2010 QualType KmpInt64Ty =
2011 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2012 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2013 FunctionProtoType::ExtProtoInfo EPI;
2014 EPI.Variadic = true;
2015 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002016 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002017 std::make_pair(".global_tid.", KmpInt32Ty),
2018 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2019 std::make_pair(".privates.",
2020 Context.VoidPtrTy.withConst().withRestrict()),
2021 std::make_pair(
2022 ".copy_fn.",
2023 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2024 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2025 std::make_pair(".lb.", KmpUInt64Ty),
2026 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2027 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002028 std::make_pair(".reductions.",
2029 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002030 std::make_pair(StringRef(), QualType()) // __context with shared vars
2031 };
2032 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2033 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002034 // Mark this captured region as inlined, because we don't use outlined
2035 // function directly.
2036 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2037 AlwaysInlineAttr::CreateImplicit(
2038 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002039 break;
2040 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002041 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002042 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002043 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00002044 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00002045 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002046 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00002047 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00002048 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002049 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002050 case OMPD_target_teams_distribute_parallel_for_simd:
2051 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002052 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2053 QualType KmpInt32PtrTy =
2054 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2055 Sema::CapturedParamNameType Params[] = {
2056 std::make_pair(".global_tid.", KmpInt32PtrTy),
2057 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2058 std::make_pair(".previous.lb.", Context.getSizeType()),
2059 std::make_pair(".previous.ub.", Context.getSizeType()),
2060 std::make_pair(StringRef(), QualType()) // __context with shared vars
2061 };
2062 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2063 Params);
2064 break;
2065 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002066 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002067 case OMPD_taskyield:
2068 case OMPD_barrier:
2069 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002070 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002071 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002072 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00002073 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00002074 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002075 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002076 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002077 case OMPD_declare_target:
2078 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00002079 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00002080 llvm_unreachable("OpenMP Directive is not allowed");
2081 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002082 llvm_unreachable("Unknown OpenMP directive");
2083 }
2084}
2085
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002086int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2087 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2088 getOpenMPCaptureRegions(CaptureRegions, DKind);
2089 return CaptureRegions.size();
2090}
2091
Alexey Bataev3392d762016-02-16 11:18:12 +00002092static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002093 Expr *CaptureExpr, bool WithInit,
2094 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002095 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002096 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002097 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002098 QualType Ty = Init->getType();
2099 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2100 if (S.getLangOpts().CPlusPlus)
2101 Ty = C.getLValueReferenceType(Ty);
2102 else {
2103 Ty = C.getPointerType(Ty);
2104 ExprResult Res =
2105 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2106 if (!Res.isUsable())
2107 return nullptr;
2108 Init = Res.get();
2109 }
Alexey Bataev61205072016-03-02 04:57:40 +00002110 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002111 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002112 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2113 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002114 if (!WithInit)
2115 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002116 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002117 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002118 return CED;
2119}
2120
Alexey Bataev61205072016-03-02 04:57:40 +00002121static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2122 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002123 OMPCapturedExprDecl *CD;
2124 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2125 CD = cast<OMPCapturedExprDecl>(VD);
2126 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002127 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2128 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002129 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002130 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002131}
2132
Alexey Bataev5a3af132016-03-29 08:58:54 +00002133static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2134 if (!Ref) {
2135 auto *CD =
2136 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2137 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2138 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2139 CaptureExpr->getExprLoc());
2140 }
2141 ExprResult Res = Ref;
2142 if (!S.getLangOpts().CPlusPlus &&
2143 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2144 Ref->getType()->isPointerType())
2145 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2146 if (!Res.isUsable())
2147 return ExprError();
2148 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002149}
2150
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002151namespace {
2152// OpenMP directives parsed in this section are represented as a
2153// CapturedStatement with an associated statement. If a syntax error
2154// is detected during the parsing of the associated statement, the
2155// compiler must abort processing and close the CapturedStatement.
2156//
2157// Combined directives such as 'target parallel' have more than one
2158// nested CapturedStatements. This RAII ensures that we unwind out
2159// of all the nested CapturedStatements when an error is found.
2160class CaptureRegionUnwinderRAII {
2161private:
2162 Sema &S;
2163 bool &ErrorFound;
2164 OpenMPDirectiveKind DKind;
2165
2166public:
2167 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2168 OpenMPDirectiveKind DKind)
2169 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2170 ~CaptureRegionUnwinderRAII() {
2171 if (ErrorFound) {
2172 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2173 while (--ThisCaptureLevel >= 0)
2174 S.ActOnCapturedRegionError();
2175 }
2176 }
2177};
2178} // namespace
2179
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002180StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2181 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002182 bool ErrorFound = false;
2183 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2184 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002185 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002186 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002187 return StmtError();
2188 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002189
2190 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002191 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002192 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002193 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002194 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002195 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002196 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2197 Clause->getClauseKind() == OMPC_in_reduction) {
2198 // Capture taskgroup task_reduction descriptors inside the tasking regions
2199 // with the corresponding in_reduction items.
2200 auto *IRC = cast<OMPInReductionClause>(Clause);
2201 for (auto *E : IRC->taskgroup_descriptors())
2202 if (E)
2203 MarkDeclarationsReferencedInExpr(E);
2204 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002205 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002206 Clause->getClauseKind() == OMPC_copyprivate ||
2207 (getLangOpts().OpenMPUseTLS &&
2208 getASTContext().getTargetInfo().isTLSSupported() &&
2209 Clause->getClauseKind() == OMPC_copyin)) {
2210 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002211 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002212 for (auto *VarRef : Clause->children()) {
2213 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002214 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002215 }
2216 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002217 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002218 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002219 if (auto *C = OMPClauseWithPreInit::get(Clause))
2220 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002221 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2222 if (auto *E = C->getPostUpdateExpr())
2223 MarkDeclarationsReferencedInExpr(E);
2224 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002225 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002226 if (Clause->getClauseKind() == OMPC_schedule)
2227 SC = cast<OMPScheduleClause>(Clause);
2228 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002229 OC = cast<OMPOrderedClause>(Clause);
2230 else if (Clause->getClauseKind() == OMPC_linear)
2231 LCs.push_back(cast<OMPLinearClause>(Clause));
2232 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002233 // OpenMP, 2.7.1 Loop Construct, Restrictions
2234 // The nonmonotonic modifier cannot be specified if an ordered clause is
2235 // specified.
2236 if (SC &&
2237 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2238 SC->getSecondScheduleModifier() ==
2239 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2240 OC) {
2241 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2242 ? SC->getFirstScheduleModifierLoc()
2243 : SC->getSecondScheduleModifierLoc(),
2244 diag::err_omp_schedule_nonmonotonic_ordered)
2245 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2246 ErrorFound = true;
2247 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002248 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2249 for (auto *C : LCs) {
2250 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2251 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2252 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002253 ErrorFound = true;
2254 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002255 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2256 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2257 OC->getNumForLoops()) {
2258 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2259 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2260 ErrorFound = true;
2261 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002262 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002263 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002264 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002265 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002266 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2267 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2268 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2269 // Mark all variables in private list clauses as used in inner region.
2270 // Required for proper codegen of combined directives.
2271 // TODO: add processing for other clauses.
2272 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2273 for (auto *C : PICs) {
2274 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2275 // Find the particular capture region for the clause if the
2276 // directive is a combined one with multiple capture regions.
2277 // If the directive is not a combined one, the capture region
2278 // associated with the clause is OMPD_unknown and is generated
2279 // only once.
2280 if (CaptureRegion == ThisCaptureRegion ||
2281 CaptureRegion == OMPD_unknown) {
2282 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2283 for (auto *D : DS->decls())
2284 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2285 }
2286 }
2287 }
2288 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002289 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002290 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002291 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002292}
2293
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002294static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2295 OpenMPDirectiveKind CancelRegion,
2296 SourceLocation StartLoc) {
2297 // CancelRegion is only needed for cancel and cancellation_point.
2298 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2299 return false;
2300
2301 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2302 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2303 return false;
2304
2305 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2306 << getOpenMPDirectiveName(CancelRegion);
2307 return true;
2308}
2309
2310static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002311 OpenMPDirectiveKind CurrentRegion,
2312 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002313 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002314 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002315 if (Stack->getCurScope()) {
2316 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002317 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002318 bool NestingProhibited = false;
2319 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002320 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002321 enum {
2322 NoRecommend,
2323 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002324 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002325 ShouldBeInTargetRegion,
2326 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002327 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002328 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002329 // OpenMP [2.16, Nesting of Regions]
2330 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002331 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002332 // An ordered construct with the simd clause is the only OpenMP
2333 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002334 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002335 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2336 // message.
2337 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2338 ? diag::err_omp_prohibited_region_simd
2339 : diag::warn_omp_nesting_simd);
2340 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002341 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002342 if (ParentRegion == OMPD_atomic) {
2343 // OpenMP [2.16, Nesting of Regions]
2344 // OpenMP constructs may not be nested inside an atomic region.
2345 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2346 return true;
2347 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002348 if (CurrentRegion == OMPD_section) {
2349 // OpenMP [2.7.2, sections Construct, Restrictions]
2350 // Orphaned section directives are prohibited. That is, the section
2351 // directives must appear within the sections construct and must not be
2352 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002353 if (ParentRegion != OMPD_sections &&
2354 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002355 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2356 << (ParentRegion != OMPD_unknown)
2357 << getOpenMPDirectiveName(ParentRegion);
2358 return true;
2359 }
2360 return false;
2361 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002362 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002363 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002364 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002365 if (ParentRegion == OMPD_unknown &&
2366 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002367 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002368 if (CurrentRegion == OMPD_cancellation_point ||
2369 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002370 // OpenMP [2.16, Nesting of Regions]
2371 // A cancellation point construct for which construct-type-clause is
2372 // taskgroup must be nested inside a task construct. A cancellation
2373 // point construct for which construct-type-clause is not taskgroup must
2374 // be closely nested inside an OpenMP construct that matches the type
2375 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002376 // A cancel construct for which construct-type-clause is taskgroup must be
2377 // nested inside a task construct. A cancel construct for which
2378 // construct-type-clause is not taskgroup must be closely nested inside an
2379 // OpenMP construct that matches the type specified in
2380 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002381 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002382 !((CancelRegion == OMPD_parallel &&
2383 (ParentRegion == OMPD_parallel ||
2384 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002385 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002386 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2387 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002388 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2389 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002390 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2391 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002392 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002393 // OpenMP [2.16, Nesting of Regions]
2394 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002395 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002396 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002397 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002398 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2399 // OpenMP [2.16, Nesting of Regions]
2400 // A critical region may not be nested (closely or otherwise) inside a
2401 // critical region with the same name. Note that this restriction is not
2402 // sufficient to prevent deadlock.
2403 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002404 bool DeadLock = Stack->hasDirective(
2405 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2406 const DeclarationNameInfo &DNI,
2407 SourceLocation Loc) -> bool {
2408 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2409 PreviousCriticalLoc = Loc;
2410 return true;
2411 } else
2412 return false;
2413 },
2414 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002415 if (DeadLock) {
2416 SemaRef.Diag(StartLoc,
2417 diag::err_omp_prohibited_region_critical_same_name)
2418 << CurrentName.getName();
2419 if (PreviousCriticalLoc.isValid())
2420 SemaRef.Diag(PreviousCriticalLoc,
2421 diag::note_omp_previous_critical_region);
2422 return true;
2423 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002424 } else if (CurrentRegion == OMPD_barrier) {
2425 // OpenMP [2.16, Nesting of Regions]
2426 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002427 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002428 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2429 isOpenMPTaskingDirective(ParentRegion) ||
2430 ParentRegion == OMPD_master ||
2431 ParentRegion == OMPD_critical ||
2432 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002433 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002434 !isOpenMPParallelDirective(CurrentRegion) &&
2435 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002436 // OpenMP [2.16, Nesting of Regions]
2437 // A worksharing region may not be closely nested inside a worksharing,
2438 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002439 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2440 isOpenMPTaskingDirective(ParentRegion) ||
2441 ParentRegion == OMPD_master ||
2442 ParentRegion == OMPD_critical ||
2443 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002444 Recommend = ShouldBeInParallelRegion;
2445 } else if (CurrentRegion == OMPD_ordered) {
2446 // OpenMP [2.16, Nesting of Regions]
2447 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002448 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002449 // An ordered region must be closely nested inside a loop region (or
2450 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002451 // OpenMP [2.8.1,simd Construct, Restrictions]
2452 // An ordered construct with the simd clause is the only OpenMP construct
2453 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002454 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002455 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002456 !(isOpenMPSimdDirective(ParentRegion) ||
2457 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002458 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002459 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002460 // OpenMP [2.16, Nesting of Regions]
2461 // If specified, a teams construct must be contained within a target
2462 // construct.
2463 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002464 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002465 Recommend = ShouldBeInTargetRegion;
2466 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2467 }
Kelvin Libf594a52016-12-17 05:48:59 +00002468 if (!NestingProhibited &&
2469 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2470 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2471 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002472 // OpenMP [2.16, Nesting of Regions]
2473 // distribute, parallel, parallel sections, parallel workshare, and the
2474 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2475 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002476 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2477 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002478 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002479 }
David Majnemer9d168222016-08-05 17:44:54 +00002480 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002481 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002482 // OpenMP 4.5 [2.17 Nesting of Regions]
2483 // The region associated with the distribute construct must be strictly
2484 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002485 NestingProhibited =
2486 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002487 Recommend = ShouldBeInTeamsRegion;
2488 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002489 if (!NestingProhibited &&
2490 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2491 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2492 // OpenMP 4.5 [2.17 Nesting of Regions]
2493 // If a target, target update, target data, target enter data, or
2494 // target exit data construct is encountered during execution of a
2495 // target region, the behavior is unspecified.
2496 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002497 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2498 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002499 if (isOpenMPTargetExecutionDirective(K)) {
2500 OffendingRegion = K;
2501 return true;
2502 } else
2503 return false;
2504 },
2505 false /* don't skip top directive */);
2506 CloseNesting = false;
2507 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002508 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002509 if (OrphanSeen) {
2510 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2511 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2512 } else {
2513 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2514 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2515 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2516 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002517 return true;
2518 }
2519 }
2520 return false;
2521}
2522
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002523static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2524 ArrayRef<OMPClause *> Clauses,
2525 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2526 bool ErrorFound = false;
2527 unsigned NamedModifiersNumber = 0;
2528 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2529 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002530 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002531 for (const auto *C : Clauses) {
2532 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2533 // At most one if clause without a directive-name-modifier can appear on
2534 // the directive.
2535 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2536 if (FoundNameModifiers[CurNM]) {
2537 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2538 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2539 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2540 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002541 } else if (CurNM != OMPD_unknown) {
2542 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002543 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002544 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002545 FoundNameModifiers[CurNM] = IC;
2546 if (CurNM == OMPD_unknown)
2547 continue;
2548 // Check if the specified name modifier is allowed for the current
2549 // directive.
2550 // At most one if clause with the particular directive-name-modifier can
2551 // appear on the directive.
2552 bool MatchFound = false;
2553 for (auto NM : AllowedNameModifiers) {
2554 if (CurNM == NM) {
2555 MatchFound = true;
2556 break;
2557 }
2558 }
2559 if (!MatchFound) {
2560 S.Diag(IC->getNameModifierLoc(),
2561 diag::err_omp_wrong_if_directive_name_modifier)
2562 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2563 ErrorFound = true;
2564 }
2565 }
2566 }
2567 // If any if clause on the directive includes a directive-name-modifier then
2568 // all if clauses on the directive must include a directive-name-modifier.
2569 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2570 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2571 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2572 diag::err_omp_no_more_if_clause);
2573 } else {
2574 std::string Values;
2575 std::string Sep(", ");
2576 unsigned AllowedCnt = 0;
2577 unsigned TotalAllowedNum =
2578 AllowedNameModifiers.size() - NamedModifiersNumber;
2579 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2580 ++Cnt) {
2581 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2582 if (!FoundNameModifiers[NM]) {
2583 Values += "'";
2584 Values += getOpenMPDirectiveName(NM);
2585 Values += "'";
2586 if (AllowedCnt + 2 == TotalAllowedNum)
2587 Values += " or ";
2588 else if (AllowedCnt + 1 != TotalAllowedNum)
2589 Values += Sep;
2590 ++AllowedCnt;
2591 }
2592 }
2593 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2594 diag::err_omp_unnamed_if_clause)
2595 << (TotalAllowedNum > 1) << Values;
2596 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002597 for (auto Loc : NameModifierLoc) {
2598 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2599 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002600 ErrorFound = true;
2601 }
2602 return ErrorFound;
2603}
2604
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002605StmtResult Sema::ActOnOpenMPExecutableDirective(
2606 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2607 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2608 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002609 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002610 // First check CancelRegion which is then used in checkNestingOfRegions.
2611 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2612 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002613 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002614 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002615
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002616 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002617 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002618 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002619 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002620 if (AStmt) {
2621 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2622
2623 // Check default data sharing attributes for referenced variables.
2624 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002625 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2626 Stmt *S = AStmt;
2627 while (--ThisCaptureLevel >= 0)
2628 S = cast<CapturedStmt>(S)->getCapturedStmt();
2629 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002630 if (DSAChecker.isErrorFound())
2631 return StmtError();
2632 // Generate list of implicitly defined firstprivate variables.
2633 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002634
Alexey Bataev88202be2017-07-27 13:20:36 +00002635 SmallVector<Expr *, 4> ImplicitFirstprivates(
2636 DSAChecker.getImplicitFirstprivate().begin(),
2637 DSAChecker.getImplicitFirstprivate().end());
2638 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2639 for (auto *C : Clauses) {
2640 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2641 for (auto *E : IRC->taskgroup_descriptors())
2642 if (E)
2643 ImplicitFirstprivates.emplace_back(E);
2644 }
2645 }
2646 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002647 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002648 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2649 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002650 ClausesWithImplicit.push_back(Implicit);
2651 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002652 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002653 } else
2654 ErrorFound = true;
2655 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002656 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002657
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002658 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002659 switch (Kind) {
2660 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002661 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2662 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002663 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002664 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002665 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002666 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2667 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002668 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002669 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002670 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2671 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002672 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002673 case OMPD_for_simd:
2674 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2675 EndLoc, VarsWithInheritedDSA);
2676 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002677 case OMPD_sections:
2678 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2679 EndLoc);
2680 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002681 case OMPD_section:
2682 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002683 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002684 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2685 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002686 case OMPD_single:
2687 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2688 EndLoc);
2689 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002690 case OMPD_master:
2691 assert(ClausesWithImplicit.empty() &&
2692 "No clauses are allowed for 'omp master' directive");
2693 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2694 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002695 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002696 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2697 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002698 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002699 case OMPD_parallel_for:
2700 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2701 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002702 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002703 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002704 case OMPD_parallel_for_simd:
2705 Res = ActOnOpenMPParallelForSimdDirective(
2706 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002707 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002708 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002709 case OMPD_parallel_sections:
2710 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2711 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002712 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002713 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002714 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002715 Res =
2716 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002717 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002718 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002719 case OMPD_taskyield:
2720 assert(ClausesWithImplicit.empty() &&
2721 "No clauses are allowed for 'omp taskyield' directive");
2722 assert(AStmt == nullptr &&
2723 "No associated statement allowed for 'omp taskyield' directive");
2724 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2725 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002726 case OMPD_barrier:
2727 assert(ClausesWithImplicit.empty() &&
2728 "No clauses are allowed for 'omp barrier' directive");
2729 assert(AStmt == nullptr &&
2730 "No associated statement allowed for 'omp barrier' directive");
2731 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2732 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002733 case OMPD_taskwait:
2734 assert(ClausesWithImplicit.empty() &&
2735 "No clauses are allowed for 'omp taskwait' directive");
2736 assert(AStmt == nullptr &&
2737 "No associated statement allowed for 'omp taskwait' directive");
2738 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2739 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002740 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002741 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2742 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002743 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002744 case OMPD_flush:
2745 assert(AStmt == nullptr &&
2746 "No associated statement allowed for 'omp flush' directive");
2747 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2748 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002749 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002750 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2751 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002752 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002753 case OMPD_atomic:
2754 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2755 EndLoc);
2756 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002757 case OMPD_teams:
2758 Res =
2759 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2760 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002761 case OMPD_target:
2762 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2763 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002764 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002765 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002766 case OMPD_target_parallel:
2767 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2768 StartLoc, EndLoc);
2769 AllowedNameModifiers.push_back(OMPD_target);
2770 AllowedNameModifiers.push_back(OMPD_parallel);
2771 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002772 case OMPD_target_parallel_for:
2773 Res = ActOnOpenMPTargetParallelForDirective(
2774 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2775 AllowedNameModifiers.push_back(OMPD_target);
2776 AllowedNameModifiers.push_back(OMPD_parallel);
2777 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002778 case OMPD_cancellation_point:
2779 assert(ClausesWithImplicit.empty() &&
2780 "No clauses are allowed for 'omp cancellation point' directive");
2781 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2782 "cancellation point' directive");
2783 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2784 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002785 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002786 assert(AStmt == nullptr &&
2787 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002788 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2789 CancelRegion);
2790 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002791 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002792 case OMPD_target_data:
2793 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2794 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002795 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002796 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002797 case OMPD_target_enter_data:
2798 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2799 EndLoc);
2800 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2801 break;
Samuel Antao72590762016-01-19 20:04:50 +00002802 case OMPD_target_exit_data:
2803 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2804 EndLoc);
2805 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2806 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002807 case OMPD_taskloop:
2808 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2809 EndLoc, VarsWithInheritedDSA);
2810 AllowedNameModifiers.push_back(OMPD_taskloop);
2811 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002812 case OMPD_taskloop_simd:
2813 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2814 EndLoc, VarsWithInheritedDSA);
2815 AllowedNameModifiers.push_back(OMPD_taskloop);
2816 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002817 case OMPD_distribute:
2818 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2819 EndLoc, VarsWithInheritedDSA);
2820 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002821 case OMPD_target_update:
2822 assert(!AStmt && "Statement is not allowed for target update");
2823 Res =
2824 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2825 AllowedNameModifiers.push_back(OMPD_target_update);
2826 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002827 case OMPD_distribute_parallel_for:
2828 Res = ActOnOpenMPDistributeParallelForDirective(
2829 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2830 AllowedNameModifiers.push_back(OMPD_parallel);
2831 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002832 case OMPD_distribute_parallel_for_simd:
2833 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2834 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2835 AllowedNameModifiers.push_back(OMPD_parallel);
2836 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002837 case OMPD_distribute_simd:
2838 Res = ActOnOpenMPDistributeSimdDirective(
2839 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2840 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002841 case OMPD_target_parallel_for_simd:
2842 Res = ActOnOpenMPTargetParallelForSimdDirective(
2843 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2844 AllowedNameModifiers.push_back(OMPD_target);
2845 AllowedNameModifiers.push_back(OMPD_parallel);
2846 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002847 case OMPD_target_simd:
2848 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2849 EndLoc, VarsWithInheritedDSA);
2850 AllowedNameModifiers.push_back(OMPD_target);
2851 break;
Kelvin Li02532872016-08-05 14:37:37 +00002852 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002853 Res = ActOnOpenMPTeamsDistributeDirective(
2854 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002855 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002856 case OMPD_teams_distribute_simd:
2857 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2858 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2859 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002860 case OMPD_teams_distribute_parallel_for_simd:
2861 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2862 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2863 AllowedNameModifiers.push_back(OMPD_parallel);
2864 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002865 case OMPD_teams_distribute_parallel_for:
2866 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2867 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2868 AllowedNameModifiers.push_back(OMPD_parallel);
2869 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002870 case OMPD_target_teams:
2871 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2872 EndLoc);
2873 AllowedNameModifiers.push_back(OMPD_target);
2874 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002875 case OMPD_target_teams_distribute:
2876 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2877 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2878 AllowedNameModifiers.push_back(OMPD_target);
2879 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002880 case OMPD_target_teams_distribute_parallel_for:
2881 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2882 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2883 AllowedNameModifiers.push_back(OMPD_target);
2884 AllowedNameModifiers.push_back(OMPD_parallel);
2885 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002886 case OMPD_target_teams_distribute_parallel_for_simd:
2887 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2888 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2889 AllowedNameModifiers.push_back(OMPD_target);
2890 AllowedNameModifiers.push_back(OMPD_parallel);
2891 break;
Kelvin Lida681182017-01-10 18:08:18 +00002892 case OMPD_target_teams_distribute_simd:
2893 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2894 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2895 AllowedNameModifiers.push_back(OMPD_target);
2896 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002897 case OMPD_declare_target:
2898 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002899 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002900 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002901 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002902 llvm_unreachable("OpenMP Directive is not allowed");
2903 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002904 llvm_unreachable("Unknown OpenMP directive");
2905 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002906
Alexey Bataev4acb8592014-07-07 13:01:15 +00002907 for (auto P : VarsWithInheritedDSA) {
2908 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2909 << P.first << P.second->getSourceRange();
2910 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002911 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2912
2913 if (!AllowedNameModifiers.empty())
2914 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2915 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002916
Alexey Bataeved09d242014-05-28 05:53:51 +00002917 if (ErrorFound)
2918 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002919 return Res;
2920}
2921
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002922Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2923 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002924 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002925 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2926 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002927 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002928 assert(Linears.size() == LinModifiers.size());
2929 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002930 if (!DG || DG.get().isNull())
2931 return DeclGroupPtrTy();
2932
2933 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002934 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002935 return DG;
2936 }
2937 auto *ADecl = DG.get().getSingleDecl();
2938 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2939 ADecl = FTD->getTemplatedDecl();
2940
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002941 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2942 if (!FD) {
2943 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002944 return DeclGroupPtrTy();
2945 }
2946
Alexey Bataev2af33e32016-04-07 12:45:37 +00002947 // OpenMP [2.8.2, declare simd construct, Description]
2948 // The parameter of the simdlen clause must be a constant positive integer
2949 // expression.
2950 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002951 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002952 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002953 // OpenMP [2.8.2, declare simd construct, Description]
2954 // The special this pointer can be used as if was one of the arguments to the
2955 // function in any of the linear, aligned, or uniform clauses.
2956 // The uniform clause declares one or more arguments to have an invariant
2957 // value for all concurrent invocations of the function in the execution of a
2958 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002959 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2960 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002961 for (auto *E : Uniforms) {
2962 E = E->IgnoreParenImpCasts();
2963 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2964 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2965 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2966 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002967 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2968 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002969 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002970 }
2971 if (isa<CXXThisExpr>(E)) {
2972 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002973 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002974 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002975 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2976 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002977 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002978 // OpenMP [2.8.2, declare simd construct, Description]
2979 // The aligned clause declares that the object to which each list item points
2980 // is aligned to the number of bytes expressed in the optional parameter of
2981 // the aligned clause.
2982 // The special this pointer can be used as if was one of the arguments to the
2983 // function in any of the linear, aligned, or uniform clauses.
2984 // The type of list items appearing in the aligned clause must be array,
2985 // pointer, reference to array, or reference to pointer.
2986 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2987 Expr *AlignedThis = nullptr;
2988 for (auto *E : Aligneds) {
2989 E = E->IgnoreParenImpCasts();
2990 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2991 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2992 auto *CanonPVD = PVD->getCanonicalDecl();
2993 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2994 FD->getParamDecl(PVD->getFunctionScopeIndex())
2995 ->getCanonicalDecl() == CanonPVD) {
2996 // OpenMP [2.8.1, simd construct, Restrictions]
2997 // A list-item cannot appear in more than one aligned clause.
2998 if (AlignedArgs.count(CanonPVD) > 0) {
2999 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3000 << 1 << E->getSourceRange();
3001 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3002 diag::note_omp_explicit_dsa)
3003 << getOpenMPClauseName(OMPC_aligned);
3004 continue;
3005 }
3006 AlignedArgs[CanonPVD] = E;
3007 QualType QTy = PVD->getType()
3008 .getNonReferenceType()
3009 .getUnqualifiedType()
3010 .getCanonicalType();
3011 const Type *Ty = QTy.getTypePtrOrNull();
3012 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3013 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3014 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3015 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3016 }
3017 continue;
3018 }
3019 }
3020 if (isa<CXXThisExpr>(E)) {
3021 if (AlignedThis) {
3022 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3023 << 2 << E->getSourceRange();
3024 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3025 << getOpenMPClauseName(OMPC_aligned);
3026 }
3027 AlignedThis = E;
3028 continue;
3029 }
3030 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3031 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3032 }
3033 // The optional parameter of the aligned clause, alignment, must be a constant
3034 // positive integer expression. If no optional parameter is specified,
3035 // implementation-defined default alignments for SIMD instructions on the
3036 // target platforms are assumed.
3037 SmallVector<Expr *, 4> NewAligns;
3038 for (auto *E : Alignments) {
3039 ExprResult Align;
3040 if (E)
3041 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3042 NewAligns.push_back(Align.get());
3043 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003044 // OpenMP [2.8.2, declare simd construct, Description]
3045 // The linear clause declares one or more list items to be private to a SIMD
3046 // lane and to have a linear relationship with respect to the iteration space
3047 // of a loop.
3048 // The special this pointer can be used as if was one of the arguments to the
3049 // function in any of the linear, aligned, or uniform clauses.
3050 // When a linear-step expression is specified in a linear clause it must be
3051 // either a constant integer expression or an integer-typed parameter that is
3052 // specified in a uniform clause on the directive.
3053 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3054 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3055 auto MI = LinModifiers.begin();
3056 for (auto *E : Linears) {
3057 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3058 ++MI;
3059 E = E->IgnoreParenImpCasts();
3060 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3061 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3062 auto *CanonPVD = PVD->getCanonicalDecl();
3063 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3064 FD->getParamDecl(PVD->getFunctionScopeIndex())
3065 ->getCanonicalDecl() == CanonPVD) {
3066 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3067 // A list-item cannot appear in more than one linear clause.
3068 if (LinearArgs.count(CanonPVD) > 0) {
3069 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3070 << getOpenMPClauseName(OMPC_linear)
3071 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3072 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3073 diag::note_omp_explicit_dsa)
3074 << getOpenMPClauseName(OMPC_linear);
3075 continue;
3076 }
3077 // Each argument can appear in at most one uniform or linear clause.
3078 if (UniformedArgs.count(CanonPVD) > 0) {
3079 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3080 << getOpenMPClauseName(OMPC_linear)
3081 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3082 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3083 diag::note_omp_explicit_dsa)
3084 << getOpenMPClauseName(OMPC_uniform);
3085 continue;
3086 }
3087 LinearArgs[CanonPVD] = E;
3088 if (E->isValueDependent() || E->isTypeDependent() ||
3089 E->isInstantiationDependent() ||
3090 E->containsUnexpandedParameterPack())
3091 continue;
3092 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3093 PVD->getOriginalType());
3094 continue;
3095 }
3096 }
3097 if (isa<CXXThisExpr>(E)) {
3098 if (UniformedLinearThis) {
3099 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3100 << getOpenMPClauseName(OMPC_linear)
3101 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3102 << E->getSourceRange();
3103 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3104 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3105 : OMPC_linear);
3106 continue;
3107 }
3108 UniformedLinearThis = E;
3109 if (E->isValueDependent() || E->isTypeDependent() ||
3110 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3111 continue;
3112 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3113 E->getType());
3114 continue;
3115 }
3116 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3117 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3118 }
3119 Expr *Step = nullptr;
3120 Expr *NewStep = nullptr;
3121 SmallVector<Expr *, 4> NewSteps;
3122 for (auto *E : Steps) {
3123 // Skip the same step expression, it was checked already.
3124 if (Step == E || !E) {
3125 NewSteps.push_back(E ? NewStep : nullptr);
3126 continue;
3127 }
3128 Step = E;
3129 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3130 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3131 auto *CanonPVD = PVD->getCanonicalDecl();
3132 if (UniformedArgs.count(CanonPVD) == 0) {
3133 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3134 << Step->getSourceRange();
3135 } else if (E->isValueDependent() || E->isTypeDependent() ||
3136 E->isInstantiationDependent() ||
3137 E->containsUnexpandedParameterPack() ||
3138 CanonPVD->getType()->hasIntegerRepresentation())
3139 NewSteps.push_back(Step);
3140 else {
3141 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3142 << Step->getSourceRange();
3143 }
3144 continue;
3145 }
3146 NewStep = Step;
3147 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3148 !Step->isInstantiationDependent() &&
3149 !Step->containsUnexpandedParameterPack()) {
3150 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3151 .get();
3152 if (NewStep)
3153 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3154 }
3155 NewSteps.push_back(NewStep);
3156 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003157 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3158 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003159 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003160 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3161 const_cast<Expr **>(Linears.data()), Linears.size(),
3162 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3163 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003164 ADecl->addAttr(NewAttr);
3165 return ConvertDeclToDeclGroup(ADecl);
3166}
3167
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003168StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3169 Stmt *AStmt,
3170 SourceLocation StartLoc,
3171 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003172 if (!AStmt)
3173 return StmtError();
3174
Alexey Bataev9959db52014-05-06 10:08:46 +00003175 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3176 // 1.2.2 OpenMP Language Terminology
3177 // Structured block - An executable statement with a single entry at the
3178 // top and a single exit at the bottom.
3179 // The point of exit cannot be a branch out of the structured block.
3180 // longjmp() and throw() must not violate the entry/exit criteria.
3181 CS->getCapturedDecl()->setNothrow();
3182
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003183 getCurFunction()->setHasBranchProtectedScope();
3184
Alexey Bataev25e5b442015-09-15 12:52:43 +00003185 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3186 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003187}
3188
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003189namespace {
3190/// \brief Helper class for checking canonical form of the OpenMP loops and
3191/// extracting iteration space of each loop in the loop nest, that will be used
3192/// for IR generation.
3193class OpenMPIterationSpaceChecker {
3194 /// \brief Reference to Sema.
3195 Sema &SemaRef;
3196 /// \brief A location for diagnostics (when there is no some better location).
3197 SourceLocation DefaultLoc;
3198 /// \brief A location for diagnostics (when increment is not compatible).
3199 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003200 /// \brief A source location for referring to loop init later.
3201 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003202 /// \brief A source location for referring to condition later.
3203 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003204 /// \brief A source location for referring to increment later.
3205 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003206 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003207 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003208 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003209 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003210 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003211 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003212 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003213 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003214 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003215 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003216 /// \brief This flag is true when condition is one of:
3217 /// Var < UB
3218 /// Var <= UB
3219 /// UB > Var
3220 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003221 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003222 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003223 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003224 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003225 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003226
3227public:
3228 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003229 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003230 /// \brief Check init-expr for canonical loop form and save loop counter
3231 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003232 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003233 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3234 /// for less/greater and for strict/non-strict comparison.
3235 bool CheckCond(Expr *S);
3236 /// \brief Check incr-expr for canonical loop form and return true if it
3237 /// does not conform, otherwise save loop step (#Step).
3238 bool CheckInc(Expr *S);
3239 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003240 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003241 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003242 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003243 /// \brief Source range of the loop init.
3244 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3245 /// \brief Source range of the loop condition.
3246 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3247 /// \brief Source range of the loop increment.
3248 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3249 /// \brief True if the step should be subtracted.
3250 bool ShouldSubtractStep() const { return SubtractStep; }
3251 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003252 Expr *
3253 BuildNumIterations(Scope *S, const bool LimitedType,
3254 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003255 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003256 Expr *BuildPreCond(Scope *S, Expr *Cond,
3257 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003258 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003259 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3260 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003261 /// \brief Build reference expression to the private counter be used for
3262 /// codegen.
3263 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003264 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003265 Expr *BuildCounterInit() const;
3266 /// \brief Build step of the counter be used for codegen.
3267 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003268 /// \brief Return true if any expression is dependent.
3269 bool Dependent() const;
3270
3271private:
3272 /// \brief Check the right-hand side of an assignment in the increment
3273 /// expression.
3274 bool CheckIncRHS(Expr *RHS);
3275 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003276 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003277 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003278 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003279 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003280 /// \brief Helper to set loop increment.
3281 bool SetStep(Expr *NewStep, bool Subtract);
3282};
3283
3284bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003285 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003286 assert(!LB && !UB && !Step);
3287 return false;
3288 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003289 return LCDecl->getType()->isDependentType() ||
3290 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3291 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003292}
3293
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003294bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3295 Expr *NewLCRefExpr,
3296 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003297 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003298 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003299 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003300 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003301 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003302 LCDecl = getCanonicalDecl(NewLCDecl);
3303 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003304 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3305 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003306 if ((Ctor->isCopyOrMoveConstructor() ||
3307 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3308 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003309 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003310 LB = NewLB;
3311 return false;
3312}
3313
3314bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003315 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003316 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003317 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3318 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003319 if (!NewUB)
3320 return true;
3321 UB = NewUB;
3322 TestIsLessOp = LessOp;
3323 TestIsStrictOp = StrictOp;
3324 ConditionSrcRange = SR;
3325 ConditionLoc = SL;
3326 return false;
3327}
3328
3329bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3330 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003331 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003332 if (!NewStep)
3333 return true;
3334 if (!NewStep->isValueDependent()) {
3335 // Check that the step is integer expression.
3336 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003337 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3338 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003339 if (Val.isInvalid())
3340 return true;
3341 NewStep = Val.get();
3342
3343 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3344 // If test-expr is of form var relational-op b and relational-op is < or
3345 // <= then incr-expr must cause var to increase on each iteration of the
3346 // loop. If test-expr is of form var relational-op b and relational-op is
3347 // > or >= then incr-expr must cause var to decrease on each iteration of
3348 // the loop.
3349 // If test-expr is of form b relational-op var and relational-op is < or
3350 // <= then incr-expr must cause var to decrease on each iteration of the
3351 // loop. If test-expr is of form b relational-op var and relational-op is
3352 // > or >= then incr-expr must cause var to increase on each iteration of
3353 // the loop.
3354 llvm::APSInt Result;
3355 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3356 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3357 bool IsConstNeg =
3358 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003359 bool IsConstPos =
3360 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003361 bool IsConstZero = IsConstant && !Result.getBoolValue();
3362 if (UB && (IsConstZero ||
3363 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003364 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003365 SemaRef.Diag(NewStep->getExprLoc(),
3366 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003367 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003368 SemaRef.Diag(ConditionLoc,
3369 diag::note_omp_loop_cond_requres_compatible_incr)
3370 << TestIsLessOp << ConditionSrcRange;
3371 return true;
3372 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003373 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003374 NewStep =
3375 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3376 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003377 Subtract = !Subtract;
3378 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003379 }
3380
3381 Step = NewStep;
3382 SubtractStep = Subtract;
3383 return false;
3384}
3385
Alexey Bataev9c821032015-04-30 04:23:23 +00003386bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003387 // Check init-expr for canonical loop form and save loop counter
3388 // variable - #Var and its initialization value - #LB.
3389 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3390 // var = lb
3391 // integer-type var = lb
3392 // random-access-iterator-type var = lb
3393 // pointer-type var = lb
3394 //
3395 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003396 if (EmitDiags) {
3397 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3398 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003399 return true;
3400 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003401 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3402 if (!ExprTemp->cleanupsHaveSideEffects())
3403 S = ExprTemp->getSubExpr();
3404
Alexander Musmana5f070a2014-10-01 06:03:56 +00003405 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003406 if (Expr *E = dyn_cast<Expr>(S))
3407 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003408 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003409 if (BO->getOpcode() == BO_Assign) {
3410 auto *LHS = BO->getLHS()->IgnoreParens();
3411 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3412 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3413 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3414 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3415 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3416 }
3417 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3418 if (ME->isArrow() &&
3419 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3420 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3421 }
3422 }
David Majnemer9d168222016-08-05 17:44:54 +00003423 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003424 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003425 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003426 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003427 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003428 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003429 SemaRef.Diag(S->getLocStart(),
3430 diag::ext_omp_loop_not_canonical_init)
3431 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003432 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003433 }
3434 }
3435 }
David Majnemer9d168222016-08-05 17:44:54 +00003436 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003437 if (CE->getOperator() == OO_Equal) {
3438 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003439 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003440 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3441 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3442 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3443 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3444 }
3445 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3446 if (ME->isArrow() &&
3447 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3448 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3449 }
3450 }
3451 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003453 if (Dependent() || SemaRef.CurContext->isDependentContext())
3454 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003455 if (EmitDiags) {
3456 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3457 << S->getSourceRange();
3458 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003459 return true;
3460}
3461
Alexey Bataev23b69422014-06-18 07:08:49 +00003462/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003463/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003464static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003465 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003466 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003467 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003468 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3469 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003470 if ((Ctor->isCopyOrMoveConstructor() ||
3471 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3472 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003473 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003474 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003475 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003476 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003477 }
3478 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3479 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3480 return getCanonicalDecl(ME->getMemberDecl());
3481 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003482}
3483
3484bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3485 // Check test-expr for canonical form, save upper-bound UB, flags for
3486 // less/greater and for strict/non-strict comparison.
3487 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3488 // var relational-op b
3489 // b relational-op var
3490 //
3491 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003492 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003493 return true;
3494 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003495 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003496 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003497 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003498 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003499 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003500 return SetUB(BO->getRHS(),
3501 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3502 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3503 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003504 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003505 return SetUB(BO->getLHS(),
3506 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3507 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3508 BO->getSourceRange(), BO->getOperatorLoc());
3509 }
David Majnemer9d168222016-08-05 17:44:54 +00003510 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003511 if (CE->getNumArgs() == 2) {
3512 auto Op = CE->getOperator();
3513 switch (Op) {
3514 case OO_Greater:
3515 case OO_GreaterEqual:
3516 case OO_Less:
3517 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003518 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003519 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3520 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3521 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003522 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003523 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3524 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3525 CE->getOperatorLoc());
3526 break;
3527 default:
3528 break;
3529 }
3530 }
3531 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003532 if (Dependent() || SemaRef.CurContext->isDependentContext())
3533 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003534 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003535 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003536 return true;
3537}
3538
3539bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3540 // RHS of canonical loop form increment can be:
3541 // var + incr
3542 // incr + var
3543 // var - incr
3544 //
3545 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003546 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003547 if (BO->isAdditiveOp()) {
3548 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003549 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003550 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003551 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003552 return SetStep(BO->getLHS(), false);
3553 }
David Majnemer9d168222016-08-05 17:44:54 +00003554 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003555 bool IsAdd = CE->getOperator() == OO_Plus;
3556 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003557 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003558 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003559 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003560 return SetStep(CE->getArg(0), false);
3561 }
3562 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003563 if (Dependent() || SemaRef.CurContext->isDependentContext())
3564 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003565 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003566 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003567 return true;
3568}
3569
3570bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3571 // Check incr-expr for canonical loop form and return true if it
3572 // does not conform.
3573 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3574 // ++var
3575 // var++
3576 // --var
3577 // var--
3578 // var += incr
3579 // var -= incr
3580 // var = var + incr
3581 // var = incr + var
3582 // var = var - incr
3583 //
3584 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003585 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003586 return true;
3587 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003588 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3589 if (!ExprTemp->cleanupsHaveSideEffects())
3590 S = ExprTemp->getSubExpr();
3591
Alexander Musmana5f070a2014-10-01 06:03:56 +00003592 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003593 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003594 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003595 if (UO->isIncrementDecrementOp() &&
3596 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003597 return SetStep(SemaRef
3598 .ActOnIntegerConstant(UO->getLocStart(),
3599 (UO->isDecrementOp() ? -1 : 1))
3600 .get(),
3601 false);
3602 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003603 switch (BO->getOpcode()) {
3604 case BO_AddAssign:
3605 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003606 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003607 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3608 break;
3609 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003610 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003611 return CheckIncRHS(BO->getRHS());
3612 break;
3613 default:
3614 break;
3615 }
David Majnemer9d168222016-08-05 17:44:54 +00003616 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003617 switch (CE->getOperator()) {
3618 case OO_PlusPlus:
3619 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003620 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003621 return SetStep(SemaRef
3622 .ActOnIntegerConstant(
3623 CE->getLocStart(),
3624 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3625 .get(),
3626 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003627 break;
3628 case OO_PlusEqual:
3629 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003630 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003631 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3632 break;
3633 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003634 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003635 return CheckIncRHS(CE->getArg(1));
3636 break;
3637 default:
3638 break;
3639 }
3640 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003641 if (Dependent() || SemaRef.CurContext->isDependentContext())
3642 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003643 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003644 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003645 return true;
3646}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003647
Alexey Bataev5a3af132016-03-29 08:58:54 +00003648static ExprResult
3649tryBuildCapture(Sema &SemaRef, Expr *Capture,
3650 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003651 if (SemaRef.CurContext->isDependentContext())
3652 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003653 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3654 return SemaRef.PerformImplicitConversion(
3655 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3656 /*AllowExplicit=*/true);
3657 auto I = Captures.find(Capture);
3658 if (I != Captures.end())
3659 return buildCapture(SemaRef, Capture, I->second);
3660 DeclRefExpr *Ref = nullptr;
3661 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3662 Captures[Capture] = Ref;
3663 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003664}
3665
Alexander Musmana5f070a2014-10-01 06:03:56 +00003666/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003667Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3668 Scope *S, const bool LimitedType,
3669 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003670 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003671 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003672 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003673 SemaRef.getLangOpts().CPlusPlus) {
3674 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003675 auto *UBExpr = TestIsLessOp ? UB : LB;
3676 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003677 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3678 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003679 if (!Upper || !Lower)
3680 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003681
3682 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3683
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003684 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003685 // BuildBinOp already emitted error, this one is to point user to upper
3686 // and lower bound, and to tell what is passed to 'operator-'.
3687 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3688 << Upper->getSourceRange() << Lower->getSourceRange();
3689 return nullptr;
3690 }
3691 }
3692
3693 if (!Diff.isUsable())
3694 return nullptr;
3695
3696 // Upper - Lower [- 1]
3697 if (TestIsStrictOp)
3698 Diff = SemaRef.BuildBinOp(
3699 S, DefaultLoc, BO_Sub, Diff.get(),
3700 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3701 if (!Diff.isUsable())
3702 return nullptr;
3703
3704 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003705 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3706 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003707 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003708 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003709 if (!Diff.isUsable())
3710 return nullptr;
3711
3712 // Parentheses (for dumping/debugging purposes only).
3713 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3714 if (!Diff.isUsable())
3715 return nullptr;
3716
3717 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003718 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003719 if (!Diff.isUsable())
3720 return nullptr;
3721
Alexander Musman174b3ca2014-10-06 11:16:29 +00003722 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003723 QualType Type = Diff.get()->getType();
3724 auto &C = SemaRef.Context;
3725 bool UseVarType = VarType->hasIntegerRepresentation() &&
3726 C.getTypeSize(Type) > C.getTypeSize(VarType);
3727 if (!Type->isIntegerType() || UseVarType) {
3728 unsigned NewSize =
3729 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3730 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3731 : Type->hasSignedIntegerRepresentation();
3732 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003733 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3734 Diff = SemaRef.PerformImplicitConversion(
3735 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3736 if (!Diff.isUsable())
3737 return nullptr;
3738 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003739 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003740 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003741 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3742 if (NewSize != C.getTypeSize(Type)) {
3743 if (NewSize < C.getTypeSize(Type)) {
3744 assert(NewSize == 64 && "incorrect loop var size");
3745 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3746 << InitSrcRange << ConditionSrcRange;
3747 }
3748 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003749 NewSize, Type->hasSignedIntegerRepresentation() ||
3750 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003751 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3752 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3753 Sema::AA_Converting, true);
3754 if (!Diff.isUsable())
3755 return nullptr;
3756 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003757 }
3758 }
3759
Alexander Musmana5f070a2014-10-01 06:03:56 +00003760 return Diff.get();
3761}
3762
Alexey Bataev5a3af132016-03-29 08:58:54 +00003763Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3764 Scope *S, Expr *Cond,
3765 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003766 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3767 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3768 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003769
Alexey Bataev5a3af132016-03-29 08:58:54 +00003770 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3771 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3772 if (!NewLB.isUsable() || !NewUB.isUsable())
3773 return nullptr;
3774
Alexey Bataev62dbb972015-04-22 11:59:37 +00003775 auto CondExpr = SemaRef.BuildBinOp(
3776 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3777 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003778 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003779 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003780 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3781 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003782 CondExpr = SemaRef.PerformImplicitConversion(
3783 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3784 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003785 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003786 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3787 // Otherwise use original loop conditon and evaluate it in runtime.
3788 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3789}
3790
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003792DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003793 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003794 auto *VD = dyn_cast<VarDecl>(LCDecl);
3795 if (!VD) {
3796 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3797 auto *Ref = buildDeclRefExpr(
3798 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003799 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3800 // If the loop control decl is explicitly marked as private, do not mark it
3801 // as captured again.
3802 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3803 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003804 return Ref;
3805 }
3806 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003807 DefaultLoc);
3808}
3809
3810Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003811 if (LCDecl && !LCDecl->isInvalidDecl()) {
3812 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003813 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003814 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3815 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003816 if (PrivateVar->isInvalidDecl())
3817 return nullptr;
3818 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3819 }
3820 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003821}
3822
Samuel Antao4c8035b2016-12-12 18:00:20 +00003823/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003824Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3825
3826/// \brief Build step of the counter be used for codegen.
3827Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3828
3829/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003830struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003831 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003832 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003833 /// \brief This expression calculates the number of iterations in the loop.
3834 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003835 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003836 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003837 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003838 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003839 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003840 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003841 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003842 /// \brief This is step for the #CounterVar used to generate its update:
3843 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003844 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003845 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003846 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003847 /// \brief Source range of the loop init.
3848 SourceRange InitSrcRange;
3849 /// \brief Source range of the loop condition.
3850 SourceRange CondSrcRange;
3851 /// \brief Source range of the loop increment.
3852 SourceRange IncSrcRange;
3853};
3854
Alexey Bataev23b69422014-06-18 07:08:49 +00003855} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003856
Alexey Bataev9c821032015-04-30 04:23:23 +00003857void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3858 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3859 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003860 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3861 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003862 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3863 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003864 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3865 if (auto *D = ISC.GetLoopDecl()) {
3866 auto *VD = dyn_cast<VarDecl>(D);
3867 if (!VD) {
3868 if (auto *Private = IsOpenMPCapturedDecl(D))
3869 VD = Private;
3870 else {
3871 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3872 /*WithInit=*/false);
3873 VD = cast<VarDecl>(Ref->getDecl());
3874 }
3875 }
3876 DSAStack->addLoopControlVariable(D, VD);
3877 }
3878 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003879 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003880 }
3881}
3882
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003883/// \brief Called on a for stmt to check and extract its iteration space
3884/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003885static bool CheckOpenMPIterationSpace(
3886 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3887 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003888 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003889 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003890 LoopIterationSpace &ResultIterSpace,
3891 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003892 // OpenMP [2.6, Canonical Loop Form]
3893 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003894 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003895 if (!For) {
3896 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003897 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3898 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3899 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3900 if (NestedLoopCount > 1) {
3901 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3902 SemaRef.Diag(DSA.getConstructLoc(),
3903 diag::note_omp_collapse_ordered_expr)
3904 << 2 << CollapseLoopCountExpr->getSourceRange()
3905 << OrderedLoopCountExpr->getSourceRange();
3906 else if (CollapseLoopCountExpr)
3907 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3908 diag::note_omp_collapse_ordered_expr)
3909 << 0 << CollapseLoopCountExpr->getSourceRange();
3910 else
3911 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3912 diag::note_omp_collapse_ordered_expr)
3913 << 1 << OrderedLoopCountExpr->getSourceRange();
3914 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003915 return true;
3916 }
3917 assert(For->getBody());
3918
3919 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3920
3921 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003922 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003923 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003924 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003925
3926 bool HasErrors = false;
3927
3928 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003929 if (auto *LCDecl = ISC.GetLoopDecl()) {
3930 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003931
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003932 // OpenMP [2.6, Canonical Loop Form]
3933 // Var is one of the following:
3934 // A variable of signed or unsigned integer type.
3935 // For C++, a variable of a random access iterator type.
3936 // For C, a variable of a pointer type.
3937 auto VarType = LCDecl->getType().getNonReferenceType();
3938 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3939 !VarType->isPointerType() &&
3940 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3941 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3942 << SemaRef.getLangOpts().CPlusPlus;
3943 HasErrors = true;
3944 }
3945
3946 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3947 // a Construct
3948 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3949 // parallel for construct is (are) private.
3950 // The loop iteration variable in the associated for-loop of a simd
3951 // construct with just one associated for-loop is linear with a
3952 // constant-linear-step that is the increment of the associated for-loop.
3953 // Exclude loop var from the list of variables with implicitly defined data
3954 // sharing attributes.
3955 VarsWithImplicitDSA.erase(LCDecl);
3956
3957 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3958 // in a Construct, C/C++].
3959 // The loop iteration variable in the associated for-loop of a simd
3960 // construct with just one associated for-loop may be listed in a linear
3961 // clause with a constant-linear-step that is the increment of the
3962 // associated for-loop.
3963 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3964 // parallel for construct may be listed in a private or lastprivate clause.
3965 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3966 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3967 // declared in the loop and it is predetermined as a private.
3968 auto PredeterminedCKind =
3969 isOpenMPSimdDirective(DKind)
3970 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3971 : OMPC_private;
3972 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3973 DVar.CKind != PredeterminedCKind) ||
3974 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3975 isOpenMPDistributeDirective(DKind)) &&
3976 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3977 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3978 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3979 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3980 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3981 << getOpenMPClauseName(PredeterminedCKind);
3982 if (DVar.RefExpr == nullptr)
3983 DVar.CKind = PredeterminedCKind;
3984 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3985 HasErrors = true;
3986 } else if (LoopDeclRefExpr != nullptr) {
3987 // Make the loop iteration variable private (for worksharing constructs),
3988 // linear (for simd directives with the only one associated loop) or
3989 // lastprivate (for simd directives with several collapsed or ordered
3990 // loops).
3991 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003992 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3993 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003994 /*FromParent=*/false);
3995 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3996 }
3997
3998 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3999
4000 // Check test-expr.
4001 HasErrors |= ISC.CheckCond(For->getCond());
4002
4003 // Check incr-expr.
4004 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004005 }
4006
Alexander Musmana5f070a2014-10-01 06:03:56 +00004007 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004008 return HasErrors;
4009
Alexander Musmana5f070a2014-10-01 06:03:56 +00004010 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004011 ResultIterSpace.PreCond =
4012 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004013 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004014 DSA.getCurScope(),
4015 (isOpenMPWorksharingDirective(DKind) ||
4016 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4017 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004018 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004019 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004020 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4021 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4022 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4023 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4024 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4025 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4026
Alexey Bataev62dbb972015-04-22 11:59:37 +00004027 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4028 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004029 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004030 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004031 ResultIterSpace.CounterInit == nullptr ||
4032 ResultIterSpace.CounterStep == nullptr);
4033
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004034 return HasErrors;
4035}
4036
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004037/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004038static ExprResult
4039BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4040 ExprResult Start,
4041 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004042 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004043 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4044 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004045 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004046 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004047 VarRef.get()->getType())) {
4048 NewStart = SemaRef.PerformImplicitConversion(
4049 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4050 /*AllowExplicit=*/true);
4051 if (!NewStart.isUsable())
4052 return ExprError();
4053 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004054
4055 auto Init =
4056 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4057 return Init;
4058}
4059
Alexander Musmana5f070a2014-10-01 06:03:56 +00004060/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004061static ExprResult
4062BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4063 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4064 ExprResult Step, bool Subtract,
4065 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004066 // Add parentheses (for debugging purposes only).
4067 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4068 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4069 !Step.isUsable())
4070 return ExprError();
4071
Alexey Bataev5a3af132016-03-29 08:58:54 +00004072 ExprResult NewStep = Step;
4073 if (Captures)
4074 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004075 if (NewStep.isInvalid())
4076 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004077 ExprResult Update =
4078 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004079 if (!Update.isUsable())
4080 return ExprError();
4081
Alexey Bataevc0214e02016-02-16 12:13:49 +00004082 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4083 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004084 ExprResult NewStart = Start;
4085 if (Captures)
4086 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004087 if (NewStart.isInvalid())
4088 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004089
Alexey Bataevc0214e02016-02-16 12:13:49 +00004090 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4091 ExprResult SavedUpdate = Update;
4092 ExprResult UpdateVal;
4093 if (VarRef.get()->getType()->isOverloadableType() ||
4094 NewStart.get()->getType()->isOverloadableType() ||
4095 Update.get()->getType()->isOverloadableType()) {
4096 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4097 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4098 Update =
4099 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4100 if (Update.isUsable()) {
4101 UpdateVal =
4102 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4103 VarRef.get(), SavedUpdate.get());
4104 if (UpdateVal.isUsable()) {
4105 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4106 UpdateVal.get());
4107 }
4108 }
4109 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4110 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004111
Alexey Bataevc0214e02016-02-16 12:13:49 +00004112 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4113 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4114 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4115 NewStart.get(), SavedUpdate.get());
4116 if (!Update.isUsable())
4117 return ExprError();
4118
Alexey Bataev11481f52016-02-17 10:29:05 +00004119 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4120 VarRef.get()->getType())) {
4121 Update = SemaRef.PerformImplicitConversion(
4122 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4123 if (!Update.isUsable())
4124 return ExprError();
4125 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004126
4127 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4128 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004129 return Update;
4130}
4131
4132/// \brief Convert integer expression \a E to make it have at least \a Bits
4133/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004134static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004135 if (E == nullptr)
4136 return ExprError();
4137 auto &C = SemaRef.Context;
4138 QualType OldType = E->getType();
4139 unsigned HasBits = C.getTypeSize(OldType);
4140 if (HasBits >= Bits)
4141 return ExprResult(E);
4142 // OK to convert to signed, because new type has more bits than old.
4143 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4144 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4145 true);
4146}
4147
4148/// \brief Check if the given expression \a E is a constant integer that fits
4149/// into \a Bits bits.
4150static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4151 if (E == nullptr)
4152 return false;
4153 llvm::APSInt Result;
4154 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4155 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4156 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004157}
4158
Alexey Bataev5a3af132016-03-29 08:58:54 +00004159/// Build preinits statement for the given declarations.
4160static Stmt *buildPreInits(ASTContext &Context,
4161 SmallVectorImpl<Decl *> &PreInits) {
4162 if (!PreInits.empty()) {
4163 return new (Context) DeclStmt(
4164 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4165 SourceLocation(), SourceLocation());
4166 }
4167 return nullptr;
4168}
4169
4170/// Build preinits statement for the given declarations.
4171static Stmt *buildPreInits(ASTContext &Context,
4172 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4173 if (!Captures.empty()) {
4174 SmallVector<Decl *, 16> PreInits;
4175 for (auto &Pair : Captures)
4176 PreInits.push_back(Pair.second->getDecl());
4177 return buildPreInits(Context, PreInits);
4178 }
4179 return nullptr;
4180}
4181
4182/// Build postupdate expression for the given list of postupdates expressions.
4183static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4184 Expr *PostUpdate = nullptr;
4185 if (!PostUpdates.empty()) {
4186 for (auto *E : PostUpdates) {
4187 Expr *ConvE = S.BuildCStyleCastExpr(
4188 E->getExprLoc(),
4189 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4190 E->getExprLoc(), E)
4191 .get();
4192 PostUpdate = PostUpdate
4193 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4194 PostUpdate, ConvE)
4195 .get()
4196 : ConvE;
4197 }
4198 }
4199 return PostUpdate;
4200}
4201
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004202/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004203/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4204/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004205static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004206CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4207 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4208 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004209 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004210 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004211 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004212 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004213 // Found 'collapse' clause - calculate collapse number.
4214 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004215 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004216 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004217 }
4218 if (OrderedLoopCountExpr) {
4219 // Found 'ordered' clause - calculate collapse number.
4220 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004221 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4222 if (Result.getLimitedValue() < NestedLoopCount) {
4223 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4224 diag::err_omp_wrong_ordered_loop_count)
4225 << OrderedLoopCountExpr->getSourceRange();
4226 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4227 diag::note_collapse_loop_count)
4228 << CollapseLoopCountExpr->getSourceRange();
4229 }
4230 NestedLoopCount = Result.getLimitedValue();
4231 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004232 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004233 // This is helper routine for loop directives (e.g., 'for', 'simd',
4234 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004235 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004236 SmallVector<LoopIterationSpace, 4> IterSpaces;
4237 IterSpaces.resize(NestedLoopCount);
4238 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004239 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004240 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004241 NestedLoopCount, CollapseLoopCountExpr,
4242 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004243 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004244 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004245 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004246 // OpenMP [2.8.1, simd construct, Restrictions]
4247 // All loops associated with the construct must be perfectly nested; that
4248 // is, there must be no intervening code nor any OpenMP directive between
4249 // any two loops.
4250 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004251 }
4252
Alexander Musmana5f070a2014-10-01 06:03:56 +00004253 Built.clear(/* size */ NestedLoopCount);
4254
4255 if (SemaRef.CurContext->isDependentContext())
4256 return NestedLoopCount;
4257
4258 // An example of what is generated for the following code:
4259 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004260 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004261 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004262 // for (k = 0; k < NK; ++k)
4263 // for (j = J0; j < NJ; j+=2) {
4264 // <loop body>
4265 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004266 //
4267 // We generate the code below.
4268 // Note: the loop body may be outlined in CodeGen.
4269 // Note: some counters may be C++ classes, operator- is used to find number of
4270 // iterations and operator+= to calculate counter value.
4271 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4272 // or i64 is currently supported).
4273 //
4274 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4275 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4276 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4277 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4278 // // similar updates for vars in clauses (e.g. 'linear')
4279 // <loop body (using local i and j)>
4280 // }
4281 // i = NI; // assign final values of counters
4282 // j = NJ;
4283 //
4284
4285 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4286 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004287 // Precondition tests if there is at least one iteration (all conditions are
4288 // true).
4289 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004290 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004291 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004292 32 /* Bits */, SemaRef
4293 .PerformImplicitConversion(
4294 N0->IgnoreImpCasts(), N0->getType(),
4295 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004296 .get(),
4297 SemaRef);
4298 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004299 64 /* Bits */, SemaRef
4300 .PerformImplicitConversion(
4301 N0->IgnoreImpCasts(), N0->getType(),
4302 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004303 .get(),
4304 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004305
4306 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4307 return NestedLoopCount;
4308
4309 auto &C = SemaRef.Context;
4310 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4311
4312 Scope *CurScope = DSA.getCurScope();
4313 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004314 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004315 PreCond =
4316 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4317 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004318 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004319 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004320 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004321 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4322 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004323 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004324 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004325 SemaRef
4326 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4327 Sema::AA_Converting,
4328 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004329 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004330 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004331 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004332 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004333 SemaRef
4334 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4335 Sema::AA_Converting,
4336 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004337 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004338 }
4339
4340 // Choose either the 32-bit or 64-bit version.
4341 ExprResult LastIteration = LastIteration64;
4342 if (LastIteration32.isUsable() &&
4343 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4344 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4345 FitsInto(
4346 32 /* Bits */,
4347 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4348 LastIteration64.get(), SemaRef)))
4349 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004350 QualType VType = LastIteration.get()->getType();
4351 QualType RealVType = VType;
4352 QualType StrideVType = VType;
4353 if (isOpenMPTaskLoopDirective(DKind)) {
4354 VType =
4355 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4356 StrideVType =
4357 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4358 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004359
4360 if (!LastIteration.isUsable())
4361 return 0;
4362
4363 // Save the number of iterations.
4364 ExprResult NumIterations = LastIteration;
4365 {
4366 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004367 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4368 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004369 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4370 if (!LastIteration.isUsable())
4371 return 0;
4372 }
4373
4374 // Calculate the last iteration number beforehand instead of doing this on
4375 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4376 llvm::APSInt Result;
4377 bool IsConstant =
4378 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4379 ExprResult CalcLastIteration;
4380 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004381 ExprResult SaveRef =
4382 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004383 LastIteration = SaveRef;
4384
4385 // Prepare SaveRef + 1.
4386 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004387 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004388 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4389 if (!NumIterations.isUsable())
4390 return 0;
4391 }
4392
4393 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4394
David Majnemer9d168222016-08-05 17:44:54 +00004395 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004396 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004397 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4398 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004399 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004400 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4401 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004402 SemaRef.AddInitializerToDecl(LBDecl,
4403 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4404 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004405
4406 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004407 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4408 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004409 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004410 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004411
4412 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4413 // This will be used to implement clause 'lastprivate'.
4414 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004415 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4416 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004417 SemaRef.AddInitializerToDecl(ILDecl,
4418 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4419 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004420
4421 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004422 VarDecl *STDecl =
4423 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4424 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004425 SemaRef.AddInitializerToDecl(STDecl,
4426 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4427 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004428
4429 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004430 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004431 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4432 UB.get(), LastIteration.get());
4433 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4434 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4435 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4436 CondOp.get());
4437 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004438
4439 // If we have a combined directive that combines 'distribute', 'for' or
4440 // 'simd' we need to be able to access the bounds of the schedule of the
4441 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4442 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4443 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004444
Carlo Bertolliffafe102017-04-20 00:39:39 +00004445 // Lower bound variable, initialized with zero.
4446 VarDecl *CombLBDecl =
4447 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4448 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4449 SemaRef.AddInitializerToDecl(
4450 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4451 /*DirectInit*/ false);
4452
4453 // Upper bound variable, initialized with last iteration number.
4454 VarDecl *CombUBDecl =
4455 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4456 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4457 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4458 /*DirectInit*/ false);
4459
4460 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4461 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4462 ExprResult CombCondOp =
4463 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4464 LastIteration.get(), CombUB.get());
4465 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4466 CombCondOp.get());
4467 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4468
4469 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004470 // We expect to have at least 2 more parameters than the 'parallel'
4471 // directive does - the lower and upper bounds of the previous schedule.
4472 assert(CD->getNumParams() >= 4 &&
4473 "Unexpected number of parameters in loop combined directive");
4474
4475 // Set the proper type for the bounds given what we learned from the
4476 // enclosed loops.
4477 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4478 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4479
4480 // Previous lower and upper bounds are obtained from the region
4481 // parameters.
4482 PrevLB =
4483 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4484 PrevUB =
4485 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4486 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004487 }
4488
4489 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004490 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004491 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004492 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004493 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4494 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004495 Expr *RHS =
4496 (isOpenMPWorksharingDirective(DKind) ||
4497 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4498 ? LB.get()
4499 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004500 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4501 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004502
4503 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4504 Expr *CombRHS =
4505 (isOpenMPWorksharingDirective(DKind) ||
4506 isOpenMPTaskLoopDirective(DKind) ||
4507 isOpenMPDistributeDirective(DKind))
4508 ? CombLB.get()
4509 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4510 CombInit =
4511 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4512 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4513 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004514 }
4515
Alexander Musmanc6388682014-12-15 07:07:06 +00004516 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004517 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004518 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004519 (isOpenMPWorksharingDirective(DKind) ||
4520 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004521 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4522 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4523 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004524 ExprResult CombCond;
4525 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4526 CombCond =
4527 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4528 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004529 // Loop increment (IV = IV + 1)
4530 SourceLocation IncLoc;
4531 ExprResult Inc =
4532 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4533 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4534 if (!Inc.isUsable())
4535 return 0;
4536 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004537 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4538 if (!Inc.isUsable())
4539 return 0;
4540
4541 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4542 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004543 // In combined construct, add combined version that use CombLB and CombUB
4544 // base variables for the update
4545 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004546 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4547 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004548 // LB + ST
4549 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4550 if (!NextLB.isUsable())
4551 return 0;
4552 // LB = LB + ST
4553 NextLB =
4554 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4555 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4556 if (!NextLB.isUsable())
4557 return 0;
4558 // UB + ST
4559 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4560 if (!NextUB.isUsable())
4561 return 0;
4562 // UB = UB + ST
4563 NextUB =
4564 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4565 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4566 if (!NextUB.isUsable())
4567 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004568 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4569 CombNextLB =
4570 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4571 if (!NextLB.isUsable())
4572 return 0;
4573 // LB = LB + ST
4574 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4575 CombNextLB.get());
4576 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4577 if (!CombNextLB.isUsable())
4578 return 0;
4579 // UB + ST
4580 CombNextUB =
4581 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4582 if (!CombNextUB.isUsable())
4583 return 0;
4584 // UB = UB + ST
4585 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4586 CombNextUB.get());
4587 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4588 if (!CombNextUB.isUsable())
4589 return 0;
4590 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004591 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004592
Carlo Bertolliffafe102017-04-20 00:39:39 +00004593 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004594 // directive with for as IV = IV + ST; ensure upper bound expression based
4595 // on PrevUB instead of NumIterations - used to implement 'for' when found
4596 // in combination with 'distribute', like in 'distribute parallel for'
4597 SourceLocation DistIncLoc;
4598 ExprResult DistCond, DistInc, PrevEUB;
4599 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4600 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4601 assert(DistCond.isUsable() && "distribute cond expr was not built");
4602
4603 DistInc =
4604 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4605 assert(DistInc.isUsable() && "distribute inc expr was not built");
4606 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4607 DistInc.get());
4608 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4609 assert(DistInc.isUsable() && "distribute inc expr was not built");
4610
4611 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4612 // construct
4613 SourceLocation DistEUBLoc;
4614 ExprResult IsUBGreater =
4615 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4616 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4617 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4618 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4619 CondOp.get());
4620 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4621 }
4622
Alexander Musmana5f070a2014-10-01 06:03:56 +00004623 // Build updates and final values of the loop counters.
4624 bool HasErrors = false;
4625 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004626 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004627 Built.Updates.resize(NestedLoopCount);
4628 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004629 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004630 {
4631 ExprResult Div;
4632 // Go from inner nested loop to outer.
4633 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4634 LoopIterationSpace &IS = IterSpaces[Cnt];
4635 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4636 // Build: Iter = (IV / Div) % IS.NumIters
4637 // where Div is product of previous iterations' IS.NumIters.
4638 ExprResult Iter;
4639 if (Div.isUsable()) {
4640 Iter =
4641 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4642 } else {
4643 Iter = IV;
4644 assert((Cnt == (int)NestedLoopCount - 1) &&
4645 "unusable div expected on first iteration only");
4646 }
4647
4648 if (Cnt != 0 && Iter.isUsable())
4649 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4650 IS.NumIterations);
4651 if (!Iter.isUsable()) {
4652 HasErrors = true;
4653 break;
4654 }
4655
Alexey Bataev39f915b82015-05-08 10:41:21 +00004656 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004657 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4658 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4659 IS.CounterVar->getExprLoc(),
4660 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004661 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004662 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004663 if (!Init.isUsable()) {
4664 HasErrors = true;
4665 break;
4666 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004667 ExprResult Update = BuildCounterUpdate(
4668 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4669 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004670 if (!Update.isUsable()) {
4671 HasErrors = true;
4672 break;
4673 }
4674
4675 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4676 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004677 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004678 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004679 if (!Final.isUsable()) {
4680 HasErrors = true;
4681 break;
4682 }
4683
4684 // Build Div for the next iteration: Div <- Div * IS.NumIters
4685 if (Cnt != 0) {
4686 if (Div.isUnset())
4687 Div = IS.NumIterations;
4688 else
4689 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4690 IS.NumIterations);
4691
4692 // Add parentheses (for debugging purposes only).
4693 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004694 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004695 if (!Div.isUsable()) {
4696 HasErrors = true;
4697 break;
4698 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004699 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004700 }
4701 if (!Update.isUsable() || !Final.isUsable()) {
4702 HasErrors = true;
4703 break;
4704 }
4705 // Save results
4706 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004707 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004708 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004709 Built.Updates[Cnt] = Update.get();
4710 Built.Finals[Cnt] = Final.get();
4711 }
4712 }
4713
4714 if (HasErrors)
4715 return 0;
4716
4717 // Save results
4718 Built.IterationVarRef = IV.get();
4719 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004720 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004721 Built.CalcLastIteration =
4722 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004723 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004724 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004725 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004726 Built.Init = Init.get();
4727 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004728 Built.LB = LB.get();
4729 Built.UB = UB.get();
4730 Built.IL = IL.get();
4731 Built.ST = ST.get();
4732 Built.EUB = EUB.get();
4733 Built.NLB = NextLB.get();
4734 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004735 Built.PrevLB = PrevLB.get();
4736 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004737 Built.DistInc = DistInc.get();
4738 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004739 Built.DistCombinedFields.LB = CombLB.get();
4740 Built.DistCombinedFields.UB = CombUB.get();
4741 Built.DistCombinedFields.EUB = CombEUB.get();
4742 Built.DistCombinedFields.Init = CombInit.get();
4743 Built.DistCombinedFields.Cond = CombCond.get();
4744 Built.DistCombinedFields.NLB = CombNextLB.get();
4745 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004746
Alexey Bataev8b427062016-05-25 12:36:08 +00004747 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4748 // Fill data for doacross depend clauses.
4749 for (auto Pair : DSA.getDoacrossDependClauses()) {
4750 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4751 Pair.first->setCounterValue(CounterVal);
4752 else {
4753 if (NestedLoopCount != Pair.second.size() ||
4754 NestedLoopCount != LoopMultipliers.size() + 1) {
4755 // Erroneous case - clause has some problems.
4756 Pair.first->setCounterValue(CounterVal);
4757 continue;
4758 }
4759 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4760 auto I = Pair.second.rbegin();
4761 auto IS = IterSpaces.rbegin();
4762 auto ILM = LoopMultipliers.rbegin();
4763 Expr *UpCounterVal = CounterVal;
4764 Expr *Multiplier = nullptr;
4765 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4766 if (I->first) {
4767 assert(IS->CounterStep);
4768 Expr *NormalizedOffset =
4769 SemaRef
4770 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4771 I->first, IS->CounterStep)
4772 .get();
4773 if (Multiplier) {
4774 NormalizedOffset =
4775 SemaRef
4776 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4777 NormalizedOffset, Multiplier)
4778 .get();
4779 }
4780 assert(I->second == OO_Plus || I->second == OO_Minus);
4781 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004782 UpCounterVal = SemaRef
4783 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4784 UpCounterVal, NormalizedOffset)
4785 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004786 }
4787 Multiplier = *ILM;
4788 ++I;
4789 ++IS;
4790 ++ILM;
4791 }
4792 Pair.first->setCounterValue(UpCounterVal);
4793 }
4794 }
4795
Alexey Bataevabfc0692014-06-25 06:52:00 +00004796 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004797}
4798
Alexey Bataev10e775f2015-07-30 11:36:16 +00004799static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004800 auto CollapseClauses =
4801 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4802 if (CollapseClauses.begin() != CollapseClauses.end())
4803 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004804 return nullptr;
4805}
4806
Alexey Bataev10e775f2015-07-30 11:36:16 +00004807static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004808 auto OrderedClauses =
4809 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4810 if (OrderedClauses.begin() != OrderedClauses.end())
4811 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004812 return nullptr;
4813}
4814
Kelvin Lic5609492016-07-15 04:39:07 +00004815static bool checkSimdlenSafelenSpecified(Sema &S,
4816 const ArrayRef<OMPClause *> Clauses) {
4817 OMPSafelenClause *Safelen = nullptr;
4818 OMPSimdlenClause *Simdlen = nullptr;
4819
4820 for (auto *Clause : Clauses) {
4821 if (Clause->getClauseKind() == OMPC_safelen)
4822 Safelen = cast<OMPSafelenClause>(Clause);
4823 else if (Clause->getClauseKind() == OMPC_simdlen)
4824 Simdlen = cast<OMPSimdlenClause>(Clause);
4825 if (Safelen && Simdlen)
4826 break;
4827 }
4828
4829 if (Simdlen && Safelen) {
4830 llvm::APSInt SimdlenRes, SafelenRes;
4831 auto SimdlenLength = Simdlen->getSimdlen();
4832 auto SafelenLength = Safelen->getSafelen();
4833 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4834 SimdlenLength->isInstantiationDependent() ||
4835 SimdlenLength->containsUnexpandedParameterPack())
4836 return false;
4837 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4838 SafelenLength->isInstantiationDependent() ||
4839 SafelenLength->containsUnexpandedParameterPack())
4840 return false;
4841 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4842 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4843 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4844 // If both simdlen and safelen clauses are specified, the value of the
4845 // simdlen parameter must be less than or equal to the value of the safelen
4846 // parameter.
4847 if (SimdlenRes > SafelenRes) {
4848 S.Diag(SimdlenLength->getExprLoc(),
4849 diag::err_omp_wrong_simdlen_safelen_values)
4850 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4851 return true;
4852 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004853 }
4854 return false;
4855}
4856
Alexey Bataev4acb8592014-07-07 13:01:15 +00004857StmtResult Sema::ActOnOpenMPSimdDirective(
4858 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4859 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004860 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004861 if (!AStmt)
4862 return StmtError();
4863
4864 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004865 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004866 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4867 // define the nested loops number.
4868 unsigned NestedLoopCount = CheckOpenMPLoop(
4869 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4870 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004871 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004872 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004873
Alexander Musmana5f070a2014-10-01 06:03:56 +00004874 assert((CurContext->isDependentContext() || B.builtAll()) &&
4875 "omp simd loop exprs were not built");
4876
Alexander Musman3276a272015-03-21 10:12:56 +00004877 if (!CurContext->isDependentContext()) {
4878 // Finalize the clauses that need pre-built expressions for CodeGen.
4879 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004880 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004881 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004882 B.NumIterations, *this, CurScope,
4883 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004884 return StmtError();
4885 }
4886 }
4887
Kelvin Lic5609492016-07-15 04:39:07 +00004888 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004889 return StmtError();
4890
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004891 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004892 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4893 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004894}
4895
Alexey Bataev4acb8592014-07-07 13:01:15 +00004896StmtResult Sema::ActOnOpenMPForDirective(
4897 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4898 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004899 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004900 if (!AStmt)
4901 return StmtError();
4902
4903 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004904 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004905 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4906 // define the nested loops number.
4907 unsigned NestedLoopCount = CheckOpenMPLoop(
4908 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4909 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004910 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004911 return StmtError();
4912
Alexander Musmana5f070a2014-10-01 06:03:56 +00004913 assert((CurContext->isDependentContext() || B.builtAll()) &&
4914 "omp for loop exprs were not built");
4915
Alexey Bataev54acd402015-08-04 11:18:19 +00004916 if (!CurContext->isDependentContext()) {
4917 // Finalize the clauses that need pre-built expressions for CodeGen.
4918 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004919 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004920 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004921 B.NumIterations, *this, CurScope,
4922 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004923 return StmtError();
4924 }
4925 }
4926
Alexey Bataevf29276e2014-06-18 04:14:57 +00004927 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004928 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004929 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004930}
4931
Alexander Musmanf82886e2014-09-18 05:12:34 +00004932StmtResult Sema::ActOnOpenMPForSimdDirective(
4933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4934 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004935 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004936 if (!AStmt)
4937 return StmtError();
4938
4939 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004940 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004941 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4942 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004943 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004944 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4945 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4946 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004947 if (NestedLoopCount == 0)
4948 return StmtError();
4949
Alexander Musmanc6388682014-12-15 07:07:06 +00004950 assert((CurContext->isDependentContext() || B.builtAll()) &&
4951 "omp for simd loop exprs were not built");
4952
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004953 if (!CurContext->isDependentContext()) {
4954 // Finalize the clauses that need pre-built expressions for CodeGen.
4955 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004956 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004957 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004958 B.NumIterations, *this, CurScope,
4959 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004960 return StmtError();
4961 }
4962 }
4963
Kelvin Lic5609492016-07-15 04:39:07 +00004964 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004965 return StmtError();
4966
Alexander Musmanf82886e2014-09-18 05:12:34 +00004967 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004968 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4969 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004970}
4971
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004972StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4973 Stmt *AStmt,
4974 SourceLocation StartLoc,
4975 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004976 if (!AStmt)
4977 return StmtError();
4978
4979 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004980 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004981 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004982 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004983 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004984 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004985 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004986 return StmtError();
4987 // All associated statements must be '#pragma omp section' except for
4988 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004989 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004990 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4991 if (SectionStmt)
4992 Diag(SectionStmt->getLocStart(),
4993 diag::err_omp_sections_substmt_not_section);
4994 return StmtError();
4995 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004996 cast<OMPSectionDirective>(SectionStmt)
4997 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004998 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004999 } else {
5000 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5001 return StmtError();
5002 }
5003
5004 getCurFunction()->setHasBranchProtectedScope();
5005
Alexey Bataev25e5b442015-09-15 12:52:43 +00005006 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5007 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005008}
5009
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005010StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5011 SourceLocation StartLoc,
5012 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005013 if (!AStmt)
5014 return StmtError();
5015
5016 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005017
5018 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005019 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005020
Alexey Bataev25e5b442015-09-15 12:52:43 +00005021 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5022 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005023}
5024
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005025StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5026 Stmt *AStmt,
5027 SourceLocation StartLoc,
5028 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005029 if (!AStmt)
5030 return StmtError();
5031
5032 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005033
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005034 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005035
Alexey Bataev3255bf32015-01-19 05:20:46 +00005036 // OpenMP [2.7.3, single Construct, Restrictions]
5037 // The copyprivate clause must not be used with the nowait clause.
5038 OMPClause *Nowait = nullptr;
5039 OMPClause *Copyprivate = nullptr;
5040 for (auto *Clause : Clauses) {
5041 if (Clause->getClauseKind() == OMPC_nowait)
5042 Nowait = Clause;
5043 else if (Clause->getClauseKind() == OMPC_copyprivate)
5044 Copyprivate = Clause;
5045 if (Copyprivate && Nowait) {
5046 Diag(Copyprivate->getLocStart(),
5047 diag::err_omp_single_copyprivate_with_nowait);
5048 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5049 return StmtError();
5050 }
5051 }
5052
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005053 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5054}
5055
Alexander Musman80c22892014-07-17 08:54:58 +00005056StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5057 SourceLocation StartLoc,
5058 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005059 if (!AStmt)
5060 return StmtError();
5061
5062 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005063
5064 getCurFunction()->setHasBranchProtectedScope();
5065
5066 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5067}
5068
Alexey Bataev28c75412015-12-15 08:19:24 +00005069StmtResult Sema::ActOnOpenMPCriticalDirective(
5070 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5071 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005072 if (!AStmt)
5073 return StmtError();
5074
5075 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005076
Alexey Bataev28c75412015-12-15 08:19:24 +00005077 bool ErrorFound = false;
5078 llvm::APSInt Hint;
5079 SourceLocation HintLoc;
5080 bool DependentHint = false;
5081 for (auto *C : Clauses) {
5082 if (C->getClauseKind() == OMPC_hint) {
5083 if (!DirName.getName()) {
5084 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5085 ErrorFound = true;
5086 }
5087 Expr *E = cast<OMPHintClause>(C)->getHint();
5088 if (E->isTypeDependent() || E->isValueDependent() ||
5089 E->isInstantiationDependent())
5090 DependentHint = true;
5091 else {
5092 Hint = E->EvaluateKnownConstInt(Context);
5093 HintLoc = C->getLocStart();
5094 }
5095 }
5096 }
5097 if (ErrorFound)
5098 return StmtError();
5099 auto Pair = DSAStack->getCriticalWithHint(DirName);
5100 if (Pair.first && DirName.getName() && !DependentHint) {
5101 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5102 Diag(StartLoc, diag::err_omp_critical_with_hint);
5103 if (HintLoc.isValid()) {
5104 Diag(HintLoc, diag::note_omp_critical_hint_here)
5105 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5106 } else
5107 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5108 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5109 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5110 << 1
5111 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5112 /*Radix=*/10, /*Signed=*/false);
5113 } else
5114 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5115 }
5116 }
5117
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005118 getCurFunction()->setHasBranchProtectedScope();
5119
Alexey Bataev28c75412015-12-15 08:19:24 +00005120 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5121 Clauses, AStmt);
5122 if (!Pair.first && DirName.getName() && !DependentHint)
5123 DSAStack->addCriticalWithHint(Dir, Hint);
5124 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005125}
5126
Alexey Bataev4acb8592014-07-07 13:01:15 +00005127StmtResult Sema::ActOnOpenMPParallelForDirective(
5128 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5129 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005130 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005131 if (!AStmt)
5132 return StmtError();
5133
Alexey Bataev4acb8592014-07-07 13:01:15 +00005134 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5135 // 1.2.2 OpenMP Language Terminology
5136 // Structured block - An executable statement with a single entry at the
5137 // top and a single exit at the bottom.
5138 // The point of exit cannot be a branch out of the structured block.
5139 // longjmp() and throw() must not violate the entry/exit criteria.
5140 CS->getCapturedDecl()->setNothrow();
5141
Alexander Musmanc6388682014-12-15 07:07:06 +00005142 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005143 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5144 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005145 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005146 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5147 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5148 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005149 if (NestedLoopCount == 0)
5150 return StmtError();
5151
Alexander Musmana5f070a2014-10-01 06:03:56 +00005152 assert((CurContext->isDependentContext() || B.builtAll()) &&
5153 "omp parallel for loop exprs were not built");
5154
Alexey Bataev54acd402015-08-04 11:18:19 +00005155 if (!CurContext->isDependentContext()) {
5156 // Finalize the clauses that need pre-built expressions for CodeGen.
5157 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005158 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005159 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005160 B.NumIterations, *this, CurScope,
5161 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005162 return StmtError();
5163 }
5164 }
5165
Alexey Bataev4acb8592014-07-07 13:01:15 +00005166 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005167 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005168 NestedLoopCount, Clauses, AStmt, B,
5169 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005170}
5171
Alexander Musmane4e893b2014-09-23 09:33:00 +00005172StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5173 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5174 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005175 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005176 if (!AStmt)
5177 return StmtError();
5178
Alexander Musmane4e893b2014-09-23 09:33:00 +00005179 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5180 // 1.2.2 OpenMP Language Terminology
5181 // Structured block - An executable statement with a single entry at the
5182 // top and a single exit at the bottom.
5183 // The point of exit cannot be a branch out of the structured block.
5184 // longjmp() and throw() must not violate the entry/exit criteria.
5185 CS->getCapturedDecl()->setNothrow();
5186
Alexander Musmanc6388682014-12-15 07:07:06 +00005187 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005188 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5189 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005190 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005191 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5192 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5193 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005194 if (NestedLoopCount == 0)
5195 return StmtError();
5196
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005197 if (!CurContext->isDependentContext()) {
5198 // Finalize the clauses that need pre-built expressions for CodeGen.
5199 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005200 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005201 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005202 B.NumIterations, *this, CurScope,
5203 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005204 return StmtError();
5205 }
5206 }
5207
Kelvin Lic5609492016-07-15 04:39:07 +00005208 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005209 return StmtError();
5210
Alexander Musmane4e893b2014-09-23 09:33:00 +00005211 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005212 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005213 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005214}
5215
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005216StmtResult
5217Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5218 Stmt *AStmt, SourceLocation StartLoc,
5219 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005220 if (!AStmt)
5221 return StmtError();
5222
5223 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005224 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005225 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005226 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005227 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005228 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005229 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005230 return StmtError();
5231 // All associated statements must be '#pragma omp section' except for
5232 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005233 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005234 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5235 if (SectionStmt)
5236 Diag(SectionStmt->getLocStart(),
5237 diag::err_omp_parallel_sections_substmt_not_section);
5238 return StmtError();
5239 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005240 cast<OMPSectionDirective>(SectionStmt)
5241 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005242 }
5243 } else {
5244 Diag(AStmt->getLocStart(),
5245 diag::err_omp_parallel_sections_not_compound_stmt);
5246 return StmtError();
5247 }
5248
5249 getCurFunction()->setHasBranchProtectedScope();
5250
Alexey Bataev25e5b442015-09-15 12:52:43 +00005251 return OMPParallelSectionsDirective::Create(
5252 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005253}
5254
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005255StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5256 Stmt *AStmt, SourceLocation StartLoc,
5257 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005258 if (!AStmt)
5259 return StmtError();
5260
David Majnemer9d168222016-08-05 17:44:54 +00005261 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005262 // 1.2.2 OpenMP Language Terminology
5263 // Structured block - An executable statement with a single entry at the
5264 // top and a single exit at the bottom.
5265 // The point of exit cannot be a branch out of the structured block.
5266 // longjmp() and throw() must not violate the entry/exit criteria.
5267 CS->getCapturedDecl()->setNothrow();
5268
5269 getCurFunction()->setHasBranchProtectedScope();
5270
Alexey Bataev25e5b442015-09-15 12:52:43 +00005271 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5272 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005273}
5274
Alexey Bataev68446b72014-07-18 07:47:19 +00005275StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5276 SourceLocation EndLoc) {
5277 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5278}
5279
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005280StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5281 SourceLocation EndLoc) {
5282 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5283}
5284
Alexey Bataev2df347a2014-07-18 10:17:07 +00005285StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5286 SourceLocation EndLoc) {
5287 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5288}
5289
Alexey Bataev169d96a2017-07-18 20:17:46 +00005290StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5291 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005292 SourceLocation StartLoc,
5293 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005294 if (!AStmt)
5295 return StmtError();
5296
5297 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005298
5299 getCurFunction()->setHasBranchProtectedScope();
5300
Alexey Bataev169d96a2017-07-18 20:17:46 +00005301 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005302 AStmt,
5303 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005304}
5305
Alexey Bataev6125da92014-07-21 11:26:11 +00005306StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5307 SourceLocation StartLoc,
5308 SourceLocation EndLoc) {
5309 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5310 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5311}
5312
Alexey Bataev346265e2015-09-25 10:37:12 +00005313StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5314 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005315 SourceLocation StartLoc,
5316 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005317 OMPClause *DependFound = nullptr;
5318 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005319 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005320 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005321 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005322 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005323 for (auto *C : Clauses) {
5324 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5325 DependFound = C;
5326 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5327 if (DependSourceClause) {
5328 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5329 << getOpenMPDirectiveName(OMPD_ordered)
5330 << getOpenMPClauseName(OMPC_depend) << 2;
5331 ErrorFound = true;
5332 } else
5333 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005334 if (DependSinkClause) {
5335 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5336 << 0;
5337 ErrorFound = true;
5338 }
5339 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5340 if (DependSourceClause) {
5341 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5342 << 1;
5343 ErrorFound = true;
5344 }
5345 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005346 }
5347 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005348 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005349 else if (C->getClauseKind() == OMPC_simd)
5350 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005351 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005352 if (!ErrorFound && !SC &&
5353 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005354 // OpenMP [2.8.1,simd Construct, Restrictions]
5355 // An ordered construct with the simd clause is the only OpenMP construct
5356 // that can appear in the simd region.
5357 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005358 ErrorFound = true;
5359 } else if (DependFound && (TC || SC)) {
5360 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5361 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5362 ErrorFound = true;
5363 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5364 Diag(DependFound->getLocStart(),
5365 diag::err_omp_ordered_directive_without_param);
5366 ErrorFound = true;
5367 } else if (TC || Clauses.empty()) {
5368 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5369 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5370 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5371 << (TC != nullptr);
5372 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5373 ErrorFound = true;
5374 }
5375 }
5376 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005377 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005378
5379 if (AStmt) {
5380 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5381
5382 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005383 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005384
5385 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005386}
5387
Alexey Bataev1d160b12015-03-13 12:27:31 +00005388namespace {
5389/// \brief Helper class for checking expression in 'omp atomic [update]'
5390/// construct.
5391class OpenMPAtomicUpdateChecker {
5392 /// \brief Error results for atomic update expressions.
5393 enum ExprAnalysisErrorCode {
5394 /// \brief A statement is not an expression statement.
5395 NotAnExpression,
5396 /// \brief Expression is not builtin binary or unary operation.
5397 NotABinaryOrUnaryExpression,
5398 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5399 NotAnUnaryIncDecExpression,
5400 /// \brief An expression is not of scalar type.
5401 NotAScalarType,
5402 /// \brief A binary operation is not an assignment operation.
5403 NotAnAssignmentOp,
5404 /// \brief RHS part of the binary operation is not a binary expression.
5405 NotABinaryExpression,
5406 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5407 /// expression.
5408 NotABinaryOperator,
5409 /// \brief RHS binary operation does not have reference to the updated LHS
5410 /// part.
5411 NotAnUpdateExpression,
5412 /// \brief No errors is found.
5413 NoError
5414 };
5415 /// \brief Reference to Sema.
5416 Sema &SemaRef;
5417 /// \brief A location for note diagnostics (when error is found).
5418 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005419 /// \brief 'x' lvalue part of the source atomic expression.
5420 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005421 /// \brief 'expr' rvalue part of the source atomic expression.
5422 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005423 /// \brief Helper expression of the form
5424 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5425 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5426 Expr *UpdateExpr;
5427 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5428 /// important for non-associative operations.
5429 bool IsXLHSInRHSPart;
5430 BinaryOperatorKind Op;
5431 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005432 /// \brief true if the source expression is a postfix unary operation, false
5433 /// if it is a prefix unary operation.
5434 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005435
5436public:
5437 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005438 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005439 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005440 /// \brief Check specified statement that it is suitable for 'atomic update'
5441 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005442 /// expression. If DiagId and NoteId == 0, then only check is performed
5443 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005444 /// \param DiagId Diagnostic which should be emitted if error is found.
5445 /// \param NoteId Diagnostic note for the main error message.
5446 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005447 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005448 /// \brief Return the 'x' lvalue part of the source atomic expression.
5449 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005450 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5451 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005452 /// \brief Return the update expression used in calculation of the updated
5453 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5454 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5455 Expr *getUpdateExpr() const { return UpdateExpr; }
5456 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5457 /// false otherwise.
5458 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5459
Alexey Bataevb78ca832015-04-01 03:33:17 +00005460 /// \brief true if the source expression is a postfix unary operation, false
5461 /// if it is a prefix unary operation.
5462 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5463
Alexey Bataev1d160b12015-03-13 12:27:31 +00005464private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005465 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5466 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005467};
5468} // namespace
5469
5470bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5471 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5472 ExprAnalysisErrorCode ErrorFound = NoError;
5473 SourceLocation ErrorLoc, NoteLoc;
5474 SourceRange ErrorRange, NoteRange;
5475 // Allowed constructs are:
5476 // x = x binop expr;
5477 // x = expr binop x;
5478 if (AtomicBinOp->getOpcode() == BO_Assign) {
5479 X = AtomicBinOp->getLHS();
5480 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5481 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5482 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5483 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5484 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005485 Op = AtomicInnerBinOp->getOpcode();
5486 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005487 auto *LHS = AtomicInnerBinOp->getLHS();
5488 auto *RHS = AtomicInnerBinOp->getRHS();
5489 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5490 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5491 /*Canonical=*/true);
5492 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5493 /*Canonical=*/true);
5494 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5495 /*Canonical=*/true);
5496 if (XId == LHSId) {
5497 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005498 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005499 } else if (XId == RHSId) {
5500 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005501 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005502 } else {
5503 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5504 ErrorRange = AtomicInnerBinOp->getSourceRange();
5505 NoteLoc = X->getExprLoc();
5506 NoteRange = X->getSourceRange();
5507 ErrorFound = NotAnUpdateExpression;
5508 }
5509 } else {
5510 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5511 ErrorRange = AtomicInnerBinOp->getSourceRange();
5512 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5513 NoteRange = SourceRange(NoteLoc, NoteLoc);
5514 ErrorFound = NotABinaryOperator;
5515 }
5516 } else {
5517 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5518 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5519 ErrorFound = NotABinaryExpression;
5520 }
5521 } else {
5522 ErrorLoc = AtomicBinOp->getExprLoc();
5523 ErrorRange = AtomicBinOp->getSourceRange();
5524 NoteLoc = AtomicBinOp->getOperatorLoc();
5525 NoteRange = SourceRange(NoteLoc, NoteLoc);
5526 ErrorFound = NotAnAssignmentOp;
5527 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005528 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005529 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5530 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5531 return true;
5532 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005533 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005534 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005535}
5536
5537bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5538 unsigned NoteId) {
5539 ExprAnalysisErrorCode ErrorFound = NoError;
5540 SourceLocation ErrorLoc, NoteLoc;
5541 SourceRange ErrorRange, NoteRange;
5542 // Allowed constructs are:
5543 // x++;
5544 // x--;
5545 // ++x;
5546 // --x;
5547 // x binop= expr;
5548 // x = x binop expr;
5549 // x = expr binop x;
5550 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5551 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5552 if (AtomicBody->getType()->isScalarType() ||
5553 AtomicBody->isInstantiationDependent()) {
5554 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5555 AtomicBody->IgnoreParenImpCasts())) {
5556 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005557 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005558 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005559 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005560 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005561 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005562 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005563 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5564 AtomicBody->IgnoreParenImpCasts())) {
5565 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005566 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005567 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005568 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5569 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005570 // Check for Unary Operation
5571 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005572 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005573 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5574 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005575 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005576 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5577 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005578 } else {
5579 ErrorFound = NotAnUnaryIncDecExpression;
5580 ErrorLoc = AtomicUnaryOp->getExprLoc();
5581 ErrorRange = AtomicUnaryOp->getSourceRange();
5582 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5583 NoteRange = SourceRange(NoteLoc, NoteLoc);
5584 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005585 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005586 ErrorFound = NotABinaryOrUnaryExpression;
5587 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5588 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5589 }
5590 } else {
5591 ErrorFound = NotAScalarType;
5592 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5593 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5594 }
5595 } else {
5596 ErrorFound = NotAnExpression;
5597 NoteLoc = ErrorLoc = S->getLocStart();
5598 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5599 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005600 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005601 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5602 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5603 return true;
5604 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005605 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005606 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005607 // Build an update expression of form 'OpaqueValueExpr(x) binop
5608 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5609 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5610 auto *OVEX = new (SemaRef.getASTContext())
5611 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5612 auto *OVEExpr = new (SemaRef.getASTContext())
5613 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5614 auto Update =
5615 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5616 IsXLHSInRHSPart ? OVEExpr : OVEX);
5617 if (Update.isInvalid())
5618 return true;
5619 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5620 Sema::AA_Casting);
5621 if (Update.isInvalid())
5622 return true;
5623 UpdateExpr = Update.get();
5624 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005625 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005626}
5627
Alexey Bataev0162e452014-07-22 10:10:35 +00005628StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5629 Stmt *AStmt,
5630 SourceLocation StartLoc,
5631 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005632 if (!AStmt)
5633 return StmtError();
5634
David Majnemer9d168222016-08-05 17:44:54 +00005635 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005636 // 1.2.2 OpenMP Language Terminology
5637 // Structured block - An executable statement with a single entry at the
5638 // top and a single exit at the bottom.
5639 // The point of exit cannot be a branch out of the structured block.
5640 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005641 OpenMPClauseKind AtomicKind = OMPC_unknown;
5642 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005643 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005644 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005645 C->getClauseKind() == OMPC_update ||
5646 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005647 if (AtomicKind != OMPC_unknown) {
5648 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5649 << SourceRange(C->getLocStart(), C->getLocEnd());
5650 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5651 << getOpenMPClauseName(AtomicKind);
5652 } else {
5653 AtomicKind = C->getClauseKind();
5654 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005655 }
5656 }
5657 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005658
Alexey Bataev459dec02014-07-24 06:46:57 +00005659 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005660 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5661 Body = EWC->getSubExpr();
5662
Alexey Bataev62cec442014-11-18 10:14:22 +00005663 Expr *X = nullptr;
5664 Expr *V = nullptr;
5665 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005666 Expr *UE = nullptr;
5667 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005668 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005669 // OpenMP [2.12.6, atomic Construct]
5670 // In the next expressions:
5671 // * x and v (as applicable) are both l-value expressions with scalar type.
5672 // * During the execution of an atomic region, multiple syntactic
5673 // occurrences of x must designate the same storage location.
5674 // * Neither of v and expr (as applicable) may access the storage location
5675 // designated by x.
5676 // * Neither of x and expr (as applicable) may access the storage location
5677 // designated by v.
5678 // * expr is an expression with scalar type.
5679 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5680 // * binop, binop=, ++, and -- are not overloaded operators.
5681 // * The expression x binop expr must be numerically equivalent to x binop
5682 // (expr). This requirement is satisfied if the operators in expr have
5683 // precedence greater than binop, or by using parentheses around expr or
5684 // subexpressions of expr.
5685 // * The expression expr binop x must be numerically equivalent to (expr)
5686 // binop x. This requirement is satisfied if the operators in expr have
5687 // precedence equal to or greater than binop, or by using parentheses around
5688 // expr or subexpressions of expr.
5689 // * For forms that allow multiple occurrences of x, the number of times
5690 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005691 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005692 enum {
5693 NotAnExpression,
5694 NotAnAssignmentOp,
5695 NotAScalarType,
5696 NotAnLValue,
5697 NoError
5698 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005699 SourceLocation ErrorLoc, NoteLoc;
5700 SourceRange ErrorRange, NoteRange;
5701 // If clause is read:
5702 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005703 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5704 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005705 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5706 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5707 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5708 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5709 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5710 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5711 if (!X->isLValue() || !V->isLValue()) {
5712 auto NotLValueExpr = X->isLValue() ? V : X;
5713 ErrorFound = NotAnLValue;
5714 ErrorLoc = AtomicBinOp->getExprLoc();
5715 ErrorRange = AtomicBinOp->getSourceRange();
5716 NoteLoc = NotLValueExpr->getExprLoc();
5717 NoteRange = NotLValueExpr->getSourceRange();
5718 }
5719 } else if (!X->isInstantiationDependent() ||
5720 !V->isInstantiationDependent()) {
5721 auto NotScalarExpr =
5722 (X->isInstantiationDependent() || X->getType()->isScalarType())
5723 ? V
5724 : X;
5725 ErrorFound = NotAScalarType;
5726 ErrorLoc = AtomicBinOp->getExprLoc();
5727 ErrorRange = AtomicBinOp->getSourceRange();
5728 NoteLoc = NotScalarExpr->getExprLoc();
5729 NoteRange = NotScalarExpr->getSourceRange();
5730 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005731 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005732 ErrorFound = NotAnAssignmentOp;
5733 ErrorLoc = AtomicBody->getExprLoc();
5734 ErrorRange = AtomicBody->getSourceRange();
5735 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5736 : AtomicBody->getExprLoc();
5737 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5738 : AtomicBody->getSourceRange();
5739 }
5740 } else {
5741 ErrorFound = NotAnExpression;
5742 NoteLoc = ErrorLoc = Body->getLocStart();
5743 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005744 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005745 if (ErrorFound != NoError) {
5746 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5747 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005748 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5749 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005750 return StmtError();
5751 } else if (CurContext->isDependentContext())
5752 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005753 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005754 enum {
5755 NotAnExpression,
5756 NotAnAssignmentOp,
5757 NotAScalarType,
5758 NotAnLValue,
5759 NoError
5760 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005761 SourceLocation ErrorLoc, NoteLoc;
5762 SourceRange ErrorRange, NoteRange;
5763 // If clause is write:
5764 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005765 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5766 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005767 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5768 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005769 X = AtomicBinOp->getLHS();
5770 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005771 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5772 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5773 if (!X->isLValue()) {
5774 ErrorFound = NotAnLValue;
5775 ErrorLoc = AtomicBinOp->getExprLoc();
5776 ErrorRange = AtomicBinOp->getSourceRange();
5777 NoteLoc = X->getExprLoc();
5778 NoteRange = X->getSourceRange();
5779 }
5780 } else if (!X->isInstantiationDependent() ||
5781 !E->isInstantiationDependent()) {
5782 auto NotScalarExpr =
5783 (X->isInstantiationDependent() || X->getType()->isScalarType())
5784 ? E
5785 : X;
5786 ErrorFound = NotAScalarType;
5787 ErrorLoc = AtomicBinOp->getExprLoc();
5788 ErrorRange = AtomicBinOp->getSourceRange();
5789 NoteLoc = NotScalarExpr->getExprLoc();
5790 NoteRange = NotScalarExpr->getSourceRange();
5791 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005792 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005793 ErrorFound = NotAnAssignmentOp;
5794 ErrorLoc = AtomicBody->getExprLoc();
5795 ErrorRange = AtomicBody->getSourceRange();
5796 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5797 : AtomicBody->getExprLoc();
5798 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5799 : AtomicBody->getSourceRange();
5800 }
5801 } else {
5802 ErrorFound = NotAnExpression;
5803 NoteLoc = ErrorLoc = Body->getLocStart();
5804 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005805 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005806 if (ErrorFound != NoError) {
5807 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5808 << ErrorRange;
5809 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5810 << NoteRange;
5811 return StmtError();
5812 } else if (CurContext->isDependentContext())
5813 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005814 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005815 // If clause is update:
5816 // x++;
5817 // x--;
5818 // ++x;
5819 // --x;
5820 // x binop= expr;
5821 // x = x binop expr;
5822 // x = expr binop x;
5823 OpenMPAtomicUpdateChecker Checker(*this);
5824 if (Checker.checkStatement(
5825 Body, (AtomicKind == OMPC_update)
5826 ? diag::err_omp_atomic_update_not_expression_statement
5827 : diag::err_omp_atomic_not_expression_statement,
5828 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005829 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005830 if (!CurContext->isDependentContext()) {
5831 E = Checker.getExpr();
5832 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005833 UE = Checker.getUpdateExpr();
5834 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005835 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005836 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005837 enum {
5838 NotAnAssignmentOp,
5839 NotACompoundStatement,
5840 NotTwoSubstatements,
5841 NotASpecificExpression,
5842 NoError
5843 } ErrorFound = NoError;
5844 SourceLocation ErrorLoc, NoteLoc;
5845 SourceRange ErrorRange, NoteRange;
5846 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5847 // If clause is a capture:
5848 // v = x++;
5849 // v = x--;
5850 // v = ++x;
5851 // v = --x;
5852 // v = x binop= expr;
5853 // v = x = x binop expr;
5854 // v = x = expr binop x;
5855 auto *AtomicBinOp =
5856 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5857 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5858 V = AtomicBinOp->getLHS();
5859 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5860 OpenMPAtomicUpdateChecker Checker(*this);
5861 if (Checker.checkStatement(
5862 Body, diag::err_omp_atomic_capture_not_expression_statement,
5863 diag::note_omp_atomic_update))
5864 return StmtError();
5865 E = Checker.getExpr();
5866 X = Checker.getX();
5867 UE = Checker.getUpdateExpr();
5868 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5869 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005870 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005871 ErrorLoc = AtomicBody->getExprLoc();
5872 ErrorRange = AtomicBody->getSourceRange();
5873 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5874 : AtomicBody->getExprLoc();
5875 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5876 : AtomicBody->getSourceRange();
5877 ErrorFound = NotAnAssignmentOp;
5878 }
5879 if (ErrorFound != NoError) {
5880 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5881 << ErrorRange;
5882 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5883 return StmtError();
5884 } else if (CurContext->isDependentContext()) {
5885 UE = V = E = X = nullptr;
5886 }
5887 } else {
5888 // If clause is a capture:
5889 // { v = x; x = expr; }
5890 // { v = x; x++; }
5891 // { v = x; x--; }
5892 // { v = x; ++x; }
5893 // { v = x; --x; }
5894 // { v = x; x binop= expr; }
5895 // { v = x; x = x binop expr; }
5896 // { v = x; x = expr binop x; }
5897 // { x++; v = x; }
5898 // { x--; v = x; }
5899 // { ++x; v = x; }
5900 // { --x; v = x; }
5901 // { x binop= expr; v = x; }
5902 // { x = x binop expr; v = x; }
5903 // { x = expr binop x; v = x; }
5904 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5905 // Check that this is { expr1; expr2; }
5906 if (CS->size() == 2) {
5907 auto *First = CS->body_front();
5908 auto *Second = CS->body_back();
5909 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5910 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5911 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5912 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5913 // Need to find what subexpression is 'v' and what is 'x'.
5914 OpenMPAtomicUpdateChecker Checker(*this);
5915 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5916 BinaryOperator *BinOp = nullptr;
5917 if (IsUpdateExprFound) {
5918 BinOp = dyn_cast<BinaryOperator>(First);
5919 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5920 }
5921 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5922 // { v = x; x++; }
5923 // { v = x; x--; }
5924 // { v = x; ++x; }
5925 // { v = x; --x; }
5926 // { v = x; x binop= expr; }
5927 // { v = x; x = x binop expr; }
5928 // { v = x; x = expr binop x; }
5929 // Check that the first expression has form v = x.
5930 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5931 llvm::FoldingSetNodeID XId, PossibleXId;
5932 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5933 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5934 IsUpdateExprFound = XId == PossibleXId;
5935 if (IsUpdateExprFound) {
5936 V = BinOp->getLHS();
5937 X = Checker.getX();
5938 E = Checker.getExpr();
5939 UE = Checker.getUpdateExpr();
5940 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005941 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005942 }
5943 }
5944 if (!IsUpdateExprFound) {
5945 IsUpdateExprFound = !Checker.checkStatement(First);
5946 BinOp = nullptr;
5947 if (IsUpdateExprFound) {
5948 BinOp = dyn_cast<BinaryOperator>(Second);
5949 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5950 }
5951 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5952 // { x++; v = x; }
5953 // { x--; v = x; }
5954 // { ++x; v = x; }
5955 // { --x; v = x; }
5956 // { x binop= expr; v = x; }
5957 // { x = x binop expr; v = x; }
5958 // { x = expr binop x; v = x; }
5959 // Check that the second expression has form v = x.
5960 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5961 llvm::FoldingSetNodeID XId, PossibleXId;
5962 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5963 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5964 IsUpdateExprFound = XId == PossibleXId;
5965 if (IsUpdateExprFound) {
5966 V = BinOp->getLHS();
5967 X = Checker.getX();
5968 E = Checker.getExpr();
5969 UE = Checker.getUpdateExpr();
5970 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005971 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005972 }
5973 }
5974 }
5975 if (!IsUpdateExprFound) {
5976 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005977 auto *FirstExpr = dyn_cast<Expr>(First);
5978 auto *SecondExpr = dyn_cast<Expr>(Second);
5979 if (!FirstExpr || !SecondExpr ||
5980 !(FirstExpr->isInstantiationDependent() ||
5981 SecondExpr->isInstantiationDependent())) {
5982 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5983 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005984 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005985 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5986 : First->getLocStart();
5987 NoteRange = ErrorRange = FirstBinOp
5988 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005989 : SourceRange(ErrorLoc, ErrorLoc);
5990 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005991 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5992 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5993 ErrorFound = NotAnAssignmentOp;
5994 NoteLoc = ErrorLoc = SecondBinOp
5995 ? SecondBinOp->getOperatorLoc()
5996 : Second->getLocStart();
5997 NoteRange = ErrorRange =
5998 SecondBinOp ? SecondBinOp->getSourceRange()
5999 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006000 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006001 auto *PossibleXRHSInFirst =
6002 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6003 auto *PossibleXLHSInSecond =
6004 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6005 llvm::FoldingSetNodeID X1Id, X2Id;
6006 PossibleXRHSInFirst->Profile(X1Id, Context,
6007 /*Canonical=*/true);
6008 PossibleXLHSInSecond->Profile(X2Id, Context,
6009 /*Canonical=*/true);
6010 IsUpdateExprFound = X1Id == X2Id;
6011 if (IsUpdateExprFound) {
6012 V = FirstBinOp->getLHS();
6013 X = SecondBinOp->getLHS();
6014 E = SecondBinOp->getRHS();
6015 UE = nullptr;
6016 IsXLHSInRHSPart = false;
6017 IsPostfixUpdate = true;
6018 } else {
6019 ErrorFound = NotASpecificExpression;
6020 ErrorLoc = FirstBinOp->getExprLoc();
6021 ErrorRange = FirstBinOp->getSourceRange();
6022 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6023 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6024 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006025 }
6026 }
6027 }
6028 }
6029 } else {
6030 NoteLoc = ErrorLoc = Body->getLocStart();
6031 NoteRange = ErrorRange =
6032 SourceRange(Body->getLocStart(), Body->getLocStart());
6033 ErrorFound = NotTwoSubstatements;
6034 }
6035 } else {
6036 NoteLoc = ErrorLoc = Body->getLocStart();
6037 NoteRange = ErrorRange =
6038 SourceRange(Body->getLocStart(), Body->getLocStart());
6039 ErrorFound = NotACompoundStatement;
6040 }
6041 if (ErrorFound != NoError) {
6042 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6043 << ErrorRange;
6044 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6045 return StmtError();
6046 } else if (CurContext->isDependentContext()) {
6047 UE = V = E = X = nullptr;
6048 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006049 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006050 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006051
6052 getCurFunction()->setHasBranchProtectedScope();
6053
Alexey Bataev62cec442014-11-18 10:14:22 +00006054 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006055 X, V, E, UE, IsXLHSInRHSPart,
6056 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006057}
6058
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006059StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6060 Stmt *AStmt,
6061 SourceLocation StartLoc,
6062 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006063 if (!AStmt)
6064 return StmtError();
6065
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006066 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6067 // 1.2.2 OpenMP Language Terminology
6068 // Structured block - An executable statement with a single entry at the
6069 // top and a single exit at the bottom.
6070 // The point of exit cannot be a branch out of the structured block.
6071 // longjmp() and throw() must not violate the entry/exit criteria.
6072 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006073
Alexey Bataev13314bf2014-10-09 04:18:56 +00006074 // OpenMP [2.16, Nesting of Regions]
6075 // If specified, a teams construct must be contained within a target
6076 // construct. That target construct must contain no statements or directives
6077 // outside of the teams construct.
6078 if (DSAStack->hasInnerTeamsRegion()) {
6079 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6080 bool OMPTeamsFound = true;
6081 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6082 auto I = CS->body_begin();
6083 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006084 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006085 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6086 OMPTeamsFound = false;
6087 break;
6088 }
6089 ++I;
6090 }
6091 assert(I != CS->body_end() && "Not found statement");
6092 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006093 } else {
6094 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6095 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006096 }
6097 if (!OMPTeamsFound) {
6098 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6099 Diag(DSAStack->getInnerTeamsRegionLoc(),
6100 diag::note_omp_nested_teams_construct_here);
6101 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6102 << isa<OMPExecutableDirective>(S);
6103 return StmtError();
6104 }
6105 }
6106
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006107 getCurFunction()->setHasBranchProtectedScope();
6108
6109 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6110}
6111
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006112StmtResult
6113Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6114 Stmt *AStmt, SourceLocation StartLoc,
6115 SourceLocation EndLoc) {
6116 if (!AStmt)
6117 return StmtError();
6118
6119 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6120 // 1.2.2 OpenMP Language Terminology
6121 // Structured block - An executable statement with a single entry at the
6122 // top and a single exit at the bottom.
6123 // The point of exit cannot be a branch out of the structured block.
6124 // longjmp() and throw() must not violate the entry/exit criteria.
6125 CS->getCapturedDecl()->setNothrow();
6126
6127 getCurFunction()->setHasBranchProtectedScope();
6128
6129 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6130 AStmt);
6131}
6132
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006133StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6134 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6135 SourceLocation EndLoc,
6136 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6137 if (!AStmt)
6138 return StmtError();
6139
6140 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6141 // 1.2.2 OpenMP Language Terminology
6142 // Structured block - An executable statement with a single entry at the
6143 // top and a single exit at the bottom.
6144 // The point of exit cannot be a branch out of the structured block.
6145 // longjmp() and throw() must not violate the entry/exit criteria.
6146 CS->getCapturedDecl()->setNothrow();
6147
6148 OMPLoopDirective::HelperExprs B;
6149 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6150 // define the nested loops number.
6151 unsigned NestedLoopCount =
6152 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6153 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6154 VarsWithImplicitDSA, B);
6155 if (NestedLoopCount == 0)
6156 return StmtError();
6157
6158 assert((CurContext->isDependentContext() || B.builtAll()) &&
6159 "omp target parallel for loop exprs were not built");
6160
6161 if (!CurContext->isDependentContext()) {
6162 // Finalize the clauses that need pre-built expressions for CodeGen.
6163 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006164 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006165 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006166 B.NumIterations, *this, CurScope,
6167 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006168 return StmtError();
6169 }
6170 }
6171
6172 getCurFunction()->setHasBranchProtectedScope();
6173 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6174 NestedLoopCount, Clauses, AStmt,
6175 B, DSAStack->isCancelRegion());
6176}
6177
Alexey Bataev95b64a92017-05-30 16:00:04 +00006178/// Check for existence of a map clause in the list of clauses.
6179static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6180 const OpenMPClauseKind K) {
6181 return llvm::any_of(
6182 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6183}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006184
Alexey Bataev95b64a92017-05-30 16:00:04 +00006185template <typename... Params>
6186static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6187 const Params... ClauseTypes) {
6188 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006189}
6190
Michael Wong65f367f2015-07-21 13:44:28 +00006191StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6192 Stmt *AStmt,
6193 SourceLocation StartLoc,
6194 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006195 if (!AStmt)
6196 return StmtError();
6197
6198 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6199
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006200 // OpenMP [2.10.1, Restrictions, p. 97]
6201 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006202 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6203 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6204 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006205 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006206 return StmtError();
6207 }
6208
Michael Wong65f367f2015-07-21 13:44:28 +00006209 getCurFunction()->setHasBranchProtectedScope();
6210
6211 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6212 AStmt);
6213}
6214
Samuel Antaodf67fc42016-01-19 19:15:56 +00006215StmtResult
6216Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6217 SourceLocation StartLoc,
6218 SourceLocation EndLoc) {
6219 // OpenMP [2.10.2, Restrictions, p. 99]
6220 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006221 if (!hasClauses(Clauses, OMPC_map)) {
6222 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6223 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006224 return StmtError();
6225 }
6226
6227 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6228 Clauses);
6229}
6230
Samuel Antao72590762016-01-19 20:04:50 +00006231StmtResult
6232Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6233 SourceLocation StartLoc,
6234 SourceLocation EndLoc) {
6235 // OpenMP [2.10.3, Restrictions, p. 102]
6236 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006237 if (!hasClauses(Clauses, OMPC_map)) {
6238 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6239 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006240 return StmtError();
6241 }
6242
6243 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6244}
6245
Samuel Antao686c70c2016-05-26 17:30:50 +00006246StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6247 SourceLocation StartLoc,
6248 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006249 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006250 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6251 return StmtError();
6252 }
6253 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6254}
6255
Alexey Bataev13314bf2014-10-09 04:18:56 +00006256StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6257 Stmt *AStmt, SourceLocation StartLoc,
6258 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006259 if (!AStmt)
6260 return StmtError();
6261
Alexey Bataev13314bf2014-10-09 04:18:56 +00006262 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6263 // 1.2.2 OpenMP Language Terminology
6264 // Structured block - An executable statement with a single entry at the
6265 // top and a single exit at the bottom.
6266 // The point of exit cannot be a branch out of the structured block.
6267 // longjmp() and throw() must not violate the entry/exit criteria.
6268 CS->getCapturedDecl()->setNothrow();
6269
6270 getCurFunction()->setHasBranchProtectedScope();
6271
6272 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6273}
6274
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006275StmtResult
6276Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6277 SourceLocation EndLoc,
6278 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006279 if (DSAStack->isParentNowaitRegion()) {
6280 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6281 return StmtError();
6282 }
6283 if (DSAStack->isParentOrderedRegion()) {
6284 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6285 return StmtError();
6286 }
6287 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6288 CancelRegion);
6289}
6290
Alexey Bataev87933c72015-09-18 08:07:34 +00006291StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6292 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006293 SourceLocation EndLoc,
6294 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006295 if (DSAStack->isParentNowaitRegion()) {
6296 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6297 return StmtError();
6298 }
6299 if (DSAStack->isParentOrderedRegion()) {
6300 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6301 return StmtError();
6302 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006303 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006304 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6305 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006306}
6307
Alexey Bataev382967a2015-12-08 12:06:20 +00006308static bool checkGrainsizeNumTasksClauses(Sema &S,
6309 ArrayRef<OMPClause *> Clauses) {
6310 OMPClause *PrevClause = nullptr;
6311 bool ErrorFound = false;
6312 for (auto *C : Clauses) {
6313 if (C->getClauseKind() == OMPC_grainsize ||
6314 C->getClauseKind() == OMPC_num_tasks) {
6315 if (!PrevClause)
6316 PrevClause = C;
6317 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6318 S.Diag(C->getLocStart(),
6319 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6320 << getOpenMPClauseName(C->getClauseKind())
6321 << getOpenMPClauseName(PrevClause->getClauseKind());
6322 S.Diag(PrevClause->getLocStart(),
6323 diag::note_omp_previous_grainsize_num_tasks)
6324 << getOpenMPClauseName(PrevClause->getClauseKind());
6325 ErrorFound = true;
6326 }
6327 }
6328 }
6329 return ErrorFound;
6330}
6331
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006332static bool checkReductionClauseWithNogroup(Sema &S,
6333 ArrayRef<OMPClause *> Clauses) {
6334 OMPClause *ReductionClause = nullptr;
6335 OMPClause *NogroupClause = nullptr;
6336 for (auto *C : Clauses) {
6337 if (C->getClauseKind() == OMPC_reduction) {
6338 ReductionClause = C;
6339 if (NogroupClause)
6340 break;
6341 continue;
6342 }
6343 if (C->getClauseKind() == OMPC_nogroup) {
6344 NogroupClause = C;
6345 if (ReductionClause)
6346 break;
6347 continue;
6348 }
6349 }
6350 if (ReductionClause && NogroupClause) {
6351 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6352 << SourceRange(NogroupClause->getLocStart(),
6353 NogroupClause->getLocEnd());
6354 return true;
6355 }
6356 return false;
6357}
6358
Alexey Bataev49f6e782015-12-01 04:18:41 +00006359StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6360 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6361 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006362 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006363 if (!AStmt)
6364 return StmtError();
6365
6366 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6367 OMPLoopDirective::HelperExprs B;
6368 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6369 // define the nested loops number.
6370 unsigned NestedLoopCount =
6371 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006372 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006373 VarsWithImplicitDSA, B);
6374 if (NestedLoopCount == 0)
6375 return StmtError();
6376
6377 assert((CurContext->isDependentContext() || B.builtAll()) &&
6378 "omp for loop exprs were not built");
6379
Alexey Bataev382967a2015-12-08 12:06:20 +00006380 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6381 // The grainsize clause and num_tasks clause are mutually exclusive and may
6382 // not appear on the same taskloop directive.
6383 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6384 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006385 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6386 // If a reduction clause is present on the taskloop directive, the nogroup
6387 // clause must not be specified.
6388 if (checkReductionClauseWithNogroup(*this, Clauses))
6389 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006390
Alexey Bataev49f6e782015-12-01 04:18:41 +00006391 getCurFunction()->setHasBranchProtectedScope();
6392 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6393 NestedLoopCount, Clauses, AStmt, B);
6394}
6395
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006396StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6397 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6398 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006399 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006400 if (!AStmt)
6401 return StmtError();
6402
6403 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6404 OMPLoopDirective::HelperExprs B;
6405 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6406 // define the nested loops number.
6407 unsigned NestedLoopCount =
6408 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6409 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6410 VarsWithImplicitDSA, B);
6411 if (NestedLoopCount == 0)
6412 return StmtError();
6413
6414 assert((CurContext->isDependentContext() || B.builtAll()) &&
6415 "omp for loop exprs were not built");
6416
Alexey Bataev5a3af132016-03-29 08:58:54 +00006417 if (!CurContext->isDependentContext()) {
6418 // Finalize the clauses that need pre-built expressions for CodeGen.
6419 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006420 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006421 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006422 B.NumIterations, *this, CurScope,
6423 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006424 return StmtError();
6425 }
6426 }
6427
Alexey Bataev382967a2015-12-08 12:06:20 +00006428 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6429 // The grainsize clause and num_tasks clause are mutually exclusive and may
6430 // not appear on the same taskloop directive.
6431 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6432 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006433 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6434 // If a reduction clause is present on the taskloop directive, the nogroup
6435 // clause must not be specified.
6436 if (checkReductionClauseWithNogroup(*this, Clauses))
6437 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006438
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006439 getCurFunction()->setHasBranchProtectedScope();
6440 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6441 NestedLoopCount, Clauses, AStmt, B);
6442}
6443
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006444StmtResult Sema::ActOnOpenMPDistributeDirective(
6445 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6446 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006447 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006448 if (!AStmt)
6449 return StmtError();
6450
6451 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6452 OMPLoopDirective::HelperExprs B;
6453 // In presence of clause 'collapse' with number of loops, it will
6454 // define the nested loops number.
6455 unsigned NestedLoopCount =
6456 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6457 nullptr /*ordered not a clause on distribute*/, AStmt,
6458 *this, *DSAStack, VarsWithImplicitDSA, B);
6459 if (NestedLoopCount == 0)
6460 return StmtError();
6461
6462 assert((CurContext->isDependentContext() || B.builtAll()) &&
6463 "omp for loop exprs were not built");
6464
6465 getCurFunction()->setHasBranchProtectedScope();
6466 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6467 NestedLoopCount, Clauses, AStmt, B);
6468}
6469
Carlo Bertolli9925f152016-06-27 14:55:37 +00006470StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6471 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6472 SourceLocation EndLoc,
6473 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6474 if (!AStmt)
6475 return StmtError();
6476
6477 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6478 // 1.2.2 OpenMP Language Terminology
6479 // Structured block - An executable statement with a single entry at the
6480 // top and a single exit at the bottom.
6481 // The point of exit cannot be a branch out of the structured block.
6482 // longjmp() and throw() must not violate the entry/exit criteria.
6483 CS->getCapturedDecl()->setNothrow();
6484
6485 OMPLoopDirective::HelperExprs B;
6486 // In presence of clause 'collapse' with number of loops, it will
6487 // define the nested loops number.
6488 unsigned NestedLoopCount = CheckOpenMPLoop(
6489 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6490 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6491 VarsWithImplicitDSA, B);
6492 if (NestedLoopCount == 0)
6493 return StmtError();
6494
6495 assert((CurContext->isDependentContext() || B.builtAll()) &&
6496 "omp for loop exprs were not built");
6497
6498 getCurFunction()->setHasBranchProtectedScope();
6499 return OMPDistributeParallelForDirective::Create(
6500 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6501}
6502
Kelvin Li4a39add2016-07-05 05:00:15 +00006503StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6504 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6505 SourceLocation EndLoc,
6506 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6507 if (!AStmt)
6508 return StmtError();
6509
6510 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6511 // 1.2.2 OpenMP Language Terminology
6512 // Structured block - An executable statement with a single entry at the
6513 // top and a single exit at the bottom.
6514 // The point of exit cannot be a branch out of the structured block.
6515 // longjmp() and throw() must not violate the entry/exit criteria.
6516 CS->getCapturedDecl()->setNothrow();
6517
6518 OMPLoopDirective::HelperExprs B;
6519 // In presence of clause 'collapse' with number of loops, it will
6520 // define the nested loops number.
6521 unsigned NestedLoopCount = CheckOpenMPLoop(
6522 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6523 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6524 VarsWithImplicitDSA, B);
6525 if (NestedLoopCount == 0)
6526 return StmtError();
6527
6528 assert((CurContext->isDependentContext() || B.builtAll()) &&
6529 "omp for loop exprs were not built");
6530
Kelvin Lic5609492016-07-15 04:39:07 +00006531 if (checkSimdlenSafelenSpecified(*this, Clauses))
6532 return StmtError();
6533
Kelvin Li4a39add2016-07-05 05:00:15 +00006534 getCurFunction()->setHasBranchProtectedScope();
6535 return OMPDistributeParallelForSimdDirective::Create(
6536 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6537}
6538
Kelvin Li787f3fc2016-07-06 04:45:38 +00006539StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6540 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6541 SourceLocation EndLoc,
6542 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6543 if (!AStmt)
6544 return StmtError();
6545
6546 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6547 // 1.2.2 OpenMP Language Terminology
6548 // Structured block - An executable statement with a single entry at the
6549 // top and a single exit at the bottom.
6550 // The point of exit cannot be a branch out of the structured block.
6551 // longjmp() and throw() must not violate the entry/exit criteria.
6552 CS->getCapturedDecl()->setNothrow();
6553
6554 OMPLoopDirective::HelperExprs B;
6555 // In presence of clause 'collapse' with number of loops, it will
6556 // define the nested loops number.
6557 unsigned NestedLoopCount =
6558 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6559 nullptr /*ordered not a clause on distribute*/, AStmt,
6560 *this, *DSAStack, VarsWithImplicitDSA, B);
6561 if (NestedLoopCount == 0)
6562 return StmtError();
6563
6564 assert((CurContext->isDependentContext() || B.builtAll()) &&
6565 "omp for loop exprs were not built");
6566
Kelvin Lic5609492016-07-15 04:39:07 +00006567 if (checkSimdlenSafelenSpecified(*this, Clauses))
6568 return StmtError();
6569
Kelvin Li787f3fc2016-07-06 04:45:38 +00006570 getCurFunction()->setHasBranchProtectedScope();
6571 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6572 NestedLoopCount, Clauses, AStmt, B);
6573}
6574
Kelvin Lia579b912016-07-14 02:54:56 +00006575StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6576 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6577 SourceLocation EndLoc,
6578 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6579 if (!AStmt)
6580 return StmtError();
6581
6582 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6583 // 1.2.2 OpenMP Language Terminology
6584 // Structured block - An executable statement with a single entry at the
6585 // top and a single exit at the bottom.
6586 // The point of exit cannot be a branch out of the structured block.
6587 // longjmp() and throw() must not violate the entry/exit criteria.
6588 CS->getCapturedDecl()->setNothrow();
6589
6590 OMPLoopDirective::HelperExprs B;
6591 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6592 // define the nested loops number.
6593 unsigned NestedLoopCount = CheckOpenMPLoop(
6594 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6595 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6596 VarsWithImplicitDSA, B);
6597 if (NestedLoopCount == 0)
6598 return StmtError();
6599
6600 assert((CurContext->isDependentContext() || B.builtAll()) &&
6601 "omp target parallel for simd loop exprs were not built");
6602
6603 if (!CurContext->isDependentContext()) {
6604 // Finalize the clauses that need pre-built expressions for CodeGen.
6605 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006606 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006607 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6608 B.NumIterations, *this, CurScope,
6609 DSAStack))
6610 return StmtError();
6611 }
6612 }
Kelvin Lic5609492016-07-15 04:39:07 +00006613 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006614 return StmtError();
6615
6616 getCurFunction()->setHasBranchProtectedScope();
6617 return OMPTargetParallelForSimdDirective::Create(
6618 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6619}
6620
Kelvin Li986330c2016-07-20 22:57:10 +00006621StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6622 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6623 SourceLocation EndLoc,
6624 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6625 if (!AStmt)
6626 return StmtError();
6627
6628 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6629 // 1.2.2 OpenMP Language Terminology
6630 // Structured block - An executable statement with a single entry at the
6631 // top and a single exit at the bottom.
6632 // The point of exit cannot be a branch out of the structured block.
6633 // longjmp() and throw() must not violate the entry/exit criteria.
6634 CS->getCapturedDecl()->setNothrow();
6635
6636 OMPLoopDirective::HelperExprs B;
6637 // In presence of clause 'collapse' with number of loops, it will define the
6638 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006639 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006640 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6641 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6642 VarsWithImplicitDSA, B);
6643 if (NestedLoopCount == 0)
6644 return StmtError();
6645
6646 assert((CurContext->isDependentContext() || B.builtAll()) &&
6647 "omp target simd loop exprs were not built");
6648
6649 if (!CurContext->isDependentContext()) {
6650 // Finalize the clauses that need pre-built expressions for CodeGen.
6651 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006652 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006653 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6654 B.NumIterations, *this, CurScope,
6655 DSAStack))
6656 return StmtError();
6657 }
6658 }
6659
6660 if (checkSimdlenSafelenSpecified(*this, Clauses))
6661 return StmtError();
6662
6663 getCurFunction()->setHasBranchProtectedScope();
6664 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6665 NestedLoopCount, Clauses, AStmt, B);
6666}
6667
Kelvin Li02532872016-08-05 14:37:37 +00006668StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6669 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6670 SourceLocation EndLoc,
6671 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6672 if (!AStmt)
6673 return StmtError();
6674
6675 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6676 // 1.2.2 OpenMP Language Terminology
6677 // Structured block - An executable statement with a single entry at the
6678 // top and a single exit at the bottom.
6679 // The point of exit cannot be a branch out of the structured block.
6680 // longjmp() and throw() must not violate the entry/exit criteria.
6681 CS->getCapturedDecl()->setNothrow();
6682
6683 OMPLoopDirective::HelperExprs B;
6684 // In presence of clause 'collapse' with number of loops, it will
6685 // define the nested loops number.
6686 unsigned NestedLoopCount =
6687 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6688 nullptr /*ordered not a clause on distribute*/, AStmt,
6689 *this, *DSAStack, VarsWithImplicitDSA, B);
6690 if (NestedLoopCount == 0)
6691 return StmtError();
6692
6693 assert((CurContext->isDependentContext() || B.builtAll()) &&
6694 "omp teams distribute loop exprs were not built");
6695
6696 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006697 return OMPTeamsDistributeDirective::Create(
6698 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006699}
6700
Kelvin Li4e325f72016-10-25 12:50:55 +00006701StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6702 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6703 SourceLocation EndLoc,
6704 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6705 if (!AStmt)
6706 return StmtError();
6707
6708 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6709 // 1.2.2 OpenMP Language Terminology
6710 // Structured block - An executable statement with a single entry at the
6711 // top and a single exit at the bottom.
6712 // The point of exit cannot be a branch out of the structured block.
6713 // longjmp() and throw() must not violate the entry/exit criteria.
6714 CS->getCapturedDecl()->setNothrow();
6715
6716 OMPLoopDirective::HelperExprs B;
6717 // In presence of clause 'collapse' with number of loops, it will
6718 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006719 unsigned NestedLoopCount = CheckOpenMPLoop(
6720 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6721 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6722 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006723
6724 if (NestedLoopCount == 0)
6725 return StmtError();
6726
6727 assert((CurContext->isDependentContext() || B.builtAll()) &&
6728 "omp teams distribute simd loop exprs were not built");
6729
6730 if (!CurContext->isDependentContext()) {
6731 // Finalize the clauses that need pre-built expressions for CodeGen.
6732 for (auto C : Clauses) {
6733 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6734 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6735 B.NumIterations, *this, CurScope,
6736 DSAStack))
6737 return StmtError();
6738 }
6739 }
6740
6741 if (checkSimdlenSafelenSpecified(*this, Clauses))
6742 return StmtError();
6743
6744 getCurFunction()->setHasBranchProtectedScope();
6745 return OMPTeamsDistributeSimdDirective::Create(
6746 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6747}
6748
Kelvin Li579e41c2016-11-30 23:51:03 +00006749StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6750 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6751 SourceLocation EndLoc,
6752 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6753 if (!AStmt)
6754 return StmtError();
6755
6756 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6757 // 1.2.2 OpenMP Language Terminology
6758 // Structured block - An executable statement with a single entry at the
6759 // top and a single exit at the bottom.
6760 // The point of exit cannot be a branch out of the structured block.
6761 // longjmp() and throw() must not violate the entry/exit criteria.
6762 CS->getCapturedDecl()->setNothrow();
6763
6764 OMPLoopDirective::HelperExprs B;
6765 // In presence of clause 'collapse' with number of loops, it will
6766 // define the nested loops number.
6767 auto NestedLoopCount = CheckOpenMPLoop(
6768 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6769 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6770 VarsWithImplicitDSA, B);
6771
6772 if (NestedLoopCount == 0)
6773 return StmtError();
6774
6775 assert((CurContext->isDependentContext() || B.builtAll()) &&
6776 "omp for loop exprs were not built");
6777
6778 if (!CurContext->isDependentContext()) {
6779 // Finalize the clauses that need pre-built expressions for CodeGen.
6780 for (auto C : Clauses) {
6781 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6782 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6783 B.NumIterations, *this, CurScope,
6784 DSAStack))
6785 return StmtError();
6786 }
6787 }
6788
6789 if (checkSimdlenSafelenSpecified(*this, Clauses))
6790 return StmtError();
6791
6792 getCurFunction()->setHasBranchProtectedScope();
6793 return OMPTeamsDistributeParallelForSimdDirective::Create(
6794 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6795}
6796
Kelvin Li7ade93f2016-12-09 03:24:30 +00006797StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6798 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6799 SourceLocation EndLoc,
6800 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6801 if (!AStmt)
6802 return StmtError();
6803
6804 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6805 // 1.2.2 OpenMP Language Terminology
6806 // Structured block - An executable statement with a single entry at the
6807 // top and a single exit at the bottom.
6808 // The point of exit cannot be a branch out of the structured block.
6809 // longjmp() and throw() must not violate the entry/exit criteria.
6810 CS->getCapturedDecl()->setNothrow();
6811
6812 OMPLoopDirective::HelperExprs B;
6813 // In presence of clause 'collapse' with number of loops, it will
6814 // define the nested loops number.
6815 unsigned NestedLoopCount = CheckOpenMPLoop(
6816 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6817 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6818 VarsWithImplicitDSA, B);
6819
6820 if (NestedLoopCount == 0)
6821 return StmtError();
6822
6823 assert((CurContext->isDependentContext() || B.builtAll()) &&
6824 "omp for loop exprs were not built");
6825
6826 if (!CurContext->isDependentContext()) {
6827 // Finalize the clauses that need pre-built expressions for CodeGen.
6828 for (auto C : Clauses) {
6829 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6830 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6831 B.NumIterations, *this, CurScope,
6832 DSAStack))
6833 return StmtError();
6834 }
6835 }
6836
6837 getCurFunction()->setHasBranchProtectedScope();
6838 return OMPTeamsDistributeParallelForDirective::Create(
6839 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6840}
6841
Kelvin Libf594a52016-12-17 05:48:59 +00006842StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6843 Stmt *AStmt,
6844 SourceLocation StartLoc,
6845 SourceLocation EndLoc) {
6846 if (!AStmt)
6847 return StmtError();
6848
6849 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6850 // 1.2.2 OpenMP Language Terminology
6851 // Structured block - An executable statement with a single entry at the
6852 // top and a single exit at the bottom.
6853 // The point of exit cannot be a branch out of the structured block.
6854 // longjmp() and throw() must not violate the entry/exit criteria.
6855 CS->getCapturedDecl()->setNothrow();
6856
6857 getCurFunction()->setHasBranchProtectedScope();
6858
6859 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6860 AStmt);
6861}
6862
Kelvin Li83c451e2016-12-25 04:52:54 +00006863StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6864 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6865 SourceLocation EndLoc,
6866 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6867 if (!AStmt)
6868 return StmtError();
6869
6870 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6871 // 1.2.2 OpenMP Language Terminology
6872 // Structured block - An executable statement with a single entry at the
6873 // top and a single exit at the bottom.
6874 // The point of exit cannot be a branch out of the structured block.
6875 // longjmp() and throw() must not violate the entry/exit criteria.
6876 CS->getCapturedDecl()->setNothrow();
6877
6878 OMPLoopDirective::HelperExprs B;
6879 // In presence of clause 'collapse' with number of loops, it will
6880 // define the nested loops number.
6881 auto NestedLoopCount = CheckOpenMPLoop(
6882 OMPD_target_teams_distribute,
6883 getCollapseNumberExpr(Clauses),
6884 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6885 VarsWithImplicitDSA, B);
6886 if (NestedLoopCount == 0)
6887 return StmtError();
6888
6889 assert((CurContext->isDependentContext() || B.builtAll()) &&
6890 "omp target teams distribute loop exprs were not built");
6891
6892 getCurFunction()->setHasBranchProtectedScope();
6893 return OMPTargetTeamsDistributeDirective::Create(
6894 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6895}
6896
Kelvin Li80e8f562016-12-29 22:16:30 +00006897StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6898 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6899 SourceLocation EndLoc,
6900 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6901 if (!AStmt)
6902 return StmtError();
6903
6904 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6905 // 1.2.2 OpenMP Language Terminology
6906 // Structured block - An executable statement with a single entry at the
6907 // top and a single exit at the bottom.
6908 // The point of exit cannot be a branch out of the structured block.
6909 // longjmp() and throw() must not violate the entry/exit criteria.
6910 CS->getCapturedDecl()->setNothrow();
6911
6912 OMPLoopDirective::HelperExprs B;
6913 // In presence of clause 'collapse' with number of loops, it will
6914 // define the nested loops number.
6915 auto NestedLoopCount = CheckOpenMPLoop(
6916 OMPD_target_teams_distribute_parallel_for,
6917 getCollapseNumberExpr(Clauses),
6918 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6919 VarsWithImplicitDSA, B);
6920 if (NestedLoopCount == 0)
6921 return StmtError();
6922
6923 assert((CurContext->isDependentContext() || B.builtAll()) &&
6924 "omp target teams distribute parallel for loop exprs were not built");
6925
6926 if (!CurContext->isDependentContext()) {
6927 // Finalize the clauses that need pre-built expressions for CodeGen.
6928 for (auto C : Clauses) {
6929 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6930 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6931 B.NumIterations, *this, CurScope,
6932 DSAStack))
6933 return StmtError();
6934 }
6935 }
6936
6937 getCurFunction()->setHasBranchProtectedScope();
6938 return OMPTargetTeamsDistributeParallelForDirective::Create(
6939 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6940}
6941
Kelvin Li1851df52017-01-03 05:23:48 +00006942StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6943 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6944 SourceLocation EndLoc,
6945 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6946 if (!AStmt)
6947 return StmtError();
6948
6949 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6950 // 1.2.2 OpenMP Language Terminology
6951 // Structured block - An executable statement with a single entry at the
6952 // top and a single exit at the bottom.
6953 // The point of exit cannot be a branch out of the structured block.
6954 // longjmp() and throw() must not violate the entry/exit criteria.
6955 CS->getCapturedDecl()->setNothrow();
6956
6957 OMPLoopDirective::HelperExprs B;
6958 // In presence of clause 'collapse' with number of loops, it will
6959 // define the nested loops number.
6960 auto NestedLoopCount = CheckOpenMPLoop(
6961 OMPD_target_teams_distribute_parallel_for_simd,
6962 getCollapseNumberExpr(Clauses),
6963 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6964 VarsWithImplicitDSA, B);
6965 if (NestedLoopCount == 0)
6966 return StmtError();
6967
6968 assert((CurContext->isDependentContext() || B.builtAll()) &&
6969 "omp target teams distribute parallel for simd loop exprs were not "
6970 "built");
6971
6972 if (!CurContext->isDependentContext()) {
6973 // Finalize the clauses that need pre-built expressions for CodeGen.
6974 for (auto C : Clauses) {
6975 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6976 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6977 B.NumIterations, *this, CurScope,
6978 DSAStack))
6979 return StmtError();
6980 }
6981 }
6982
6983 getCurFunction()->setHasBranchProtectedScope();
6984 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6985 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6986}
6987
Kelvin Lida681182017-01-10 18:08:18 +00006988StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6989 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6990 SourceLocation EndLoc,
6991 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6992 if (!AStmt)
6993 return StmtError();
6994
6995 auto *CS = cast<CapturedStmt>(AStmt);
6996 // 1.2.2 OpenMP Language Terminology
6997 // Structured block - An executable statement with a single entry at the
6998 // top and a single exit at the bottom.
6999 // The point of exit cannot be a branch out of the structured block.
7000 // longjmp() and throw() must not violate the entry/exit criteria.
7001 CS->getCapturedDecl()->setNothrow();
7002
7003 OMPLoopDirective::HelperExprs B;
7004 // In presence of clause 'collapse' with number of loops, it will
7005 // define the nested loops number.
7006 auto NestedLoopCount = CheckOpenMPLoop(
7007 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7008 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7009 VarsWithImplicitDSA, B);
7010 if (NestedLoopCount == 0)
7011 return StmtError();
7012
7013 assert((CurContext->isDependentContext() || B.builtAll()) &&
7014 "omp target teams distribute simd loop exprs were not built");
7015
7016 getCurFunction()->setHasBranchProtectedScope();
7017 return OMPTargetTeamsDistributeSimdDirective::Create(
7018 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7019}
7020
Alexey Bataeved09d242014-05-28 05:53:51 +00007021OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007022 SourceLocation StartLoc,
7023 SourceLocation LParenLoc,
7024 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007025 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007026 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007027 case OMPC_final:
7028 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7029 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007030 case OMPC_num_threads:
7031 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7032 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007033 case OMPC_safelen:
7034 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7035 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007036 case OMPC_simdlen:
7037 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7038 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007039 case OMPC_collapse:
7040 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7041 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007042 case OMPC_ordered:
7043 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7044 break;
Michael Wonge710d542015-08-07 16:16:36 +00007045 case OMPC_device:
7046 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7047 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007048 case OMPC_num_teams:
7049 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7050 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007051 case OMPC_thread_limit:
7052 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7053 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007054 case OMPC_priority:
7055 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7056 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007057 case OMPC_grainsize:
7058 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7059 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007060 case OMPC_num_tasks:
7061 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7062 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007063 case OMPC_hint:
7064 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7065 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007066 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007067 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007068 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007069 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007070 case OMPC_private:
7071 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007072 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007073 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007074 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007075 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007076 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007077 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007078 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007079 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007080 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007081 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007082 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007083 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007084 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007085 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007086 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007087 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007088 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007089 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007090 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007091 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007092 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007093 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007094 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007095 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007096 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007097 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007098 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007099 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007100 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007101 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007102 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007103 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007104 llvm_unreachable("Clause is not allowed.");
7105 }
7106 return Res;
7107}
7108
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007109// An OpenMP directive such as 'target parallel' has two captured regions:
7110// for the 'target' and 'parallel' respectively. This function returns
7111// the region in which to capture expressions associated with a clause.
7112// A return value of OMPD_unknown signifies that the expression should not
7113// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007114static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7115 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7116 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007117 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7118
7119 switch (CKind) {
7120 case OMPC_if:
7121 switch (DKind) {
7122 case OMPD_target_parallel:
7123 // If this clause applies to the nested 'parallel' region, capture within
7124 // the 'target' region, otherwise do not capture.
7125 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7126 CaptureRegion = OMPD_target;
7127 break;
7128 case OMPD_cancel:
7129 case OMPD_parallel:
7130 case OMPD_parallel_sections:
7131 case OMPD_parallel_for:
7132 case OMPD_parallel_for_simd:
7133 case OMPD_target:
7134 case OMPD_target_simd:
7135 case OMPD_target_parallel_for:
7136 case OMPD_target_parallel_for_simd:
7137 case OMPD_target_teams:
7138 case OMPD_target_teams_distribute:
7139 case OMPD_target_teams_distribute_simd:
7140 case OMPD_target_teams_distribute_parallel_for:
7141 case OMPD_target_teams_distribute_parallel_for_simd:
7142 case OMPD_teams_distribute_parallel_for:
7143 case OMPD_teams_distribute_parallel_for_simd:
7144 case OMPD_distribute_parallel_for:
7145 case OMPD_distribute_parallel_for_simd:
7146 case OMPD_task:
7147 case OMPD_taskloop:
7148 case OMPD_taskloop_simd:
7149 case OMPD_target_data:
7150 case OMPD_target_enter_data:
7151 case OMPD_target_exit_data:
7152 case OMPD_target_update:
7153 // Do not capture if-clause expressions.
7154 break;
7155 case OMPD_threadprivate:
7156 case OMPD_taskyield:
7157 case OMPD_barrier:
7158 case OMPD_taskwait:
7159 case OMPD_cancellation_point:
7160 case OMPD_flush:
7161 case OMPD_declare_reduction:
7162 case OMPD_declare_simd:
7163 case OMPD_declare_target:
7164 case OMPD_end_declare_target:
7165 case OMPD_teams:
7166 case OMPD_simd:
7167 case OMPD_for:
7168 case OMPD_for_simd:
7169 case OMPD_sections:
7170 case OMPD_section:
7171 case OMPD_single:
7172 case OMPD_master:
7173 case OMPD_critical:
7174 case OMPD_taskgroup:
7175 case OMPD_distribute:
7176 case OMPD_ordered:
7177 case OMPD_atomic:
7178 case OMPD_distribute_simd:
7179 case OMPD_teams_distribute:
7180 case OMPD_teams_distribute_simd:
7181 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7182 case OMPD_unknown:
7183 llvm_unreachable("Unknown OpenMP directive");
7184 }
7185 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007186 case OMPC_num_threads:
7187 switch (DKind) {
7188 case OMPD_target_parallel:
7189 CaptureRegion = OMPD_target;
7190 break;
7191 case OMPD_cancel:
7192 case OMPD_parallel:
7193 case OMPD_parallel_sections:
7194 case OMPD_parallel_for:
7195 case OMPD_parallel_for_simd:
7196 case OMPD_target:
7197 case OMPD_target_simd:
7198 case OMPD_target_parallel_for:
7199 case OMPD_target_parallel_for_simd:
7200 case OMPD_target_teams:
7201 case OMPD_target_teams_distribute:
7202 case OMPD_target_teams_distribute_simd:
7203 case OMPD_target_teams_distribute_parallel_for:
7204 case OMPD_target_teams_distribute_parallel_for_simd:
7205 case OMPD_teams_distribute_parallel_for:
7206 case OMPD_teams_distribute_parallel_for_simd:
7207 case OMPD_distribute_parallel_for:
7208 case OMPD_distribute_parallel_for_simd:
7209 case OMPD_task:
7210 case OMPD_taskloop:
7211 case OMPD_taskloop_simd:
7212 case OMPD_target_data:
7213 case OMPD_target_enter_data:
7214 case OMPD_target_exit_data:
7215 case OMPD_target_update:
7216 // Do not capture num_threads-clause expressions.
7217 break;
7218 case OMPD_threadprivate:
7219 case OMPD_taskyield:
7220 case OMPD_barrier:
7221 case OMPD_taskwait:
7222 case OMPD_cancellation_point:
7223 case OMPD_flush:
7224 case OMPD_declare_reduction:
7225 case OMPD_declare_simd:
7226 case OMPD_declare_target:
7227 case OMPD_end_declare_target:
7228 case OMPD_teams:
7229 case OMPD_simd:
7230 case OMPD_for:
7231 case OMPD_for_simd:
7232 case OMPD_sections:
7233 case OMPD_section:
7234 case OMPD_single:
7235 case OMPD_master:
7236 case OMPD_critical:
7237 case OMPD_taskgroup:
7238 case OMPD_distribute:
7239 case OMPD_ordered:
7240 case OMPD_atomic:
7241 case OMPD_distribute_simd:
7242 case OMPD_teams_distribute:
7243 case OMPD_teams_distribute_simd:
7244 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7245 case OMPD_unknown:
7246 llvm_unreachable("Unknown OpenMP directive");
7247 }
7248 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007249 case OMPC_num_teams:
7250 switch (DKind) {
7251 case OMPD_target_teams:
7252 CaptureRegion = OMPD_target;
7253 break;
7254 case OMPD_cancel:
7255 case OMPD_parallel:
7256 case OMPD_parallel_sections:
7257 case OMPD_parallel_for:
7258 case OMPD_parallel_for_simd:
7259 case OMPD_target:
7260 case OMPD_target_simd:
7261 case OMPD_target_parallel:
7262 case OMPD_target_parallel_for:
7263 case OMPD_target_parallel_for_simd:
7264 case OMPD_target_teams_distribute:
7265 case OMPD_target_teams_distribute_simd:
7266 case OMPD_target_teams_distribute_parallel_for:
7267 case OMPD_target_teams_distribute_parallel_for_simd:
7268 case OMPD_teams_distribute_parallel_for:
7269 case OMPD_teams_distribute_parallel_for_simd:
7270 case OMPD_distribute_parallel_for:
7271 case OMPD_distribute_parallel_for_simd:
7272 case OMPD_task:
7273 case OMPD_taskloop:
7274 case OMPD_taskloop_simd:
7275 case OMPD_target_data:
7276 case OMPD_target_enter_data:
7277 case OMPD_target_exit_data:
7278 case OMPD_target_update:
7279 case OMPD_teams:
7280 case OMPD_teams_distribute:
7281 case OMPD_teams_distribute_simd:
7282 // Do not capture num_teams-clause expressions.
7283 break;
7284 case OMPD_threadprivate:
7285 case OMPD_taskyield:
7286 case OMPD_barrier:
7287 case OMPD_taskwait:
7288 case OMPD_cancellation_point:
7289 case OMPD_flush:
7290 case OMPD_declare_reduction:
7291 case OMPD_declare_simd:
7292 case OMPD_declare_target:
7293 case OMPD_end_declare_target:
7294 case OMPD_simd:
7295 case OMPD_for:
7296 case OMPD_for_simd:
7297 case OMPD_sections:
7298 case OMPD_section:
7299 case OMPD_single:
7300 case OMPD_master:
7301 case OMPD_critical:
7302 case OMPD_taskgroup:
7303 case OMPD_distribute:
7304 case OMPD_ordered:
7305 case OMPD_atomic:
7306 case OMPD_distribute_simd:
7307 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7308 case OMPD_unknown:
7309 llvm_unreachable("Unknown OpenMP directive");
7310 }
7311 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007312 case OMPC_thread_limit:
7313 switch (DKind) {
7314 case OMPD_target_teams:
7315 CaptureRegion = OMPD_target;
7316 break;
7317 case OMPD_cancel:
7318 case OMPD_parallel:
7319 case OMPD_parallel_sections:
7320 case OMPD_parallel_for:
7321 case OMPD_parallel_for_simd:
7322 case OMPD_target:
7323 case OMPD_target_simd:
7324 case OMPD_target_parallel:
7325 case OMPD_target_parallel_for:
7326 case OMPD_target_parallel_for_simd:
7327 case OMPD_target_teams_distribute:
7328 case OMPD_target_teams_distribute_simd:
7329 case OMPD_target_teams_distribute_parallel_for:
7330 case OMPD_target_teams_distribute_parallel_for_simd:
7331 case OMPD_teams_distribute_parallel_for:
7332 case OMPD_teams_distribute_parallel_for_simd:
7333 case OMPD_distribute_parallel_for:
7334 case OMPD_distribute_parallel_for_simd:
7335 case OMPD_task:
7336 case OMPD_taskloop:
7337 case OMPD_taskloop_simd:
7338 case OMPD_target_data:
7339 case OMPD_target_enter_data:
7340 case OMPD_target_exit_data:
7341 case OMPD_target_update:
7342 case OMPD_teams:
7343 case OMPD_teams_distribute:
7344 case OMPD_teams_distribute_simd:
7345 // Do not capture thread_limit-clause expressions.
7346 break;
7347 case OMPD_threadprivate:
7348 case OMPD_taskyield:
7349 case OMPD_barrier:
7350 case OMPD_taskwait:
7351 case OMPD_cancellation_point:
7352 case OMPD_flush:
7353 case OMPD_declare_reduction:
7354 case OMPD_declare_simd:
7355 case OMPD_declare_target:
7356 case OMPD_end_declare_target:
7357 case OMPD_simd:
7358 case OMPD_for:
7359 case OMPD_for_simd:
7360 case OMPD_sections:
7361 case OMPD_section:
7362 case OMPD_single:
7363 case OMPD_master:
7364 case OMPD_critical:
7365 case OMPD_taskgroup:
7366 case OMPD_distribute:
7367 case OMPD_ordered:
7368 case OMPD_atomic:
7369 case OMPD_distribute_simd:
7370 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7371 case OMPD_unknown:
7372 llvm_unreachable("Unknown OpenMP directive");
7373 }
7374 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007375 case OMPC_schedule:
7376 case OMPC_dist_schedule:
7377 case OMPC_firstprivate:
7378 case OMPC_lastprivate:
7379 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007380 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007381 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007382 case OMPC_linear:
7383 case OMPC_default:
7384 case OMPC_proc_bind:
7385 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007386 case OMPC_safelen:
7387 case OMPC_simdlen:
7388 case OMPC_collapse:
7389 case OMPC_private:
7390 case OMPC_shared:
7391 case OMPC_aligned:
7392 case OMPC_copyin:
7393 case OMPC_copyprivate:
7394 case OMPC_ordered:
7395 case OMPC_nowait:
7396 case OMPC_untied:
7397 case OMPC_mergeable:
7398 case OMPC_threadprivate:
7399 case OMPC_flush:
7400 case OMPC_read:
7401 case OMPC_write:
7402 case OMPC_update:
7403 case OMPC_capture:
7404 case OMPC_seq_cst:
7405 case OMPC_depend:
7406 case OMPC_device:
7407 case OMPC_threads:
7408 case OMPC_simd:
7409 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007410 case OMPC_priority:
7411 case OMPC_grainsize:
7412 case OMPC_nogroup:
7413 case OMPC_num_tasks:
7414 case OMPC_hint:
7415 case OMPC_defaultmap:
7416 case OMPC_unknown:
7417 case OMPC_uniform:
7418 case OMPC_to:
7419 case OMPC_from:
7420 case OMPC_use_device_ptr:
7421 case OMPC_is_device_ptr:
7422 llvm_unreachable("Unexpected OpenMP clause.");
7423 }
7424 return CaptureRegion;
7425}
7426
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007427OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7428 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007429 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007430 SourceLocation NameModifierLoc,
7431 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007432 SourceLocation EndLoc) {
7433 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007434 Stmt *HelperValStmt = nullptr;
7435 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007436 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7437 !Condition->isInstantiationDependent() &&
7438 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007439 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007440 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007441 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007442
Richard Smith03a4aa32016-06-23 19:02:52 +00007443 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007444
7445 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7446 CaptureRegion =
7447 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7448 if (CaptureRegion != OMPD_unknown) {
7449 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7450 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7451 HelperValStmt = buildPreInits(Context, Captures);
7452 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007453 }
7454
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007455 return new (Context)
7456 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7457 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007458}
7459
Alexey Bataev3778b602014-07-17 07:32:53 +00007460OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7461 SourceLocation StartLoc,
7462 SourceLocation LParenLoc,
7463 SourceLocation EndLoc) {
7464 Expr *ValExpr = Condition;
7465 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7466 !Condition->isInstantiationDependent() &&
7467 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007468 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007469 if (Val.isInvalid())
7470 return nullptr;
7471
Richard Smith03a4aa32016-06-23 19:02:52 +00007472 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007473 }
7474
7475 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7476}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007477ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7478 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007479 if (!Op)
7480 return ExprError();
7481
7482 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7483 public:
7484 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007485 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007486 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7487 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007488 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7489 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007490 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7491 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007492 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7493 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007494 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7495 QualType T,
7496 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007497 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7498 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007499 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7500 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007501 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007502 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007503 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007504 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7505 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007506 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7507 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007508 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7509 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007510 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007511 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007512 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007513 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7514 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007515 llvm_unreachable("conversion functions are permitted");
7516 }
7517 } ConvertDiagnoser;
7518 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7519}
7520
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007521static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007522 OpenMPClauseKind CKind,
7523 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007524 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7525 !ValExpr->isInstantiationDependent()) {
7526 SourceLocation Loc = ValExpr->getExprLoc();
7527 ExprResult Value =
7528 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7529 if (Value.isInvalid())
7530 return false;
7531
7532 ValExpr = Value.get();
7533 // The expression must evaluate to a non-negative integer value.
7534 llvm::APSInt Result;
7535 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007536 Result.isSigned() &&
7537 !((!StrictlyPositive && Result.isNonNegative()) ||
7538 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007539 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007540 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7541 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007542 return false;
7543 }
7544 }
7545 return true;
7546}
7547
Alexey Bataev568a8332014-03-06 06:15:19 +00007548OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7549 SourceLocation StartLoc,
7550 SourceLocation LParenLoc,
7551 SourceLocation EndLoc) {
7552 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007553 Stmt *HelperValStmt = nullptr;
7554 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007555
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007556 // OpenMP [2.5, Restrictions]
7557 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007558 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7559 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007560 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007561
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007562 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7563 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7564 if (CaptureRegion != OMPD_unknown) {
7565 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7566 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7567 HelperValStmt = buildPreInits(Context, Captures);
7568 }
7569
7570 return new (Context) OMPNumThreadsClause(
7571 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007572}
7573
Alexey Bataev62c87d22014-03-21 04:51:18 +00007574ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007575 OpenMPClauseKind CKind,
7576 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007577 if (!E)
7578 return ExprError();
7579 if (E->isValueDependent() || E->isTypeDependent() ||
7580 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007581 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007582 llvm::APSInt Result;
7583 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7584 if (ICE.isInvalid())
7585 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007586 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7587 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007588 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007589 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7590 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007591 return ExprError();
7592 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007593 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7594 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7595 << E->getSourceRange();
7596 return ExprError();
7597 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007598 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7599 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007600 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007601 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007602 return ICE;
7603}
7604
7605OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7606 SourceLocation LParenLoc,
7607 SourceLocation EndLoc) {
7608 // OpenMP [2.8.1, simd construct, Description]
7609 // The parameter of the safelen clause must be a constant
7610 // positive integer expression.
7611 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7612 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007613 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007614 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007615 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007616}
7617
Alexey Bataev66b15b52015-08-21 11:14:16 +00007618OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7619 SourceLocation LParenLoc,
7620 SourceLocation EndLoc) {
7621 // OpenMP [2.8.1, simd construct, Description]
7622 // The parameter of the simdlen clause must be a constant
7623 // positive integer expression.
7624 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7625 if (Simdlen.isInvalid())
7626 return nullptr;
7627 return new (Context)
7628 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7629}
7630
Alexander Musman64d33f12014-06-04 07:53:32 +00007631OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7632 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007633 SourceLocation LParenLoc,
7634 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007635 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007636 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007637 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007638 // The parameter of the collapse clause must be a constant
7639 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007640 ExprResult NumForLoopsResult =
7641 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7642 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007643 return nullptr;
7644 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007645 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007646}
7647
Alexey Bataev10e775f2015-07-30 11:36:16 +00007648OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7649 SourceLocation EndLoc,
7650 SourceLocation LParenLoc,
7651 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007652 // OpenMP [2.7.1, loop construct, Description]
7653 // OpenMP [2.8.1, simd construct, Description]
7654 // OpenMP [2.9.6, distribute construct, Description]
7655 // The parameter of the ordered clause must be a constant
7656 // positive integer expression if any.
7657 if (NumForLoops && LParenLoc.isValid()) {
7658 ExprResult NumForLoopsResult =
7659 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7660 if (NumForLoopsResult.isInvalid())
7661 return nullptr;
7662 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007663 } else
7664 NumForLoops = nullptr;
7665 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007666 return new (Context)
7667 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7668}
7669
Alexey Bataeved09d242014-05-28 05:53:51 +00007670OMPClause *Sema::ActOnOpenMPSimpleClause(
7671 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7672 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007673 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007674 switch (Kind) {
7675 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007676 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007677 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7678 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007679 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007680 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007681 Res = ActOnOpenMPProcBindClause(
7682 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7683 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007684 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007685 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007686 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007687 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007688 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007689 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007690 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007691 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007692 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007693 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007694 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007695 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007696 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007697 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007698 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007699 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007700 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007701 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007702 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007703 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007704 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007705 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007706 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007707 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007708 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007709 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007710 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007711 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007712 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007713 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007714 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007715 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007716 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007717 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007718 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007719 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007720 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007721 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007722 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007723 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007724 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007725 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007726 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007727 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007728 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007729 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007730 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007731 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007732 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007733 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007734 llvm_unreachable("Clause is not allowed.");
7735 }
7736 return Res;
7737}
7738
Alexey Bataev6402bca2015-12-28 07:25:51 +00007739static std::string
7740getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7741 ArrayRef<unsigned> Exclude = llvm::None) {
7742 std::string Values;
7743 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7744 unsigned Skipped = Exclude.size();
7745 auto S = Exclude.begin(), E = Exclude.end();
7746 for (unsigned i = First; i < Last; ++i) {
7747 if (std::find(S, E, i) != E) {
7748 --Skipped;
7749 continue;
7750 }
7751 Values += "'";
7752 Values += getOpenMPSimpleClauseTypeName(K, i);
7753 Values += "'";
7754 if (i == Bound - Skipped)
7755 Values += " or ";
7756 else if (i != Bound + 1 - Skipped)
7757 Values += ", ";
7758 }
7759 return Values;
7760}
7761
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007762OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7763 SourceLocation KindKwLoc,
7764 SourceLocation StartLoc,
7765 SourceLocation LParenLoc,
7766 SourceLocation EndLoc) {
7767 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007768 static_assert(OMPC_DEFAULT_unknown > 0,
7769 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007770 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007771 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7772 /*Last=*/OMPC_DEFAULT_unknown)
7773 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007774 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007775 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007776 switch (Kind) {
7777 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007778 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007779 break;
7780 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007781 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007782 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007783 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007784 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007785 break;
7786 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007787 return new (Context)
7788 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007789}
7790
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007791OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7792 SourceLocation KindKwLoc,
7793 SourceLocation StartLoc,
7794 SourceLocation LParenLoc,
7795 SourceLocation EndLoc) {
7796 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007797 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007798 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7799 /*Last=*/OMPC_PROC_BIND_unknown)
7800 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007801 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007802 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007803 return new (Context)
7804 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007805}
7806
Alexey Bataev56dafe82014-06-20 07:16:17 +00007807OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007808 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007809 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007810 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007811 SourceLocation EndLoc) {
7812 OMPClause *Res = nullptr;
7813 switch (Kind) {
7814 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007815 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7816 assert(Argument.size() == NumberOfElements &&
7817 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007818 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007819 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7820 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7821 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7822 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7823 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007824 break;
7825 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007826 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7827 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7828 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7829 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007830 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007831 case OMPC_dist_schedule:
7832 Res = ActOnOpenMPDistScheduleClause(
7833 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7834 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7835 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007836 case OMPC_defaultmap:
7837 enum { Modifier, DefaultmapKind };
7838 Res = ActOnOpenMPDefaultmapClause(
7839 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7840 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007841 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7842 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007843 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007844 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007845 case OMPC_num_threads:
7846 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007847 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007848 case OMPC_collapse:
7849 case OMPC_default:
7850 case OMPC_proc_bind:
7851 case OMPC_private:
7852 case OMPC_firstprivate:
7853 case OMPC_lastprivate:
7854 case OMPC_shared:
7855 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007856 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007857 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007858 case OMPC_linear:
7859 case OMPC_aligned:
7860 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007861 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007862 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007863 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007864 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007865 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007866 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007867 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007868 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007869 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007870 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007871 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007872 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007873 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007874 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007875 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007876 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007877 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007878 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007879 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007880 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007881 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007882 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007883 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007884 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007885 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007886 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007887 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007888 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007889 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007890 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007891 llvm_unreachable("Clause is not allowed.");
7892 }
7893 return Res;
7894}
7895
Alexey Bataev6402bca2015-12-28 07:25:51 +00007896static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7897 OpenMPScheduleClauseModifier M2,
7898 SourceLocation M1Loc, SourceLocation M2Loc) {
7899 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7900 SmallVector<unsigned, 2> Excluded;
7901 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7902 Excluded.push_back(M2);
7903 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7904 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7905 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7906 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7907 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7908 << getListOfPossibleValues(OMPC_schedule,
7909 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7910 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7911 Excluded)
7912 << getOpenMPClauseName(OMPC_schedule);
7913 return true;
7914 }
7915 return false;
7916}
7917
Alexey Bataev56dafe82014-06-20 07:16:17 +00007918OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007919 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007920 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007921 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7922 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7923 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7924 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7925 return nullptr;
7926 // OpenMP, 2.7.1, Loop Construct, Restrictions
7927 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7928 // but not both.
7929 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7930 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7931 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7932 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7933 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7934 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7935 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7936 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7937 return nullptr;
7938 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007939 if (Kind == OMPC_SCHEDULE_unknown) {
7940 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007941 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7942 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7943 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7944 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7945 Exclude);
7946 } else {
7947 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7948 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007949 }
7950 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7951 << Values << getOpenMPClauseName(OMPC_schedule);
7952 return nullptr;
7953 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007954 // OpenMP, 2.7.1, Loop Construct, Restrictions
7955 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7956 // schedule(guided).
7957 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7958 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7959 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7960 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7961 diag::err_omp_schedule_nonmonotonic_static);
7962 return nullptr;
7963 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007964 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007965 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007966 if (ChunkSize) {
7967 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7968 !ChunkSize->isInstantiationDependent() &&
7969 !ChunkSize->containsUnexpandedParameterPack()) {
7970 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7971 ExprResult Val =
7972 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7973 if (Val.isInvalid())
7974 return nullptr;
7975
7976 ValExpr = Val.get();
7977
7978 // OpenMP [2.7.1, Restrictions]
7979 // chunk_size must be a loop invariant integer expression with a positive
7980 // value.
7981 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007982 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7983 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7984 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007985 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007986 return nullptr;
7987 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007988 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7989 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007990 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7991 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7992 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007993 }
7994 }
7995 }
7996
Alexey Bataev6402bca2015-12-28 07:25:51 +00007997 return new (Context)
7998 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007999 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008000}
8001
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008002OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8003 SourceLocation StartLoc,
8004 SourceLocation EndLoc) {
8005 OMPClause *Res = nullptr;
8006 switch (Kind) {
8007 case OMPC_ordered:
8008 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8009 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008010 case OMPC_nowait:
8011 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8012 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008013 case OMPC_untied:
8014 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8015 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008016 case OMPC_mergeable:
8017 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8018 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008019 case OMPC_read:
8020 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8021 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008022 case OMPC_write:
8023 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8024 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008025 case OMPC_update:
8026 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8027 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008028 case OMPC_capture:
8029 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8030 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008031 case OMPC_seq_cst:
8032 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8033 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008034 case OMPC_threads:
8035 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8036 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008037 case OMPC_simd:
8038 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8039 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008040 case OMPC_nogroup:
8041 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8042 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008043 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008044 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008045 case OMPC_num_threads:
8046 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008047 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008048 case OMPC_collapse:
8049 case OMPC_schedule:
8050 case OMPC_private:
8051 case OMPC_firstprivate:
8052 case OMPC_lastprivate:
8053 case OMPC_shared:
8054 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008055 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008056 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008057 case OMPC_linear:
8058 case OMPC_aligned:
8059 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008060 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008061 case OMPC_default:
8062 case OMPC_proc_bind:
8063 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008064 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008065 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008066 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008067 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008068 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008069 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008070 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008071 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008072 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008073 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008074 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008075 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008076 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008077 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008078 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008079 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008080 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008081 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008082 llvm_unreachable("Clause is not allowed.");
8083 }
8084 return Res;
8085}
8086
Alexey Bataev236070f2014-06-20 11:19:47 +00008087OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8088 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008089 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008090 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8091}
8092
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008093OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8094 SourceLocation EndLoc) {
8095 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8096}
8097
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008098OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8099 SourceLocation EndLoc) {
8100 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8101}
8102
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008103OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8104 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008105 return new (Context) OMPReadClause(StartLoc, EndLoc);
8106}
8107
Alexey Bataevdea47612014-07-23 07:46:59 +00008108OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8109 SourceLocation EndLoc) {
8110 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8111}
8112
Alexey Bataev67a4f222014-07-23 10:25:33 +00008113OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8114 SourceLocation EndLoc) {
8115 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8116}
8117
Alexey Bataev459dec02014-07-24 06:46:57 +00008118OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8119 SourceLocation EndLoc) {
8120 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8121}
8122
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008123OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8124 SourceLocation EndLoc) {
8125 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8126}
8127
Alexey Bataev346265e2015-09-25 10:37:12 +00008128OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8129 SourceLocation EndLoc) {
8130 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8131}
8132
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008133OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8134 SourceLocation EndLoc) {
8135 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8136}
8137
Alexey Bataevb825de12015-12-07 10:51:44 +00008138OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8139 SourceLocation EndLoc) {
8140 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8141}
8142
Alexey Bataevc5e02582014-06-16 07:08:35 +00008143OMPClause *Sema::ActOnOpenMPVarListClause(
8144 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8145 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8146 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008147 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008148 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8149 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8150 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008151 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008152 switch (Kind) {
8153 case OMPC_private:
8154 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8155 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008156 case OMPC_firstprivate:
8157 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8158 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008159 case OMPC_lastprivate:
8160 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8161 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008162 case OMPC_shared:
8163 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8164 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008165 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008166 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8167 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008168 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008169 case OMPC_task_reduction:
8170 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8171 EndLoc, ReductionIdScopeSpec,
8172 ReductionId);
8173 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008174 case OMPC_in_reduction:
8175 Res =
8176 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8177 EndLoc, ReductionIdScopeSpec, ReductionId);
8178 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008179 case OMPC_linear:
8180 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008181 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008182 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008183 case OMPC_aligned:
8184 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8185 ColonLoc, EndLoc);
8186 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008187 case OMPC_copyin:
8188 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8189 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008190 case OMPC_copyprivate:
8191 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8192 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008193 case OMPC_flush:
8194 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8195 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008196 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008197 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008198 StartLoc, LParenLoc, EndLoc);
8199 break;
8200 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008201 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8202 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8203 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008204 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008205 case OMPC_to:
8206 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8207 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008208 case OMPC_from:
8209 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8210 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008211 case OMPC_use_device_ptr:
8212 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8213 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008214 case OMPC_is_device_ptr:
8215 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8216 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008217 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008218 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008219 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008220 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008221 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008222 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008223 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008224 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008225 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008226 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008227 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008228 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008229 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008230 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008231 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008232 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008233 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008234 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008235 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008236 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008237 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008238 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008239 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008240 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008241 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008242 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008243 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008244 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008245 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008246 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008247 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008248 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008249 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008250 llvm_unreachable("Clause is not allowed.");
8251 }
8252 return Res;
8253}
8254
Alexey Bataev90c228f2016-02-08 09:29:13 +00008255ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008256 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008257 ExprResult Res = BuildDeclRefExpr(
8258 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8259 if (!Res.isUsable())
8260 return ExprError();
8261 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8262 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8263 if (!Res.isUsable())
8264 return ExprError();
8265 }
8266 if (VK != VK_LValue && Res.get()->isGLValue()) {
8267 Res = DefaultLvalueConversion(Res.get());
8268 if (!Res.isUsable())
8269 return ExprError();
8270 }
8271 return Res;
8272}
8273
Alexey Bataev60da77e2016-02-29 05:54:20 +00008274static std::pair<ValueDecl *, bool>
8275getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8276 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008277 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8278 RefExpr->containsUnexpandedParameterPack())
8279 return std::make_pair(nullptr, true);
8280
Alexey Bataevd985eda2016-02-10 11:29:16 +00008281 // OpenMP [3.1, C/C++]
8282 // A list item is a variable name.
8283 // OpenMP [2.9.3.3, Restrictions, p.1]
8284 // A variable that is part of another variable (as an array or
8285 // structure element) cannot appear in a private clause.
8286 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008287 enum {
8288 NoArrayExpr = -1,
8289 ArraySubscript = 0,
8290 OMPArraySection = 1
8291 } IsArrayExpr = NoArrayExpr;
8292 if (AllowArraySection) {
8293 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8294 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8295 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8296 Base = TempASE->getBase()->IgnoreParenImpCasts();
8297 RefExpr = Base;
8298 IsArrayExpr = ArraySubscript;
8299 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8300 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8301 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8302 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8303 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8304 Base = TempASE->getBase()->IgnoreParenImpCasts();
8305 RefExpr = Base;
8306 IsArrayExpr = OMPArraySection;
8307 }
8308 }
8309 ELoc = RefExpr->getExprLoc();
8310 ERange = RefExpr->getSourceRange();
8311 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008312 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8313 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8314 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8315 (S.getCurrentThisType().isNull() || !ME ||
8316 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8317 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008318 if (IsArrayExpr != NoArrayExpr)
8319 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8320 << ERange;
8321 else {
8322 S.Diag(ELoc,
8323 AllowArraySection
8324 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8325 : diag::err_omp_expected_var_name_member_expr)
8326 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8327 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008328 return std::make_pair(nullptr, false);
8329 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008330 return std::make_pair(
8331 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008332}
8333
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008334OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8335 SourceLocation StartLoc,
8336 SourceLocation LParenLoc,
8337 SourceLocation EndLoc) {
8338 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008339 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008340 for (auto &RefExpr : VarList) {
8341 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008342 SourceLocation ELoc;
8343 SourceRange ERange;
8344 Expr *SimpleRefExpr = RefExpr;
8345 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008346 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008347 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008348 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008349 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008350 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008351 ValueDecl *D = Res.first;
8352 if (!D)
8353 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008354
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008355 QualType Type = D->getType();
8356 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008357
8358 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8359 // A variable that appears in a private clause must not have an incomplete
8360 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008361 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008362 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008363 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008364
Alexey Bataev758e55e2013-09-06 18:03:48 +00008365 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8366 // in a Construct]
8367 // Variables with the predetermined data-sharing attributes may not be
8368 // listed in data-sharing attributes clauses, except for the cases
8369 // listed below. For these exceptions only, listing a predetermined
8370 // variable in a data-sharing attribute clause is allowed and overrides
8371 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008372 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008373 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008374 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8375 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008376 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008377 continue;
8378 }
8379
Kelvin Libf594a52016-12-17 05:48:59 +00008380 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008381 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008382 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008383 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008384 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8385 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008386 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008387 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008388 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008389 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008390 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008391 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008392 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008393 continue;
8394 }
8395
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008396 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8397 // A list item cannot appear in both a map clause and a data-sharing
8398 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008399 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008400 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008401 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008402 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008403 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008404 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008405 CurrDir == OMPD_target_parallel_for_simd ||
8406 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008407 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008408 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008409 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008410 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8411 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8412 ConflictKind = WhereFoundClauseKind;
8413 return true;
8414 })) {
8415 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008416 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008417 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008418 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008419 ReportOriginalDSA(*this, DSAStack, D, DVar);
8420 continue;
8421 }
8422 }
8423
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008424 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8425 // A variable of class type (or array thereof) that appears in a private
8426 // clause requires an accessible, unambiguous default constructor for the
8427 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008428 // Generate helper private variable and initialize it with the default
8429 // value. The address of the original variable is replaced by the address of
8430 // the new private variable in CodeGen. This new variable is not added to
8431 // IdResolver, so the code in the OpenMP region uses original variable for
8432 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008433 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008434 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8435 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008436 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008437 if (VDPrivate->isInvalidDecl())
8438 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008439 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008440 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008441
Alexey Bataev90c228f2016-02-08 09:29:13 +00008442 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008443 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008444 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008445 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008446 Vars.push_back((VD || CurContext->isDependentContext())
8447 ? RefExpr->IgnoreParens()
8448 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008449 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008450 }
8451
Alexey Bataeved09d242014-05-28 05:53:51 +00008452 if (Vars.empty())
8453 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008454
Alexey Bataev03b340a2014-10-21 03:16:40 +00008455 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8456 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008457}
8458
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008459namespace {
8460class DiagsUninitializedSeveretyRAII {
8461private:
8462 DiagnosticsEngine &Diags;
8463 SourceLocation SavedLoc;
8464 bool IsIgnored;
8465
8466public:
8467 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8468 bool IsIgnored)
8469 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8470 if (!IsIgnored) {
8471 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8472 /*Map*/ diag::Severity::Ignored, Loc);
8473 }
8474 }
8475 ~DiagsUninitializedSeveretyRAII() {
8476 if (!IsIgnored)
8477 Diags.popMappings(SavedLoc);
8478 }
8479};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008480}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008481
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008482OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8483 SourceLocation StartLoc,
8484 SourceLocation LParenLoc,
8485 SourceLocation EndLoc) {
8486 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008487 SmallVector<Expr *, 8> PrivateCopies;
8488 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008489 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008490 bool IsImplicitClause =
8491 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8492 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8493
Alexey Bataeved09d242014-05-28 05:53:51 +00008494 for (auto &RefExpr : VarList) {
8495 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008496 SourceLocation ELoc;
8497 SourceRange ERange;
8498 Expr *SimpleRefExpr = RefExpr;
8499 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008500 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008501 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008502 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008503 PrivateCopies.push_back(nullptr);
8504 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008505 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008506 ValueDecl *D = Res.first;
8507 if (!D)
8508 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008509
Alexey Bataev60da77e2016-02-29 05:54:20 +00008510 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008511 QualType Type = D->getType();
8512 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008513
8514 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8515 // A variable that appears in a private clause must not have an incomplete
8516 // type or a reference type.
8517 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008518 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008519 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008520 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008521
8522 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8523 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008524 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008525 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008526 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008527
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008528 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008529 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008530 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008531 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008532 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008533 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008534 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008535 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8536 // A list item that specifies a given variable may not appear in more
8537 // than one clause on the same directive, except that a variable may be
8538 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008539 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8540 // A list item may appear in a firstprivate or lastprivate clause but not
8541 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008542 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008543 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8544 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008545 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008546 << getOpenMPClauseName(DVar.CKind)
8547 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008548 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008549 continue;
8550 }
8551
8552 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8553 // in a Construct]
8554 // Variables with the predetermined data-sharing attributes may not be
8555 // listed in data-sharing attributes clauses, except for the cases
8556 // listed below. For these exceptions only, listing a predetermined
8557 // variable in a data-sharing attribute clause is allowed and overrides
8558 // the variable's predetermined data-sharing attributes.
8559 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8560 // in a Construct, C/C++, p.2]
8561 // Variables with const-qualified type having no mutable member may be
8562 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008563 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008564 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8565 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008566 << getOpenMPClauseName(DVar.CKind)
8567 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008568 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008569 continue;
8570 }
8571
8572 // OpenMP [2.9.3.4, Restrictions, p.2]
8573 // A list item that is private within a parallel region must not appear
8574 // in a firstprivate clause on a worksharing construct if any of the
8575 // worksharing regions arising from the worksharing construct ever bind
8576 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008577 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8578 // A list item that is private within a teams region must not appear in a
8579 // firstprivate clause on a distribute construct if any of the distribute
8580 // regions arising from the distribute construct ever bind to any of the
8581 // teams regions arising from the teams construct.
8582 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8583 // A list item that appears in a reduction clause of a teams construct
8584 // must not appear in a firstprivate clause on a distribute construct if
8585 // any of the distribute regions arising from the distribute construct
8586 // ever bind to any of the teams regions arising from the teams construct.
8587 if ((isOpenMPWorksharingDirective(CurrDir) ||
8588 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008589 !isOpenMPParallelDirective(CurrDir) &&
8590 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008591 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008592 if (DVar.CKind != OMPC_shared &&
8593 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008594 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008595 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008596 Diag(ELoc, diag::err_omp_required_access)
8597 << getOpenMPClauseName(OMPC_firstprivate)
8598 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008599 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008600 continue;
8601 }
8602 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008603 // OpenMP [2.9.3.4, Restrictions, p.3]
8604 // A list item that appears in a reduction clause of a parallel construct
8605 // must not appear in a firstprivate clause on a worksharing or task
8606 // construct if any of the worksharing or task regions arising from the
8607 // worksharing or task construct ever bind to any of the parallel regions
8608 // arising from the parallel construct.
8609 // OpenMP [2.9.3.4, Restrictions, p.4]
8610 // A list item that appears in a reduction clause in worksharing
8611 // construct must not appear in a firstprivate clause in a task construct
8612 // encountered during execution of any of the worksharing regions arising
8613 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008614 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008615 DVar = DSAStack->hasInnermostDSA(
8616 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8617 [](OpenMPDirectiveKind K) -> bool {
8618 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008619 isOpenMPWorksharingDirective(K) ||
8620 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008621 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008622 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008623 if (DVar.CKind == OMPC_reduction &&
8624 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008625 isOpenMPWorksharingDirective(DVar.DKind) ||
8626 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008627 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8628 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008629 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008630 continue;
8631 }
8632 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008633
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008634 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8635 // A list item cannot appear in both a map clause and a data-sharing
8636 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008637 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008638 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008639 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008640 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008641 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008642 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008643 CurrDir == OMPD_target_parallel_for_simd ||
8644 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008645 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008646 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008647 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008648 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8649 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8650 ConflictKind = WhereFoundClauseKind;
8651 return true;
8652 })) {
8653 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008654 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008655 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008656 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8657 ReportOriginalDSA(*this, DSAStack, D, DVar);
8658 continue;
8659 }
8660 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008661 }
8662
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008663 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008664 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008665 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008666 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8667 << getOpenMPClauseName(OMPC_firstprivate) << Type
8668 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8669 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008670 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008671 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008672 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008673 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008674 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008675 continue;
8676 }
8677
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008678 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008679 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8680 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008681 // Generate helper private variable and initialize it with the value of the
8682 // original variable. The address of the original variable is replaced by
8683 // the address of the new private variable in the CodeGen. This new variable
8684 // is not added to IdResolver, so the code in the OpenMP region uses
8685 // original variable for proper diagnostics and variable capturing.
8686 Expr *VDInitRefExpr = nullptr;
8687 // For arrays generate initializer for single element and replace it by the
8688 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008689 if (Type->isArrayType()) {
8690 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008691 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008692 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008693 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008694 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008695 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008696 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008697 InitializedEntity Entity =
8698 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008699 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8700
8701 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8702 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8703 if (Result.isInvalid())
8704 VDPrivate->setInvalidDecl();
8705 else
8706 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008707 // Remove temp variable declaration.
8708 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008709 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008710 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8711 ".firstprivate.temp");
8712 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8713 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008714 AddInitializerToDecl(VDPrivate,
8715 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008716 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008717 }
8718 if (VDPrivate->isInvalidDecl()) {
8719 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008720 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008721 diag::note_omp_task_predetermined_firstprivate_here);
8722 }
8723 continue;
8724 }
8725 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008726 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008727 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8728 RefExpr->getExprLoc());
8729 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008730 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008731 if (TopDVar.CKind == OMPC_lastprivate)
8732 Ref = TopDVar.PrivateCopy;
8733 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008734 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008735 if (!IsOpenMPCapturedDecl(D))
8736 ExprCaptures.push_back(Ref->getDecl());
8737 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008738 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008739 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008740 Vars.push_back((VD || CurContext->isDependentContext())
8741 ? RefExpr->IgnoreParens()
8742 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008743 PrivateCopies.push_back(VDPrivateRefExpr);
8744 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008745 }
8746
Alexey Bataeved09d242014-05-28 05:53:51 +00008747 if (Vars.empty())
8748 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008749
8750 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008751 Vars, PrivateCopies, Inits,
8752 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008753}
8754
Alexander Musman1bb328c2014-06-04 13:06:39 +00008755OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8756 SourceLocation StartLoc,
8757 SourceLocation LParenLoc,
8758 SourceLocation EndLoc) {
8759 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008760 SmallVector<Expr *, 8> SrcExprs;
8761 SmallVector<Expr *, 8> DstExprs;
8762 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008763 SmallVector<Decl *, 4> ExprCaptures;
8764 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008765 for (auto &RefExpr : VarList) {
8766 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008767 SourceLocation ELoc;
8768 SourceRange ERange;
8769 Expr *SimpleRefExpr = RefExpr;
8770 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008771 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008772 // It will be analyzed later.
8773 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008774 SrcExprs.push_back(nullptr);
8775 DstExprs.push_back(nullptr);
8776 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008777 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008778 ValueDecl *D = Res.first;
8779 if (!D)
8780 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008781
Alexey Bataev74caaf22016-02-20 04:09:36 +00008782 QualType Type = D->getType();
8783 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008784
8785 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8786 // A variable that appears in a lastprivate clause must not have an
8787 // incomplete type or a reference type.
8788 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008789 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008790 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008791 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008792
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008793 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008794 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8795 // in a Construct]
8796 // Variables with the predetermined data-sharing attributes may not be
8797 // listed in data-sharing attributes clauses, except for the cases
8798 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008799 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8800 // A list item may appear in a firstprivate or lastprivate clause but not
8801 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008802 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008803 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008804 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00008805 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8806 Diag(ELoc, diag::err_omp_wrong_dsa)
8807 << getOpenMPClauseName(DVar.CKind)
8808 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008809 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008810 continue;
8811 }
8812
Alexey Bataevf29276e2014-06-18 04:14:57 +00008813 // OpenMP [2.14.3.5, Restrictions, p.2]
8814 // A list item that is private within a parallel region, or that appears in
8815 // the reduction clause of a parallel construct, must not appear in a
8816 // lastprivate clause on a worksharing construct if any of the corresponding
8817 // worksharing regions ever binds to any of the corresponding parallel
8818 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008819 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008820 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008821 !isOpenMPParallelDirective(CurrDir) &&
8822 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008823 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008824 if (DVar.CKind != OMPC_shared) {
8825 Diag(ELoc, diag::err_omp_required_access)
8826 << getOpenMPClauseName(OMPC_lastprivate)
8827 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008828 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008829 continue;
8830 }
8831 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008832
Alexander Musman1bb328c2014-06-04 13:06:39 +00008833 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008834 // A variable of class type (or array thereof) that appears in a
8835 // lastprivate clause requires an accessible, unambiguous default
8836 // constructor for the class type, unless the list item is also specified
8837 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008838 // A variable of class type (or array thereof) that appears in a
8839 // lastprivate clause requires an accessible, unambiguous copy assignment
8840 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008841 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008842 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008843 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008844 D->hasAttrs() ? &D->getAttrs() : nullptr);
8845 auto *PseudoSrcExpr =
8846 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008847 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008848 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008849 D->hasAttrs() ? &D->getAttrs() : nullptr);
8850 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008851 // For arrays generate assignment operation for single element and replace
8852 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008853 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008854 PseudoDstExpr, PseudoSrcExpr);
8855 if (AssignmentOp.isInvalid())
8856 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008857 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008858 /*DiscardedValue=*/true);
8859 if (AssignmentOp.isInvalid())
8860 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008861
Alexey Bataev74caaf22016-02-20 04:09:36 +00008862 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008863 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008864 if (TopDVar.CKind == OMPC_firstprivate)
8865 Ref = TopDVar.PrivateCopy;
8866 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008867 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008868 if (!IsOpenMPCapturedDecl(D))
8869 ExprCaptures.push_back(Ref->getDecl());
8870 }
8871 if (TopDVar.CKind == OMPC_firstprivate ||
8872 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008873 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008874 ExprResult RefRes = DefaultLvalueConversion(Ref);
8875 if (!RefRes.isUsable())
8876 continue;
8877 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008878 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8879 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008880 if (!PostUpdateRes.isUsable())
8881 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008882 ExprPostUpdates.push_back(
8883 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008884 }
8885 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008886 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008887 Vars.push_back((VD || CurContext->isDependentContext())
8888 ? RefExpr->IgnoreParens()
8889 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008890 SrcExprs.push_back(PseudoSrcExpr);
8891 DstExprs.push_back(PseudoDstExpr);
8892 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008893 }
8894
8895 if (Vars.empty())
8896 return nullptr;
8897
8898 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008899 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008900 buildPreInits(Context, ExprCaptures),
8901 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008902}
8903
Alexey Bataev758e55e2013-09-06 18:03:48 +00008904OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8905 SourceLocation StartLoc,
8906 SourceLocation LParenLoc,
8907 SourceLocation EndLoc) {
8908 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008909 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008910 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008911 SourceLocation ELoc;
8912 SourceRange ERange;
8913 Expr *SimpleRefExpr = RefExpr;
8914 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008915 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008916 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008917 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008918 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008919 ValueDecl *D = Res.first;
8920 if (!D)
8921 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008922
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008923 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008924 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8925 // in a Construct]
8926 // Variables with the predetermined data-sharing attributes may not be
8927 // listed in data-sharing attributes clauses, except for the cases
8928 // listed below. For these exceptions only, listing a predetermined
8929 // variable in a data-sharing attribute clause is allowed and overrides
8930 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008931 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008932 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8933 DVar.RefExpr) {
8934 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8935 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008936 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008937 continue;
8938 }
8939
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008940 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008941 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008942 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008943 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008944 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8945 ? RefExpr->IgnoreParens()
8946 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008947 }
8948
Alexey Bataeved09d242014-05-28 05:53:51 +00008949 if (Vars.empty())
8950 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008951
8952 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8953}
8954
Alexey Bataevc5e02582014-06-16 07:08:35 +00008955namespace {
8956class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8957 DSAStackTy *Stack;
8958
8959public:
8960 bool VisitDeclRefExpr(DeclRefExpr *E) {
8961 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008962 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008963 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8964 return false;
8965 if (DVar.CKind != OMPC_unknown)
8966 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008967 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8968 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008969 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008970 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008971 return true;
8972 return false;
8973 }
8974 return false;
8975 }
8976 bool VisitStmt(Stmt *S) {
8977 for (auto Child : S->children()) {
8978 if (Child && Visit(Child))
8979 return true;
8980 }
8981 return false;
8982 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008983 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008984};
Alexey Bataev23b69422014-06-18 07:08:49 +00008985} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008986
Alexey Bataev60da77e2016-02-29 05:54:20 +00008987namespace {
8988// Transform MemberExpression for specified FieldDecl of current class to
8989// DeclRefExpr to specified OMPCapturedExprDecl.
8990class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8991 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8992 ValueDecl *Field;
8993 DeclRefExpr *CapturedExpr;
8994
8995public:
8996 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8997 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8998
8999 ExprResult TransformMemberExpr(MemberExpr *E) {
9000 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9001 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009002 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009003 return CapturedExpr;
9004 }
9005 return BaseTransform::TransformMemberExpr(E);
9006 }
9007 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9008};
9009} // namespace
9010
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009011template <typename T>
9012static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9013 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9014 for (auto &Set : Lookups) {
9015 for (auto *D : Set) {
9016 if (auto Res = Gen(cast<ValueDecl>(D)))
9017 return Res;
9018 }
9019 }
9020 return T();
9021}
9022
9023static ExprResult
9024buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9025 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9026 const DeclarationNameInfo &ReductionId, QualType Ty,
9027 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9028 if (ReductionIdScopeSpec.isInvalid())
9029 return ExprError();
9030 SmallVector<UnresolvedSet<8>, 4> Lookups;
9031 if (S) {
9032 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9033 Lookup.suppressDiagnostics();
9034 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9035 auto *D = Lookup.getRepresentativeDecl();
9036 do {
9037 S = S->getParent();
9038 } while (S && !S->isDeclScope(D));
9039 if (S)
9040 S = S->getParent();
9041 Lookups.push_back(UnresolvedSet<8>());
9042 Lookups.back().append(Lookup.begin(), Lookup.end());
9043 Lookup.clear();
9044 }
9045 } else if (auto *ULE =
9046 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9047 Lookups.push_back(UnresolvedSet<8>());
9048 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009049 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009050 if (D == PrevD)
9051 Lookups.push_back(UnresolvedSet<8>());
9052 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9053 Lookups.back().addDecl(DRD);
9054 PrevD = D;
9055 }
9056 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009057 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9058 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009059 Ty->containsUnexpandedParameterPack() ||
9060 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9061 return !D->isInvalidDecl() &&
9062 (D->getType()->isDependentType() ||
9063 D->getType()->isInstantiationDependentType() ||
9064 D->getType()->containsUnexpandedParameterPack());
9065 })) {
9066 UnresolvedSet<8> ResSet;
9067 for (auto &Set : Lookups) {
9068 ResSet.append(Set.begin(), Set.end());
9069 // The last item marks the end of all declarations at the specified scope.
9070 ResSet.addDecl(Set[Set.size() - 1]);
9071 }
9072 return UnresolvedLookupExpr::Create(
9073 SemaRef.Context, /*NamingClass=*/nullptr,
9074 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9075 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9076 }
9077 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9078 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9079 if (!D->isInvalidDecl() &&
9080 SemaRef.Context.hasSameType(D->getType(), Ty))
9081 return D;
9082 return nullptr;
9083 }))
9084 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9085 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9086 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9087 if (!D->isInvalidDecl() &&
9088 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9089 !Ty.isMoreQualifiedThan(D->getType()))
9090 return D;
9091 return nullptr;
9092 })) {
9093 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9094 /*DetectVirtual=*/false);
9095 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9096 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9097 VD->getType().getUnqualifiedType()))) {
9098 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9099 /*DiagID=*/0) !=
9100 Sema::AR_inaccessible) {
9101 SemaRef.BuildBasePathArray(Paths, BasePath);
9102 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9103 }
9104 }
9105 }
9106 }
9107 if (ReductionIdScopeSpec.isSet()) {
9108 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9109 return ExprError();
9110 }
9111 return ExprEmpty();
9112}
9113
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009114namespace {
9115/// Data for the reduction-based clauses.
9116struct ReductionData {
9117 /// List of original reduction items.
9118 SmallVector<Expr *, 8> Vars;
9119 /// List of private copies of the reduction items.
9120 SmallVector<Expr *, 8> Privates;
9121 /// LHS expressions for the reduction_op expressions.
9122 SmallVector<Expr *, 8> LHSs;
9123 /// RHS expressions for the reduction_op expressions.
9124 SmallVector<Expr *, 8> RHSs;
9125 /// Reduction operation expression.
9126 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009127 /// Taskgroup descriptors for the corresponding reduction items in
9128 /// in_reduction clauses.
9129 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009130 /// List of captures for clause.
9131 SmallVector<Decl *, 4> ExprCaptures;
9132 /// List of postupdate expressions.
9133 SmallVector<Expr *, 4> ExprPostUpdates;
9134 ReductionData() = delete;
9135 /// Reserves required memory for the reduction data.
9136 ReductionData(unsigned Size) {
9137 Vars.reserve(Size);
9138 Privates.reserve(Size);
9139 LHSs.reserve(Size);
9140 RHSs.reserve(Size);
9141 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009142 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009143 ExprCaptures.reserve(Size);
9144 ExprPostUpdates.reserve(Size);
9145 }
9146 /// Stores reduction item and reduction operation only (required for dependent
9147 /// reduction item).
9148 void push(Expr *Item, Expr *ReductionOp) {
9149 Vars.emplace_back(Item);
9150 Privates.emplace_back(nullptr);
9151 LHSs.emplace_back(nullptr);
9152 RHSs.emplace_back(nullptr);
9153 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009154 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009155 }
9156 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009157 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9158 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009159 Vars.emplace_back(Item);
9160 Privates.emplace_back(Private);
9161 LHSs.emplace_back(LHS);
9162 RHSs.emplace_back(RHS);
9163 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009164 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009165 }
9166};
9167} // namespace
9168
9169static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009170 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9171 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9172 SourceLocation ColonLoc, SourceLocation EndLoc,
9173 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009174 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009175 auto DN = ReductionId.getName();
9176 auto OOK = DN.getCXXOverloadedOperator();
9177 BinaryOperatorKind BOK = BO_Comma;
9178
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009179 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009180 // OpenMP [2.14.3.6, reduction clause]
9181 // C
9182 // reduction-identifier is either an identifier or one of the following
9183 // operators: +, -, *, &, |, ^, && and ||
9184 // C++
9185 // reduction-identifier is either an id-expression or one of the following
9186 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009187 switch (OOK) {
9188 case OO_Plus:
9189 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009190 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009191 break;
9192 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009193 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009194 break;
9195 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009196 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009197 break;
9198 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009199 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009200 break;
9201 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009202 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009203 break;
9204 case OO_AmpAmp:
9205 BOK = BO_LAnd;
9206 break;
9207 case OO_PipePipe:
9208 BOK = BO_LOr;
9209 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009210 case OO_New:
9211 case OO_Delete:
9212 case OO_Array_New:
9213 case OO_Array_Delete:
9214 case OO_Slash:
9215 case OO_Percent:
9216 case OO_Tilde:
9217 case OO_Exclaim:
9218 case OO_Equal:
9219 case OO_Less:
9220 case OO_Greater:
9221 case OO_LessEqual:
9222 case OO_GreaterEqual:
9223 case OO_PlusEqual:
9224 case OO_MinusEqual:
9225 case OO_StarEqual:
9226 case OO_SlashEqual:
9227 case OO_PercentEqual:
9228 case OO_CaretEqual:
9229 case OO_AmpEqual:
9230 case OO_PipeEqual:
9231 case OO_LessLess:
9232 case OO_GreaterGreater:
9233 case OO_LessLessEqual:
9234 case OO_GreaterGreaterEqual:
9235 case OO_EqualEqual:
9236 case OO_ExclaimEqual:
9237 case OO_PlusPlus:
9238 case OO_MinusMinus:
9239 case OO_Comma:
9240 case OO_ArrowStar:
9241 case OO_Arrow:
9242 case OO_Call:
9243 case OO_Subscript:
9244 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009245 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009246 case NUM_OVERLOADED_OPERATORS:
9247 llvm_unreachable("Unexpected reduction identifier");
9248 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009249 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009250 if (II->isStr("max"))
9251 BOK = BO_GT;
9252 else if (II->isStr("min"))
9253 BOK = BO_LT;
9254 }
9255 break;
9256 }
9257 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009258 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009259 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009260 else
9261 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009262 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009263
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009264 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9265 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009266 for (auto RefExpr : VarList) {
9267 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009268 // OpenMP [2.1, C/C++]
9269 // A list item is a variable or array section, subject to the restrictions
9270 // specified in Section 2.4 on page 42 and in each of the sections
9271 // describing clauses and directives for which a list appears.
9272 // OpenMP [2.14.3.3, Restrictions, p.1]
9273 // A variable that is part of another variable (as an array or
9274 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009275 if (!FirstIter && IR != ER)
9276 ++IR;
9277 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009278 SourceLocation ELoc;
9279 SourceRange ERange;
9280 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009281 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009282 /*AllowArraySection=*/true);
9283 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009284 // Try to find 'declare reduction' corresponding construct before using
9285 // builtin/overloaded operators.
9286 QualType Type = Context.DependentTy;
9287 CXXCastPath BasePath;
9288 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009289 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009290 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009291 Expr *ReductionOp = nullptr;
9292 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009293 (DeclareReductionRef.isUnset() ||
9294 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009295 ReductionOp = DeclareReductionRef.get();
9296 // It will be analyzed later.
9297 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009298 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009299 ValueDecl *D = Res.first;
9300 if (!D)
9301 continue;
9302
Alexey Bataev88202be2017-07-27 13:20:36 +00009303 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009304 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009305 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9306 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9307 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009308 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009309 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009310 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9311 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9312 Type = ATy->getElementType();
9313 else
9314 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009315 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009316 } else
9317 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9318 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009319
Alexey Bataevc5e02582014-06-16 07:08:35 +00009320 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9321 // A variable that appears in a private clause must not have an incomplete
9322 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009323 if (S.RequireCompleteType(ELoc, Type,
9324 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009325 continue;
9326 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009327 // A list item that appears in a reduction clause must not be
9328 // const-qualified.
9329 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009330 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009331 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009332 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9333 VarDecl::DeclarationOnly;
9334 S.Diag(D->getLocation(),
9335 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009336 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009337 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009338 continue;
9339 }
9340 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9341 // If a list-item is a reference type then it must bind to the same object
9342 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009343 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009344 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009345 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009346 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009347 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009348 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9349 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009350 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009351 continue;
9352 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009353 }
9354 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009355
Alexey Bataevc5e02582014-06-16 07:08:35 +00009356 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9357 // in a Construct]
9358 // Variables with the predetermined data-sharing attributes may not be
9359 // listed in data-sharing attributes clauses, except for the cases
9360 // listed below. For these exceptions only, listing a predetermined
9361 // variable in a data-sharing attribute clause is allowed and overrides
9362 // the variable's predetermined data-sharing attributes.
9363 // OpenMP [2.14.3.6, Restrictions, p.3]
9364 // Any number of reduction clauses can be specified on the directive,
9365 // but a list item can appear only once in the reduction clauses for that
9366 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009367 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009368 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009369 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009370 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009371 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009372 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009373 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009374 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009375 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009376 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009377 << getOpenMPClauseName(DVar.CKind)
9378 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009379 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009380 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009381 }
9382
9383 // OpenMP [2.14.3.6, Restrictions, p.1]
9384 // A list item that appears in a reduction clause of a worksharing
9385 // construct must be shared in the parallel regions to which any of the
9386 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009387 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009388 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009389 !isOpenMPParallelDirective(CurrDir) &&
9390 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009391 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009392 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009393 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009394 << getOpenMPClauseName(OMPC_reduction)
9395 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009396 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009397 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009398 }
9399 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009400
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009401 // Try to find 'declare reduction' corresponding construct before using
9402 // builtin/overloaded operators.
9403 CXXCastPath BasePath;
9404 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009405 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009406 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9407 if (DeclareReductionRef.isInvalid())
9408 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009409 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009410 (DeclareReductionRef.isUnset() ||
9411 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009412 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009413 continue;
9414 }
9415 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9416 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009417 S.Diag(ReductionId.getLocStart(),
9418 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009419 << Type << ReductionIdRange;
9420 continue;
9421 }
9422
9423 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9424 // The type of a list item that appears in a reduction clause must be valid
9425 // for the reduction-identifier. For a max or min reduction in C, the type
9426 // of the list item must be an allowed arithmetic data type: char, int,
9427 // float, double, or _Bool, possibly modified with long, short, signed, or
9428 // unsigned. For a max or min reduction in C++, the type of the list item
9429 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9430 // double, or bool, possibly modified with long, short, signed, or unsigned.
9431 if (DeclareReductionRef.isUnset()) {
9432 if ((BOK == BO_GT || BOK == BO_LT) &&
9433 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009434 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9435 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009436 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009437 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009438 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9439 VarDecl::DeclarationOnly;
9440 S.Diag(D->getLocation(),
9441 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009442 << D;
9443 }
9444 continue;
9445 }
9446 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009447 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009448 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9449 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009450 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009451 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9452 VarDecl::DeclarationOnly;
9453 S.Diag(D->getLocation(),
9454 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009455 << D;
9456 }
9457 continue;
9458 }
9459 }
9460
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009461 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009462 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009463 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009464 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009465 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009466 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009467 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009468 (!ASE &&
9469 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009470 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009471 // Create pseudo array type for private copy. The size for this array will
9472 // be generated during codegen.
9473 // For array subscripts or single variables Private Ty is the same as Type
9474 // (type of the variable or single array element).
9475 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009476 Type,
9477 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9478 VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009479 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009480 } else if (!ASE && !OASE &&
9481 Context.getAsArrayType(D->getType().getNonReferenceType()))
9482 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009483 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009484 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009485 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009486 // Add initializer for private variable.
9487 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009488 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9489 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009490 if (DeclareReductionRef.isUsable()) {
9491 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9492 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9493 if (DRD->getInitializer()) {
9494 Init = DRDRef;
9495 RHSVD->setInit(DRDRef);
9496 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009497 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009498 } else {
9499 switch (BOK) {
9500 case BO_Add:
9501 case BO_Xor:
9502 case BO_Or:
9503 case BO_LOr:
9504 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9505 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009506 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009507 break;
9508 case BO_Mul:
9509 case BO_LAnd:
9510 if (Type->isScalarType() || Type->isAnyComplexType()) {
9511 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009512 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009513 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009514 break;
9515 case BO_And: {
9516 // '&' reduction op - initializer is '~0'.
9517 QualType OrigType = Type;
9518 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9519 Type = ComplexTy->getElementType();
9520 if (Type->isRealFloatingType()) {
9521 llvm::APFloat InitValue =
9522 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9523 /*isIEEE=*/true);
9524 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9525 Type, ELoc);
9526 } else if (Type->isScalarType()) {
9527 auto Size = Context.getTypeSize(Type);
9528 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9529 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9530 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9531 }
9532 if (Init && OrigType->isAnyComplexType()) {
9533 // Init = 0xFFFF + 0xFFFFi;
9534 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009535 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009536 }
9537 Type = OrigType;
9538 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009539 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009540 case BO_LT:
9541 case BO_GT: {
9542 // 'min' reduction op - initializer is 'Largest representable number in
9543 // the reduction list item type'.
9544 // 'max' reduction op - initializer is 'Least representable number in
9545 // the reduction list item type'.
9546 if (Type->isIntegerType() || Type->isPointerType()) {
9547 bool IsSigned = Type->hasSignedIntegerRepresentation();
9548 auto Size = Context.getTypeSize(Type);
9549 QualType IntTy =
9550 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9551 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009552 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9553 : llvm::APInt::getMinValue(Size)
9554 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9555 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009556 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9557 if (Type->isPointerType()) {
9558 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009559 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009560 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9561 SourceLocation(), Init);
9562 if (CastExpr.isInvalid())
9563 continue;
9564 Init = CastExpr.get();
9565 }
9566 } else if (Type->isRealFloatingType()) {
9567 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9568 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9569 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9570 Type, ELoc);
9571 }
9572 break;
9573 }
9574 case BO_PtrMemD:
9575 case BO_PtrMemI:
9576 case BO_MulAssign:
9577 case BO_Div:
9578 case BO_Rem:
9579 case BO_Sub:
9580 case BO_Shl:
9581 case BO_Shr:
9582 case BO_LE:
9583 case BO_GE:
9584 case BO_EQ:
9585 case BO_NE:
9586 case BO_AndAssign:
9587 case BO_XorAssign:
9588 case BO_OrAssign:
9589 case BO_Assign:
9590 case BO_AddAssign:
9591 case BO_SubAssign:
9592 case BO_DivAssign:
9593 case BO_RemAssign:
9594 case BO_ShlAssign:
9595 case BO_ShrAssign:
9596 case BO_Comma:
9597 llvm_unreachable("Unexpected reduction operation");
9598 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009599 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009600 if (Init && DeclareReductionRef.isUnset())
9601 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9602 else if (!Init)
9603 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009604 if (RHSVD->isInvalidDecl())
9605 continue;
9606 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009607 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9608 << Type << ReductionIdRange;
9609 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9610 VarDecl::DeclarationOnly;
9611 S.Diag(D->getLocation(),
9612 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009613 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009614 continue;
9615 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009616 // Store initializer for single element in private copy. Will be used during
9617 // codegen.
9618 PrivateVD->setInit(RHSVD->getInit());
9619 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009620 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009621 ExprResult ReductionOp;
9622 if (DeclareReductionRef.isUsable()) {
9623 QualType RedTy = DeclareReductionRef.get()->getType();
9624 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009625 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9626 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009627 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009628 LHS = S.DefaultLvalueConversion(LHS.get());
9629 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009630 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9631 CK_UncheckedDerivedToBase, LHS.get(),
9632 &BasePath, LHS.get()->getValueKind());
9633 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9634 CK_UncheckedDerivedToBase, RHS.get(),
9635 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009636 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009637 FunctionProtoType::ExtProtoInfo EPI;
9638 QualType Params[] = {PtrRedTy, PtrRedTy};
9639 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9640 auto *OVE = new (Context) OpaqueValueExpr(
9641 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009642 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009643 Expr *Args[] = {LHS.get(), RHS.get()};
9644 ReductionOp = new (Context)
9645 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9646 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009647 ReductionOp = S.BuildBinOp(
9648 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009649 if (ReductionOp.isUsable()) {
9650 if (BOK != BO_LT && BOK != BO_GT) {
9651 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009652 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9653 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009654 } else {
9655 auto *ConditionalOp = new (Context) ConditionalOperator(
9656 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9657 RHSDRE, Type, VK_LValue, OK_Ordinary);
9658 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009659 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9660 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009661 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009662 if (ReductionOp.isUsable())
9663 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009664 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009665 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009666 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009667 }
9668
Alexey Bataevfa312f32017-07-21 18:48:21 +00009669 // OpenMP [2.15.4.6, Restrictions, p.2]
9670 // A list item that appears in an in_reduction clause of a task construct
9671 // must appear in a task_reduction clause of a construct associated with a
9672 // taskgroup region that includes the participating task in its taskgroup
9673 // set. The construct associated with the innermost region that meets this
9674 // condition must specify the same reduction-identifier as the in_reduction
9675 // clause.
9676 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00009677 SourceRange ParentSR;
9678 BinaryOperatorKind ParentBOK;
9679 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +00009680 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +00009681 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009682 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
9683 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009684 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009685 Stack->getTopMostTaskgroupReductionData(
9686 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009687 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
9688 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
9689 if (!IsParentBOK && !IsParentReductionOp) {
9690 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
9691 continue;
9692 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00009693 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
9694 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
9695 IsParentReductionOp) {
9696 bool EmitError = true;
9697 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
9698 llvm::FoldingSetNodeID RedId, ParentRedId;
9699 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
9700 DeclareReductionRef.get()->Profile(RedId, Context,
9701 /*Canonical=*/true);
9702 EmitError = RedId != ParentRedId;
9703 }
9704 if (EmitError) {
9705 S.Diag(ReductionId.getLocStart(),
9706 diag::err_omp_reduction_identifier_mismatch)
9707 << ReductionIdRange << RefExpr->getSourceRange();
9708 S.Diag(ParentSR.getBegin(),
9709 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +00009710 << ParentSR
9711 << (IsParentBOK ? ParentBOKDSA.RefExpr
9712 : ParentReductionOpDSA.RefExpr)
9713 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +00009714 continue;
9715 }
9716 }
Alexey Bataev88202be2017-07-27 13:20:36 +00009717 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
9718 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +00009719 }
9720
Alexey Bataev60da77e2016-02-29 05:54:20 +00009721 DeclRefExpr *Ref = nullptr;
9722 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009723 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009724 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009725 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009726 VarsExpr =
9727 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9728 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009729 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009730 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009731 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009732 if (!S.IsOpenMPCapturedDecl(D)) {
9733 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009734 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009735 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009736 if (!RefRes.isUsable())
9737 continue;
9738 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009739 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9740 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009741 if (!PostUpdateRes.isUsable())
9742 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009743 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9744 Stack->getCurrentDirective() == OMPD_taskgroup) {
9745 S.Diag(RefExpr->getExprLoc(),
9746 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009747 << RefExpr->getSourceRange();
9748 continue;
9749 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009750 RD.ExprPostUpdates.emplace_back(
9751 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009752 }
9753 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009754 }
Alexey Bataev169d96a2017-07-18 20:17:46 +00009755 // All reduction items are still marked as reduction (to do not increase
9756 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009757 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009758 if (CurrDir == OMPD_taskgroup) {
9759 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +00009760 Stack->addTaskgroupReductionData(D, ReductionIdRange,
9761 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +00009762 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +00009763 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009764 }
Alexey Bataev88202be2017-07-27 13:20:36 +00009765 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
9766 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009767 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009768 return RD.Vars.empty();
9769}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009770
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009771OMPClause *Sema::ActOnOpenMPReductionClause(
9772 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9773 SourceLocation ColonLoc, SourceLocation EndLoc,
9774 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9775 ArrayRef<Expr *> UnresolvedReductions) {
9776 ReductionData RD(VarList.size());
9777
Alexey Bataev169d96a2017-07-18 20:17:46 +00009778 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
9779 StartLoc, LParenLoc, ColonLoc, EndLoc,
9780 ReductionIdScopeSpec, ReductionId,
9781 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009782 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009783
Alexey Bataevc5e02582014-06-16 07:08:35 +00009784 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009785 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9786 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9787 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9788 buildPreInits(Context, RD.ExprCaptures),
9789 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009790}
9791
Alexey Bataev169d96a2017-07-18 20:17:46 +00009792OMPClause *Sema::ActOnOpenMPTaskReductionClause(
9793 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9794 SourceLocation ColonLoc, SourceLocation EndLoc,
9795 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9796 ArrayRef<Expr *> UnresolvedReductions) {
9797 ReductionData RD(VarList.size());
9798
9799 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
9800 VarList, StartLoc, LParenLoc, ColonLoc,
9801 EndLoc, ReductionIdScopeSpec, ReductionId,
9802 UnresolvedReductions, RD))
9803 return nullptr;
9804
9805 return OMPTaskReductionClause::Create(
9806 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9807 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9808 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9809 buildPreInits(Context, RD.ExprCaptures),
9810 buildPostUpdate(*this, RD.ExprPostUpdates));
9811}
9812
Alexey Bataevfa312f32017-07-21 18:48:21 +00009813OMPClause *Sema::ActOnOpenMPInReductionClause(
9814 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9815 SourceLocation ColonLoc, SourceLocation EndLoc,
9816 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9817 ArrayRef<Expr *> UnresolvedReductions) {
9818 ReductionData RD(VarList.size());
9819
9820 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
9821 StartLoc, LParenLoc, ColonLoc, EndLoc,
9822 ReductionIdScopeSpec, ReductionId,
9823 UnresolvedReductions, RD))
9824 return nullptr;
9825
9826 return OMPInReductionClause::Create(
9827 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9828 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +00009829 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +00009830 buildPreInits(Context, RD.ExprCaptures),
9831 buildPostUpdate(*this, RD.ExprPostUpdates));
9832}
9833
Alexey Bataevecba70f2016-04-12 11:02:11 +00009834bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9835 SourceLocation LinLoc) {
9836 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9837 LinKind == OMPC_LINEAR_unknown) {
9838 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9839 return true;
9840 }
9841 return false;
9842}
9843
9844bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9845 OpenMPLinearClauseKind LinKind,
9846 QualType Type) {
9847 auto *VD = dyn_cast_or_null<VarDecl>(D);
9848 // A variable must not have an incomplete type or a reference type.
9849 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9850 return true;
9851 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9852 !Type->isReferenceType()) {
9853 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9854 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9855 return true;
9856 }
9857 Type = Type.getNonReferenceType();
9858
9859 // A list item must not be const-qualified.
9860 if (Type.isConstant(Context)) {
9861 Diag(ELoc, diag::err_omp_const_variable)
9862 << getOpenMPClauseName(OMPC_linear);
9863 if (D) {
9864 bool IsDecl =
9865 !VD ||
9866 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9867 Diag(D->getLocation(),
9868 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9869 << D;
9870 }
9871 return true;
9872 }
9873
9874 // A list item must be of integral or pointer type.
9875 Type = Type.getUnqualifiedType().getCanonicalType();
9876 const auto *Ty = Type.getTypePtrOrNull();
9877 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9878 !Ty->isPointerType())) {
9879 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9880 if (D) {
9881 bool IsDecl =
9882 !VD ||
9883 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9884 Diag(D->getLocation(),
9885 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9886 << D;
9887 }
9888 return true;
9889 }
9890 return false;
9891}
9892
Alexey Bataev182227b2015-08-20 10:54:39 +00009893OMPClause *Sema::ActOnOpenMPLinearClause(
9894 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9895 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9896 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009897 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009898 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009899 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009900 SmallVector<Decl *, 4> ExprCaptures;
9901 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009902 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009903 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009904 for (auto &RefExpr : VarList) {
9905 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009906 SourceLocation ELoc;
9907 SourceRange ERange;
9908 Expr *SimpleRefExpr = RefExpr;
9909 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9910 /*AllowArraySection=*/false);
9911 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009912 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009913 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009914 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009915 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009916 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009917 ValueDecl *D = Res.first;
9918 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009919 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009920
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009921 QualType Type = D->getType();
9922 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009923
9924 // OpenMP [2.14.3.7, linear clause]
9925 // A list-item cannot appear in more than one linear clause.
9926 // A list-item that appears in a linear clause cannot appear in any
9927 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009928 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009929 if (DVar.RefExpr) {
9930 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9931 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009932 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009933 continue;
9934 }
9935
Alexey Bataevecba70f2016-04-12 11:02:11 +00009936 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009937 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009938 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009939
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009940 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009941 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9942 D->hasAttrs() ? &D->getAttrs() : nullptr);
9943 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009944 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009945 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009946 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009947 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009948 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009949 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9950 if (!IsOpenMPCapturedDecl(D)) {
9951 ExprCaptures.push_back(Ref->getDecl());
9952 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9953 ExprResult RefRes = DefaultLvalueConversion(Ref);
9954 if (!RefRes.isUsable())
9955 continue;
9956 ExprResult PostUpdateRes =
9957 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9958 SimpleRefExpr, RefRes.get());
9959 if (!PostUpdateRes.isUsable())
9960 continue;
9961 ExprPostUpdates.push_back(
9962 IgnoredValueConversions(PostUpdateRes.get()).get());
9963 }
9964 }
9965 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009966 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009967 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009968 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009969 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009970 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009971 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009972 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9973
9974 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009975 Vars.push_back((VD || CurContext->isDependentContext())
9976 ? RefExpr->IgnoreParens()
9977 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009978 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009979 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009980 }
9981
9982 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009983 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009984
9985 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009986 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009987 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9988 !Step->isInstantiationDependent() &&
9989 !Step->containsUnexpandedParameterPack()) {
9990 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009991 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009992 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009993 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009994 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009995
Alexander Musman3276a272015-03-21 10:12:56 +00009996 // Build var to save the step value.
9997 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009998 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009999 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010000 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010001 ExprResult CalcStep =
10002 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010003 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010004
Alexander Musman8dba6642014-04-22 13:09:42 +000010005 // Warn about zero linear step (it would be probably better specified as
10006 // making corresponding variables 'const').
10007 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010008 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10009 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010010 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10011 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010012 if (!IsConstant && CalcStep.isUsable()) {
10013 // Calculate the step beforehand instead of doing this on each iteration.
10014 // (This is not used if the number of iterations may be kfold-ed).
10015 CalcStepExpr = CalcStep.get();
10016 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010017 }
10018
Alexey Bataev182227b2015-08-20 10:54:39 +000010019 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10020 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010021 StepExpr, CalcStepExpr,
10022 buildPreInits(Context, ExprCaptures),
10023 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010024}
10025
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010026static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10027 Expr *NumIterations, Sema &SemaRef,
10028 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010029 // Walk the vars and build update/final expressions for the CodeGen.
10030 SmallVector<Expr *, 8> Updates;
10031 SmallVector<Expr *, 8> Finals;
10032 Expr *Step = Clause.getStep();
10033 Expr *CalcStep = Clause.getCalcStep();
10034 // OpenMP [2.14.3.7, linear clause]
10035 // If linear-step is not specified it is assumed to be 1.
10036 if (Step == nullptr)
10037 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010038 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010039 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010040 }
Alexander Musman3276a272015-03-21 10:12:56 +000010041 bool HasErrors = false;
10042 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010043 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010044 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010045 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010046 SourceLocation ELoc;
10047 SourceRange ERange;
10048 Expr *SimpleRefExpr = RefExpr;
10049 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10050 /*AllowArraySection=*/false);
10051 ValueDecl *D = Res.first;
10052 if (Res.second || !D) {
10053 Updates.push_back(nullptr);
10054 Finals.push_back(nullptr);
10055 HasErrors = true;
10056 continue;
10057 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010058 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010059 Expr *InitExpr = *CurInit;
10060
10061 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010062 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010063 Expr *CapturedRef;
10064 if (LinKind == OMPC_LINEAR_uval)
10065 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10066 else
10067 CapturedRef =
10068 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10069 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10070 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010071
10072 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010073 ExprResult Update;
10074 if (!Info.first) {
10075 Update =
10076 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10077 InitExpr, IV, Step, /* Subtract */ false);
10078 } else
10079 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010080 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10081 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010082
10083 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010084 ExprResult Final;
10085 if (!Info.first) {
10086 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10087 InitExpr, NumIterations, Step,
10088 /* Subtract */ false);
10089 } else
10090 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010091 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10092 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010093
Alexander Musman3276a272015-03-21 10:12:56 +000010094 if (!Update.isUsable() || !Final.isUsable()) {
10095 Updates.push_back(nullptr);
10096 Finals.push_back(nullptr);
10097 HasErrors = true;
10098 } else {
10099 Updates.push_back(Update.get());
10100 Finals.push_back(Final.get());
10101 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010102 ++CurInit;
10103 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010104 }
10105 Clause.setUpdates(Updates);
10106 Clause.setFinals(Finals);
10107 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010108}
10109
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010110OMPClause *Sema::ActOnOpenMPAlignedClause(
10111 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10112 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10113
10114 SmallVector<Expr *, 8> Vars;
10115 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010116 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10117 SourceLocation ELoc;
10118 SourceRange ERange;
10119 Expr *SimpleRefExpr = RefExpr;
10120 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10121 /*AllowArraySection=*/false);
10122 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010123 // It will be analyzed later.
10124 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010125 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010126 ValueDecl *D = Res.first;
10127 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010128 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010129
Alexey Bataev1efd1662016-03-29 10:59:56 +000010130 QualType QType = D->getType();
10131 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010132
10133 // OpenMP [2.8.1, simd construct, Restrictions]
10134 // The type of list items appearing in the aligned clause must be
10135 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010136 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010137 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010138 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010139 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010140 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010141 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010142 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010143 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010144 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010145 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010146 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010147 continue;
10148 }
10149
10150 // OpenMP [2.8.1, simd construct, Restrictions]
10151 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010152 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010153 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010154 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10155 << getOpenMPClauseName(OMPC_aligned);
10156 continue;
10157 }
10158
Alexey Bataev1efd1662016-03-29 10:59:56 +000010159 DeclRefExpr *Ref = nullptr;
10160 if (!VD && IsOpenMPCapturedDecl(D))
10161 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10162 Vars.push_back(DefaultFunctionArrayConversion(
10163 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10164 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010165 }
10166
10167 // OpenMP [2.8.1, simd construct, Description]
10168 // The parameter of the aligned clause, alignment, must be a constant
10169 // positive integer expression.
10170 // If no optional parameter is specified, implementation-defined default
10171 // alignments for SIMD instructions on the target platforms are assumed.
10172 if (Alignment != nullptr) {
10173 ExprResult AlignResult =
10174 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10175 if (AlignResult.isInvalid())
10176 return nullptr;
10177 Alignment = AlignResult.get();
10178 }
10179 if (Vars.empty())
10180 return nullptr;
10181
10182 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10183 EndLoc, Vars, Alignment);
10184}
10185
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010186OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10187 SourceLocation StartLoc,
10188 SourceLocation LParenLoc,
10189 SourceLocation EndLoc) {
10190 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010191 SmallVector<Expr *, 8> SrcExprs;
10192 SmallVector<Expr *, 8> DstExprs;
10193 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010194 for (auto &RefExpr : VarList) {
10195 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10196 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010197 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010198 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010199 SrcExprs.push_back(nullptr);
10200 DstExprs.push_back(nullptr);
10201 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010202 continue;
10203 }
10204
Alexey Bataeved09d242014-05-28 05:53:51 +000010205 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010206 // OpenMP [2.1, C/C++]
10207 // A list item is a variable name.
10208 // OpenMP [2.14.4.1, Restrictions, p.1]
10209 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010210 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010211 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010212 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10213 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010214 continue;
10215 }
10216
10217 Decl *D = DE->getDecl();
10218 VarDecl *VD = cast<VarDecl>(D);
10219
10220 QualType Type = VD->getType();
10221 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10222 // It will be analyzed later.
10223 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010224 SrcExprs.push_back(nullptr);
10225 DstExprs.push_back(nullptr);
10226 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010227 continue;
10228 }
10229
10230 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10231 // A list item that appears in a copyin clause must be threadprivate.
10232 if (!DSAStack->isThreadPrivate(VD)) {
10233 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010234 << getOpenMPClauseName(OMPC_copyin)
10235 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010236 continue;
10237 }
10238
10239 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10240 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010241 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010242 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010243 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010244 auto *SrcVD =
10245 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10246 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010247 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010248 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10249 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010250 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10251 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010252 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010253 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010254 // For arrays generate assignment operation for single element and replace
10255 // it by the original array element in CodeGen.
10256 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10257 PseudoDstExpr, PseudoSrcExpr);
10258 if (AssignmentOp.isInvalid())
10259 continue;
10260 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10261 /*DiscardedValue=*/true);
10262 if (AssignmentOp.isInvalid())
10263 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010264
10265 DSAStack->addDSA(VD, DE, OMPC_copyin);
10266 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010267 SrcExprs.push_back(PseudoSrcExpr);
10268 DstExprs.push_back(PseudoDstExpr);
10269 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010270 }
10271
Alexey Bataeved09d242014-05-28 05:53:51 +000010272 if (Vars.empty())
10273 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010274
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010275 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10276 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010277}
10278
Alexey Bataevbae9a792014-06-27 10:37:06 +000010279OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10280 SourceLocation StartLoc,
10281 SourceLocation LParenLoc,
10282 SourceLocation EndLoc) {
10283 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010284 SmallVector<Expr *, 8> SrcExprs;
10285 SmallVector<Expr *, 8> DstExprs;
10286 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010287 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010288 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10289 SourceLocation ELoc;
10290 SourceRange ERange;
10291 Expr *SimpleRefExpr = RefExpr;
10292 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10293 /*AllowArraySection=*/false);
10294 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010295 // It will be analyzed later.
10296 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010297 SrcExprs.push_back(nullptr);
10298 DstExprs.push_back(nullptr);
10299 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010300 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010301 ValueDecl *D = Res.first;
10302 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010303 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010304
Alexey Bataeve122da12016-03-17 10:50:17 +000010305 QualType Type = D->getType();
10306 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010307
10308 // OpenMP [2.14.4.2, Restrictions, p.2]
10309 // A list item that appears in a copyprivate clause may not appear in a
10310 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010311 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10312 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010313 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10314 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010315 Diag(ELoc, diag::err_omp_wrong_dsa)
10316 << getOpenMPClauseName(DVar.CKind)
10317 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010318 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010319 continue;
10320 }
10321
10322 // OpenMP [2.11.4.2, Restrictions, p.1]
10323 // All list items that appear in a copyprivate clause must be either
10324 // threadprivate or private in the enclosing context.
10325 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010326 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010327 if (DVar.CKind == OMPC_shared) {
10328 Diag(ELoc, diag::err_omp_required_access)
10329 << getOpenMPClauseName(OMPC_copyprivate)
10330 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010331 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010332 continue;
10333 }
10334 }
10335 }
10336
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010337 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010338 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010339 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010340 << getOpenMPClauseName(OMPC_copyprivate) << Type
10341 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010342 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010343 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010344 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010345 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010346 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010347 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010348 continue;
10349 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010350
Alexey Bataevbae9a792014-06-27 10:37:06 +000010351 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10352 // A variable of class type (or array thereof) that appears in a
10353 // copyin clause requires an accessible, unambiguous copy assignment
10354 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010355 Type = Context.getBaseElementType(Type.getNonReferenceType())
10356 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010357 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010358 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10359 D->hasAttrs() ? &D->getAttrs() : nullptr);
10360 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010361 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010362 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10363 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010364 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010365 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010366 PseudoDstExpr, PseudoSrcExpr);
10367 if (AssignmentOp.isInvalid())
10368 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010369 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010370 /*DiscardedValue=*/true);
10371 if (AssignmentOp.isInvalid())
10372 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010373
10374 // No need to mark vars as copyprivate, they are already threadprivate or
10375 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010376 assert(VD || IsOpenMPCapturedDecl(D));
10377 Vars.push_back(
10378 VD ? RefExpr->IgnoreParens()
10379 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010380 SrcExprs.push_back(PseudoSrcExpr);
10381 DstExprs.push_back(PseudoDstExpr);
10382 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010383 }
10384
10385 if (Vars.empty())
10386 return nullptr;
10387
Alexey Bataeva63048e2015-03-23 06:18:07 +000010388 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10389 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010390}
10391
Alexey Bataev6125da92014-07-21 11:26:11 +000010392OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10393 SourceLocation StartLoc,
10394 SourceLocation LParenLoc,
10395 SourceLocation EndLoc) {
10396 if (VarList.empty())
10397 return nullptr;
10398
10399 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10400}
Alexey Bataevdea47612014-07-23 07:46:59 +000010401
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010402OMPClause *
10403Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10404 SourceLocation DepLoc, SourceLocation ColonLoc,
10405 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10406 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010407 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010408 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010409 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010410 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010411 return nullptr;
10412 }
10413 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010414 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10415 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010416 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010417 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010418 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10419 /*Last=*/OMPC_DEPEND_unknown, Except)
10420 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010421 return nullptr;
10422 }
10423 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010424 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010425 llvm::APSInt DepCounter(/*BitWidth=*/32);
10426 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10427 if (DepKind == OMPC_DEPEND_sink) {
10428 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10429 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10430 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010431 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010432 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010433 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10434 DSAStack->getParentOrderedRegionParam()) {
10435 for (auto &RefExpr : VarList) {
10436 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010437 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010438 // It will be analyzed later.
10439 Vars.push_back(RefExpr);
10440 continue;
10441 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010442
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010443 SourceLocation ELoc = RefExpr->getExprLoc();
10444 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10445 if (DepKind == OMPC_DEPEND_sink) {
10446 if (DepCounter >= TotalDepCount) {
10447 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10448 continue;
10449 }
10450 ++DepCounter;
10451 // OpenMP [2.13.9, Summary]
10452 // depend(dependence-type : vec), where dependence-type is:
10453 // 'sink' and where vec is the iteration vector, which has the form:
10454 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10455 // where n is the value specified by the ordered clause in the loop
10456 // directive, xi denotes the loop iteration variable of the i-th nested
10457 // loop associated with the loop directive, and di is a constant
10458 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010459 if (CurContext->isDependentContext()) {
10460 // It will be analyzed later.
10461 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010462 continue;
10463 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010464 SimpleExpr = SimpleExpr->IgnoreImplicit();
10465 OverloadedOperatorKind OOK = OO_None;
10466 SourceLocation OOLoc;
10467 Expr *LHS = SimpleExpr;
10468 Expr *RHS = nullptr;
10469 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10470 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10471 OOLoc = BO->getOperatorLoc();
10472 LHS = BO->getLHS()->IgnoreParenImpCasts();
10473 RHS = BO->getRHS()->IgnoreParenImpCasts();
10474 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10475 OOK = OCE->getOperator();
10476 OOLoc = OCE->getOperatorLoc();
10477 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10478 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10479 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10480 OOK = MCE->getMethodDecl()
10481 ->getNameInfo()
10482 .getName()
10483 .getCXXOverloadedOperator();
10484 OOLoc = MCE->getCallee()->getExprLoc();
10485 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10486 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10487 }
10488 SourceLocation ELoc;
10489 SourceRange ERange;
10490 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10491 /*AllowArraySection=*/false);
10492 if (Res.second) {
10493 // It will be analyzed later.
10494 Vars.push_back(RefExpr);
10495 }
10496 ValueDecl *D = Res.first;
10497 if (!D)
10498 continue;
10499
10500 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10501 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10502 continue;
10503 }
10504 if (RHS) {
10505 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10506 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10507 if (RHSRes.isInvalid())
10508 continue;
10509 }
10510 if (!CurContext->isDependentContext() &&
10511 DSAStack->getParentOrderedRegionParam() &&
10512 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000010513 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
10514 DepCounter.getZExtValue());
10515 if (VD) {
10516 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10517 << 1 << VD;
10518 } else {
10519 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
10520 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010521 continue;
10522 }
10523 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010524 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010525 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010526 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010527 (ASE &&
10528 !ASE->getBase()
10529 ->getType()
10530 .getNonReferenceType()
10531 ->isPointerType() &&
10532 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010533 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10534 << RefExpr->getSourceRange();
10535 continue;
10536 }
10537 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
10538 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
10539 ExprResult Res = CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf,
10540 RefExpr->IgnoreParenImpCasts());
10541 getDiagnostics().setSuppressAllDiagnostics(Suppress);
10542 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
10543 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10544 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010545 continue;
10546 }
10547 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010548 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10549 }
10550
10551 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10552 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000010553 DSAStack->getParentOrderedRegionParam() &&
10554 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
10555 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010556 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10557 }
10558 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10559 Vars.empty())
10560 return nullptr;
10561 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010562 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10563 DepKind, DepLoc, ColonLoc, Vars);
10564 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10565 DSAStack->addDoacrossDependClause(C, OpsOffs);
10566 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010567}
Michael Wonge710d542015-08-07 16:16:36 +000010568
10569OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10570 SourceLocation LParenLoc,
10571 SourceLocation EndLoc) {
10572 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010573
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010574 // OpenMP [2.9.1, Restrictions]
10575 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010576 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10577 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010578 return nullptr;
10579
Michael Wonge710d542015-08-07 16:16:36 +000010580 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10581}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010582
Kelvin Li0bff7af2015-11-23 05:32:03 +000010583static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10584 DSAStackTy *Stack, QualType QTy) {
10585 NamedDecl *ND;
10586 if (QTy->isIncompleteType(&ND)) {
10587 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10588 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010589 }
10590 return true;
10591}
10592
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010593/// \brief Return true if it can be proven that the provided array expression
10594/// (array section or array subscript) does NOT specify the whole size of the
10595/// array whose base type is \a BaseQTy.
10596static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10597 const Expr *E,
10598 QualType BaseQTy) {
10599 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10600
10601 // If this is an array subscript, it refers to the whole size if the size of
10602 // the dimension is constant and equals 1. Also, an array section assumes the
10603 // format of an array subscript if no colon is used.
10604 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10605 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10606 return ATy->getSize().getSExtValue() != 1;
10607 // Size can't be evaluated statically.
10608 return false;
10609 }
10610
10611 assert(OASE && "Expecting array section if not an array subscript.");
10612 auto *LowerBound = OASE->getLowerBound();
10613 auto *Length = OASE->getLength();
10614
10615 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010616 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010617 if (LowerBound) {
10618 llvm::APSInt ConstLowerBound;
10619 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10620 return false; // Can't get the integer value as a constant.
10621 if (ConstLowerBound.getSExtValue())
10622 return true;
10623 }
10624
10625 // If we don't have a length we covering the whole dimension.
10626 if (!Length)
10627 return false;
10628
10629 // If the base is a pointer, we don't have a way to get the size of the
10630 // pointee.
10631 if (BaseQTy->isPointerType())
10632 return false;
10633
10634 // We can only check if the length is the same as the size of the dimension
10635 // if we have a constant array.
10636 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10637 if (!CATy)
10638 return false;
10639
10640 llvm::APSInt ConstLength;
10641 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10642 return false; // Can't get the integer value as a constant.
10643
10644 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10645}
10646
10647// Return true if it can be proven that the provided array expression (array
10648// section or array subscript) does NOT specify a single element of the array
10649// whose base type is \a BaseQTy.
10650static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010651 const Expr *E,
10652 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010653 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10654
10655 // An array subscript always refer to a single element. Also, an array section
10656 // assumes the format of an array subscript if no colon is used.
10657 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10658 return false;
10659
10660 assert(OASE && "Expecting array section if not an array subscript.");
10661 auto *Length = OASE->getLength();
10662
10663 // If we don't have a length we have to check if the array has unitary size
10664 // for this dimension. Also, we should always expect a length if the base type
10665 // is pointer.
10666 if (!Length) {
10667 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10668 return ATy->getSize().getSExtValue() != 1;
10669 // We cannot assume anything.
10670 return false;
10671 }
10672
10673 // Check if the length evaluates to 1.
10674 llvm::APSInt ConstLength;
10675 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10676 return false; // Can't get the integer value as a constant.
10677
10678 return ConstLength.getSExtValue() != 1;
10679}
10680
Samuel Antao661c0902016-05-26 17:39:58 +000010681// Return the expression of the base of the mappable expression or null if it
10682// cannot be determined and do all the necessary checks to see if the expression
10683// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010684// components of the expression.
10685static Expr *CheckMapClauseExpressionBase(
10686 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010687 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10688 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010689 SourceLocation ELoc = E->getExprLoc();
10690 SourceRange ERange = E->getSourceRange();
10691
10692 // The base of elements of list in a map clause have to be either:
10693 // - a reference to variable or field.
10694 // - a member expression.
10695 // - an array expression.
10696 //
10697 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10698 // reference to 'r'.
10699 //
10700 // If we have:
10701 //
10702 // struct SS {
10703 // Bla S;
10704 // foo() {
10705 // #pragma omp target map (S.Arr[:12]);
10706 // }
10707 // }
10708 //
10709 // We want to retrieve the member expression 'this->S';
10710
10711 Expr *RelevantExpr = nullptr;
10712
Samuel Antao5de996e2016-01-22 20:21:36 +000010713 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10714 // If a list item is an array section, it must specify contiguous storage.
10715 //
10716 // For this restriction it is sufficient that we make sure only references
10717 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010718 // exist except in the rightmost expression (unless they cover the whole
10719 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010720 //
10721 // r.ArrS[3:5].Arr[6:7]
10722 //
10723 // r.ArrS[3:5].x
10724 //
10725 // but these would be valid:
10726 // r.ArrS[3].Arr[6:7]
10727 //
10728 // r.ArrS[3].x
10729
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010730 bool AllowUnitySizeArraySection = true;
10731 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010732
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010733 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010734 E = E->IgnoreParenImpCasts();
10735
10736 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10737 if (!isa<VarDecl>(CurE->getDecl()))
10738 break;
10739
10740 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010741
10742 // If we got a reference to a declaration, we should not expect any array
10743 // section before that.
10744 AllowUnitySizeArraySection = false;
10745 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010746
10747 // Record the component.
10748 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10749 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010750 continue;
10751 }
10752
10753 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10754 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10755
10756 if (isa<CXXThisExpr>(BaseE))
10757 // We found a base expression: this->Val.
10758 RelevantExpr = CurE;
10759 else
10760 E = BaseE;
10761
10762 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10763 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10764 << CurE->getSourceRange();
10765 break;
10766 }
10767
10768 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10769
10770 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10771 // A bit-field cannot appear in a map clause.
10772 //
10773 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010774 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10775 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010776 break;
10777 }
10778
10779 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10780 // If the type of a list item is a reference to a type T then the type
10781 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010782 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010783
10784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10785 // A list item cannot be a variable that is a member of a structure with
10786 // a union type.
10787 //
10788 if (auto *RT = CurType->getAs<RecordType>())
10789 if (RT->isUnionType()) {
10790 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10791 << CurE->getSourceRange();
10792 break;
10793 }
10794
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010795 // If we got a member expression, we should not expect any array section
10796 // before that:
10797 //
10798 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10799 // If a list item is an element of a structure, only the rightmost symbol
10800 // of the variable reference can be an array section.
10801 //
10802 AllowUnitySizeArraySection = false;
10803 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010804
10805 // Record the component.
10806 CurComponents.push_back(
10807 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010808 continue;
10809 }
10810
10811 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10812 E = CurE->getBase()->IgnoreParenImpCasts();
10813
10814 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10815 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10816 << 0 << CurE->getSourceRange();
10817 break;
10818 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010819
10820 // If we got an array subscript that express the whole dimension we
10821 // can have any array expressions before. If it only expressing part of
10822 // the dimension, we can only have unitary-size array expressions.
10823 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10824 E->getType()))
10825 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010826
10827 // Record the component - we don't have any declaration associated.
10828 CurComponents.push_back(
10829 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010830 continue;
10831 }
10832
10833 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010834 E = CurE->getBase()->IgnoreParenImpCasts();
10835
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010836 auto CurType =
10837 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10838
Samuel Antao5de996e2016-01-22 20:21:36 +000010839 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10840 // If the type of a list item is a reference to a type T then the type
10841 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010842 if (CurType->isReferenceType())
10843 CurType = CurType->getPointeeType();
10844
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010845 bool IsPointer = CurType->isAnyPointerType();
10846
10847 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010848 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10849 << 0 << CurE->getSourceRange();
10850 break;
10851 }
10852
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010853 bool NotWhole =
10854 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10855 bool NotUnity =
10856 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10857
Samuel Antaodab51bb2016-07-18 23:22:11 +000010858 if (AllowWholeSizeArraySection) {
10859 // Any array section is currently allowed. Allowing a whole size array
10860 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010861 //
10862 // If this array section refers to the whole dimension we can still
10863 // accept other array sections before this one, except if the base is a
10864 // pointer. Otherwise, only unitary sections are accepted.
10865 if (NotWhole || IsPointer)
10866 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010867 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010868 // A unity or whole array section is not allowed and that is not
10869 // compatible with the properties of the current array section.
10870 SemaRef.Diag(
10871 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10872 << CurE->getSourceRange();
10873 break;
10874 }
Samuel Antao90927002016-04-26 14:54:23 +000010875
10876 // Record the component - we don't have any declaration associated.
10877 CurComponents.push_back(
10878 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010879 continue;
10880 }
10881
10882 // If nothing else worked, this is not a valid map clause expression.
10883 SemaRef.Diag(ELoc,
10884 diag::err_omp_expected_named_var_member_or_array_expression)
10885 << ERange;
10886 break;
10887 }
10888
10889 return RelevantExpr;
10890}
10891
10892// Return true if expression E associated with value VD has conflicts with other
10893// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010894static bool CheckMapConflicts(
10895 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10896 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010897 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10898 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010899 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010900 SourceLocation ELoc = E->getExprLoc();
10901 SourceRange ERange = E->getSourceRange();
10902
10903 // In order to easily check the conflicts we need to match each component of
10904 // the expression under test with the components of the expressions that are
10905 // already in the stack.
10906
Samuel Antao5de996e2016-01-22 20:21:36 +000010907 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010908 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010909 "Map clause expression with unexpected base!");
10910
10911 // Variables to help detecting enclosing problems in data environment nests.
10912 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010913 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010914
Samuel Antao90927002016-04-26 14:54:23 +000010915 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10916 VD, CurrentRegionOnly,
10917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010918 StackComponents,
10919 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010920
Samuel Antao5de996e2016-01-22 20:21:36 +000010921 assert(!StackComponents.empty() &&
10922 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010923 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010924 "Map clause expression with unexpected base!");
10925
Samuel Antao90927002016-04-26 14:54:23 +000010926 // The whole expression in the stack.
10927 auto *RE = StackComponents.front().getAssociatedExpression();
10928
Samuel Antao5de996e2016-01-22 20:21:36 +000010929 // Expressions must start from the same base. Here we detect at which
10930 // point both expressions diverge from each other and see if we can
10931 // detect if the memory referred to both expressions is contiguous and
10932 // do not overlap.
10933 auto CI = CurComponents.rbegin();
10934 auto CE = CurComponents.rend();
10935 auto SI = StackComponents.rbegin();
10936 auto SE = StackComponents.rend();
10937 for (; CI != CE && SI != SE; ++CI, ++SI) {
10938
10939 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10940 // At most one list item can be an array item derived from a given
10941 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010942 if (CurrentRegionOnly &&
10943 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10944 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10945 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10946 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10947 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010948 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010949 << CI->getAssociatedExpression()->getSourceRange();
10950 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10951 diag::note_used_here)
10952 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010953 return true;
10954 }
10955
10956 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010957 if (CI->getAssociatedExpression()->getStmtClass() !=
10958 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010959 break;
10960
10961 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010962 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010963 break;
10964 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010965 // Check if the extra components of the expressions in the enclosing
10966 // data environment are redundant for the current base declaration.
10967 // If they are, the maps completely overlap, which is legal.
10968 for (; SI != SE; ++SI) {
10969 QualType Type;
10970 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010971 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010972 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010973 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10974 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010975 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10976 Type =
10977 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10978 }
10979 if (Type.isNull() || Type->isAnyPointerType() ||
10980 CheckArrayExpressionDoesNotReferToWholeSize(
10981 SemaRef, SI->getAssociatedExpression(), Type))
10982 break;
10983 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010984
10985 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10986 // List items of map clauses in the same construct must not share
10987 // original storage.
10988 //
10989 // If the expressions are exactly the same or one is a subset of the
10990 // other, it means they are sharing storage.
10991 if (CI == CE && SI == SE) {
10992 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010993 if (CKind == OMPC_map)
10994 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10995 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010996 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010997 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10998 << ERange;
10999 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011000 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11001 << RE->getSourceRange();
11002 return true;
11003 } else {
11004 // If we find the same expression in the enclosing data environment,
11005 // that is legal.
11006 IsEnclosedByDataEnvironmentExpr = true;
11007 return false;
11008 }
11009 }
11010
Samuel Antao90927002016-04-26 14:54:23 +000011011 QualType DerivedType =
11012 std::prev(CI)->getAssociatedDeclaration()->getType();
11013 SourceLocation DerivedLoc =
11014 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011015
11016 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11017 // If the type of a list item is a reference to a type T then the type
11018 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011019 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011020
11021 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11022 // A variable for which the type is pointer and an array section
11023 // derived from that variable must not appear as list items of map
11024 // clauses of the same construct.
11025 //
11026 // Also, cover one of the cases in:
11027 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11028 // If any part of the original storage of a list item has corresponding
11029 // storage in the device data environment, all of the original storage
11030 // must have corresponding storage in the device data environment.
11031 //
11032 if (DerivedType->isAnyPointerType()) {
11033 if (CI == CE || SI == SE) {
11034 SemaRef.Diag(
11035 DerivedLoc,
11036 diag::err_omp_pointer_mapped_along_with_derived_section)
11037 << DerivedLoc;
11038 } else {
11039 assert(CI != CE && SI != SE);
11040 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11041 << DerivedLoc;
11042 }
11043 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11044 << RE->getSourceRange();
11045 return true;
11046 }
11047
11048 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11049 // List items of map clauses in the same construct must not share
11050 // original storage.
11051 //
11052 // An expression is a subset of the other.
11053 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011054 if (CKind == OMPC_map)
11055 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11056 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011057 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011058 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11059 << ERange;
11060 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011061 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11062 << RE->getSourceRange();
11063 return true;
11064 }
11065
11066 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011067 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011068 if (!CurrentRegionOnly && SI != SE)
11069 EnclosingExpr = RE;
11070
11071 // The current expression is a subset of the expression in the data
11072 // environment.
11073 IsEnclosedByDataEnvironmentExpr |=
11074 (!CurrentRegionOnly && CI != CE && SI == SE);
11075
11076 return false;
11077 });
11078
11079 if (CurrentRegionOnly)
11080 return FoundError;
11081
11082 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11083 // If any part of the original storage of a list item has corresponding
11084 // storage in the device data environment, all of the original storage must
11085 // have corresponding storage in the device data environment.
11086 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11087 // If a list item is an element of a structure, and a different element of
11088 // the structure has a corresponding list item in the device data environment
11089 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011090 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011091 // data environment prior to the task encountering the construct.
11092 //
11093 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11094 SemaRef.Diag(ELoc,
11095 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11096 << ERange;
11097 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11098 << EnclosingExpr->getSourceRange();
11099 return true;
11100 }
11101
11102 return FoundError;
11103}
11104
Samuel Antao661c0902016-05-26 17:39:58 +000011105namespace {
11106// Utility struct that gathers all the related lists associated with a mappable
11107// expression.
11108struct MappableVarListInfo final {
11109 // The list of expressions.
11110 ArrayRef<Expr *> VarList;
11111 // The list of processed expressions.
11112 SmallVector<Expr *, 16> ProcessedVarList;
11113 // The mappble components for each expression.
11114 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11115 // The base declaration of the variable.
11116 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11117
11118 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11119 // We have a list of components and base declarations for each entry in the
11120 // variable list.
11121 VarComponents.reserve(VarList.size());
11122 VarBaseDeclarations.reserve(VarList.size());
11123 }
11124};
11125}
11126
11127// Check the validity of the provided variable list for the provided clause kind
11128// \a CKind. In the check process the valid expressions, and mappable expression
11129// components and variables are extracted and used to fill \a Vars,
11130// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11131// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11132static void
11133checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11134 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11135 SourceLocation StartLoc,
11136 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11137 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011138 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11139 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011140 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011141
Samuel Antao90927002016-04-26 14:54:23 +000011142 // Keep track of the mappable components and base declarations in this clause.
11143 // Each entry in the list is going to have a list of components associated. We
11144 // record each set of the components so that we can build the clause later on.
11145 // In the end we should have the same amount of declarations and component
11146 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011147
Samuel Antao661c0902016-05-26 17:39:58 +000011148 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011149 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011150 SourceLocation ELoc = RE->getExprLoc();
11151
Kelvin Li0bff7af2015-11-23 05:32:03 +000011152 auto *VE = RE->IgnoreParenLValueCasts();
11153
11154 if (VE->isValueDependent() || VE->isTypeDependent() ||
11155 VE->isInstantiationDependent() ||
11156 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011157 // We can only analyze this information once the missing information is
11158 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011159 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011160 continue;
11161 }
11162
11163 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011164
Samuel Antao5de996e2016-01-22 20:21:36 +000011165 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011166 SemaRef.Diag(ELoc,
11167 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011168 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011169 continue;
11170 }
11171
Samuel Antao90927002016-04-26 14:54:23 +000011172 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11173 ValueDecl *CurDeclaration = nullptr;
11174
11175 // Obtain the array or member expression bases if required. Also, fill the
11176 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011177 auto *BE =
11178 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011179 if (!BE)
11180 continue;
11181
Samuel Antao90927002016-04-26 14:54:23 +000011182 assert(!CurComponents.empty() &&
11183 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011184
Samuel Antao90927002016-04-26 14:54:23 +000011185 // For the following checks, we rely on the base declaration which is
11186 // expected to be associated with the last component. The declaration is
11187 // expected to be a variable or a field (if 'this' is being mapped).
11188 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11189 assert(CurDeclaration && "Null decl on map clause.");
11190 assert(
11191 CurDeclaration->isCanonicalDecl() &&
11192 "Expecting components to have associated only canonical declarations.");
11193
11194 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11195 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011196
11197 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011198 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011199
11200 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011201 // threadprivate variables cannot appear in a map clause.
11202 // OpenMP 4.5 [2.10.5, target update Construct]
11203 // threadprivate variables cannot appear in a from clause.
11204 if (VD && DSAS->isThreadPrivate(VD)) {
11205 auto DVar = DSAS->getTopDSA(VD, false);
11206 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11207 << getOpenMPClauseName(CKind);
11208 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011209 continue;
11210 }
11211
Samuel Antao5de996e2016-01-22 20:21:36 +000011212 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11213 // A list item cannot appear in both a map clause and a data-sharing
11214 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011215
Samuel Antao5de996e2016-01-22 20:21:36 +000011216 // Check conflicts with other map clause expressions. We check the conflicts
11217 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011218 // environment, because the restrictions are different. We only have to
11219 // check conflicts across regions for the map clauses.
11220 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11221 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011222 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011223 if (CKind == OMPC_map &&
11224 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11225 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011226 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011227
Samuel Antao661c0902016-05-26 17:39:58 +000011228 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011229 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11230 // If the type of a list item is a reference to a type T then the type will
11231 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011232 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011233
Samuel Antao661c0902016-05-26 17:39:58 +000011234 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11235 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011236 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011237 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011238 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11239 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011240 continue;
11241
Samuel Antao661c0902016-05-26 17:39:58 +000011242 if (CKind == OMPC_map) {
11243 // target enter data
11244 // OpenMP [2.10.2, Restrictions, p. 99]
11245 // A map-type must be specified in all map clauses and must be either
11246 // to or alloc.
11247 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11248 if (DKind == OMPD_target_enter_data &&
11249 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11250 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11251 << (IsMapTypeImplicit ? 1 : 0)
11252 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11253 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011254 continue;
11255 }
Samuel Antao661c0902016-05-26 17:39:58 +000011256
11257 // target exit_data
11258 // OpenMP [2.10.3, Restrictions, p. 102]
11259 // A map-type must be specified in all map clauses and must be either
11260 // from, release, or delete.
11261 if (DKind == OMPD_target_exit_data &&
11262 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11263 MapType == OMPC_MAP_delete)) {
11264 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11265 << (IsMapTypeImplicit ? 1 : 0)
11266 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11267 << getOpenMPDirectiveName(DKind);
11268 continue;
11269 }
11270
11271 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11272 // A list item cannot appear in both a map clause and a data-sharing
11273 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011274 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011275 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011276 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011277 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11278 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011279 auto DVar = DSAS->getTopDSA(VD, false);
11280 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011281 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011282 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011283 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011284 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11285 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11286 continue;
11287 }
11288 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011289 }
11290
Samuel Antao90927002016-04-26 14:54:23 +000011291 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011292 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011293
11294 // Store the components in the stack so that they can be used to check
11295 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011296 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11297 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011298
11299 // Save the components and declaration to create the clause. For purposes of
11300 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011301 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011302 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11303 MVLI.VarComponents.back().append(CurComponents.begin(),
11304 CurComponents.end());
11305 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11306 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011307 }
Samuel Antao661c0902016-05-26 17:39:58 +000011308}
11309
11310OMPClause *
11311Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11312 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11313 SourceLocation MapLoc, SourceLocation ColonLoc,
11314 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11315 SourceLocation LParenLoc, SourceLocation EndLoc) {
11316 MappableVarListInfo MVLI(VarList);
11317 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11318 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011319
Samuel Antao5de996e2016-01-22 20:21:36 +000011320 // We need to produce a map clause even if we don't have variables so that
11321 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011322 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11323 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11324 MVLI.VarComponents, MapTypeModifier, MapType,
11325 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011326}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011327
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011328QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11329 TypeResult ParsedType) {
11330 assert(ParsedType.isUsable());
11331
11332 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11333 if (ReductionType.isNull())
11334 return QualType();
11335
11336 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11337 // A type name in a declare reduction directive cannot be a function type, an
11338 // array type, a reference type, or a type qualified with const, volatile or
11339 // restrict.
11340 if (ReductionType.hasQualifiers()) {
11341 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11342 return QualType();
11343 }
11344
11345 if (ReductionType->isFunctionType()) {
11346 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11347 return QualType();
11348 }
11349 if (ReductionType->isReferenceType()) {
11350 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11351 return QualType();
11352 }
11353 if (ReductionType->isArrayType()) {
11354 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11355 return QualType();
11356 }
11357 return ReductionType;
11358}
11359
11360Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11361 Scope *S, DeclContext *DC, DeclarationName Name,
11362 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11363 AccessSpecifier AS, Decl *PrevDeclInScope) {
11364 SmallVector<Decl *, 8> Decls;
11365 Decls.reserve(ReductionTypes.size());
11366
11367 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11368 ForRedeclaration);
11369 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11370 // A reduction-identifier may not be re-declared in the current scope for the
11371 // same type or for a type that is compatible according to the base language
11372 // rules.
11373 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11374 OMPDeclareReductionDecl *PrevDRD = nullptr;
11375 bool InCompoundScope = true;
11376 if (S != nullptr) {
11377 // Find previous declaration with the same name not referenced in other
11378 // declarations.
11379 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11380 InCompoundScope =
11381 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11382 LookupName(Lookup, S);
11383 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11384 /*AllowInlineNamespace=*/false);
11385 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11386 auto Filter = Lookup.makeFilter();
11387 while (Filter.hasNext()) {
11388 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11389 if (InCompoundScope) {
11390 auto I = UsedAsPrevious.find(PrevDecl);
11391 if (I == UsedAsPrevious.end())
11392 UsedAsPrevious[PrevDecl] = false;
11393 if (auto *D = PrevDecl->getPrevDeclInScope())
11394 UsedAsPrevious[D] = true;
11395 }
11396 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11397 PrevDecl->getLocation();
11398 }
11399 Filter.done();
11400 if (InCompoundScope) {
11401 for (auto &PrevData : UsedAsPrevious) {
11402 if (!PrevData.second) {
11403 PrevDRD = PrevData.first;
11404 break;
11405 }
11406 }
11407 }
11408 } else if (PrevDeclInScope != nullptr) {
11409 auto *PrevDRDInScope = PrevDRD =
11410 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11411 do {
11412 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11413 PrevDRDInScope->getLocation();
11414 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11415 } while (PrevDRDInScope != nullptr);
11416 }
11417 for (auto &TyData : ReductionTypes) {
11418 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11419 bool Invalid = false;
11420 if (I != PreviousRedeclTypes.end()) {
11421 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11422 << TyData.first;
11423 Diag(I->second, diag::note_previous_definition);
11424 Invalid = true;
11425 }
11426 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11427 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11428 Name, TyData.first, PrevDRD);
11429 DC->addDecl(DRD);
11430 DRD->setAccess(AS);
11431 Decls.push_back(DRD);
11432 if (Invalid)
11433 DRD->setInvalidDecl();
11434 else
11435 PrevDRD = DRD;
11436 }
11437
11438 return DeclGroupPtrTy::make(
11439 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11440}
11441
11442void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11443 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11444
11445 // Enter new function scope.
11446 PushFunctionScope();
11447 getCurFunction()->setHasBranchProtectedScope();
11448 getCurFunction()->setHasOMPDeclareReductionCombiner();
11449
11450 if (S != nullptr)
11451 PushDeclContext(S, DRD);
11452 else
11453 CurContext = DRD;
11454
Faisal Valid143a0c2017-04-01 21:30:49 +000011455 PushExpressionEvaluationContext(
11456 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011457
11458 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011459 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11460 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11461 // uses semantics of argument handles by value, but it should be passed by
11462 // reference. C lang does not support references, so pass all parameters as
11463 // pointers.
11464 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011465 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011466 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011467 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11468 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11469 // uses semantics of argument handles by value, but it should be passed by
11470 // reference. C lang does not support references, so pass all parameters as
11471 // pointers.
11472 // Create 'T omp_out;' variable.
11473 auto *OmpOutParm =
11474 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11475 if (S != nullptr) {
11476 PushOnScopeChains(OmpInParm, S);
11477 PushOnScopeChains(OmpOutParm, S);
11478 } else {
11479 DRD->addDecl(OmpInParm);
11480 DRD->addDecl(OmpOutParm);
11481 }
11482}
11483
11484void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11485 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11486 DiscardCleanupsInEvaluationContext();
11487 PopExpressionEvaluationContext();
11488
11489 PopDeclContext();
11490 PopFunctionScopeInfo();
11491
11492 if (Combiner != nullptr)
11493 DRD->setCombiner(Combiner);
11494 else
11495 DRD->setInvalidDecl();
11496}
11497
Alexey Bataev070f43a2017-09-06 14:49:58 +000011498VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011499 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11500
11501 // Enter new function scope.
11502 PushFunctionScope();
11503 getCurFunction()->setHasBranchProtectedScope();
11504
11505 if (S != nullptr)
11506 PushDeclContext(S, DRD);
11507 else
11508 CurContext = DRD;
11509
Faisal Valid143a0c2017-04-01 21:30:49 +000011510 PushExpressionEvaluationContext(
11511 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011512
11513 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011514 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11515 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11516 // uses semantics of argument handles by value, but it should be passed by
11517 // reference. C lang does not support references, so pass all parameters as
11518 // pointers.
11519 // Create 'T omp_priv;' variable.
11520 auto *OmpPrivParm =
11521 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011522 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11523 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11524 // uses semantics of argument handles by value, but it should be passed by
11525 // reference. C lang does not support references, so pass all parameters as
11526 // pointers.
11527 // Create 'T omp_orig;' variable.
11528 auto *OmpOrigParm =
11529 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011530 if (S != nullptr) {
11531 PushOnScopeChains(OmpPrivParm, S);
11532 PushOnScopeChains(OmpOrigParm, S);
11533 } else {
11534 DRD->addDecl(OmpPrivParm);
11535 DRD->addDecl(OmpOrigParm);
11536 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000011537 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011538}
11539
Alexey Bataev070f43a2017-09-06 14:49:58 +000011540void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
11541 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011542 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11543 DiscardCleanupsInEvaluationContext();
11544 PopExpressionEvaluationContext();
11545
11546 PopDeclContext();
11547 PopFunctionScopeInfo();
11548
Alexey Bataev070f43a2017-09-06 14:49:58 +000011549 if (Initializer != nullptr) {
11550 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
11551 } else if (OmpPrivParm->hasInit()) {
11552 DRD->setInitializer(OmpPrivParm->getInit(),
11553 OmpPrivParm->isDirectInit()
11554 ? OMPDeclareReductionDecl::DirectInit
11555 : OMPDeclareReductionDecl::CopyInit);
11556 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011557 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000011558 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011559}
11560
11561Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11562 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11563 for (auto *D : DeclReductions.get()) {
11564 if (IsValid) {
11565 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11566 if (S != nullptr)
11567 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11568 } else
11569 D->setInvalidDecl();
11570 }
11571 return DeclReductions;
11572}
11573
David Majnemer9d168222016-08-05 17:44:54 +000011574OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011575 SourceLocation StartLoc,
11576 SourceLocation LParenLoc,
11577 SourceLocation EndLoc) {
11578 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011579 Stmt *HelperValStmt = nullptr;
11580 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011581
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011582 // OpenMP [teams Constrcut, Restrictions]
11583 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011584 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11585 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011586 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011587
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011588 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11589 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11590 if (CaptureRegion != OMPD_unknown) {
11591 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11592 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11593 HelperValStmt = buildPreInits(Context, Captures);
11594 }
11595
11596 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11597 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011598}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011599
11600OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11601 SourceLocation StartLoc,
11602 SourceLocation LParenLoc,
11603 SourceLocation EndLoc) {
11604 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011605 Stmt *HelperValStmt = nullptr;
11606 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011607
11608 // OpenMP [teams Constrcut, Restrictions]
11609 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011610 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11611 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011612 return nullptr;
11613
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011614 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11615 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11616 if (CaptureRegion != OMPD_unknown) {
11617 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11618 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11619 HelperValStmt = buildPreInits(Context, Captures);
11620 }
11621
11622 return new (Context) OMPThreadLimitClause(
11623 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011624}
Alexey Bataeva0569352015-12-01 10:17:31 +000011625
11626OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11627 SourceLocation StartLoc,
11628 SourceLocation LParenLoc,
11629 SourceLocation EndLoc) {
11630 Expr *ValExpr = Priority;
11631
11632 // OpenMP [2.9.1, task Constrcut]
11633 // The priority-value is a non-negative numerical scalar expression.
11634 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11635 /*StrictlyPositive=*/false))
11636 return nullptr;
11637
11638 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11639}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011640
11641OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11642 SourceLocation StartLoc,
11643 SourceLocation LParenLoc,
11644 SourceLocation EndLoc) {
11645 Expr *ValExpr = Grainsize;
11646
11647 // OpenMP [2.9.2, taskloop Constrcut]
11648 // The parameter of the grainsize clause must be a positive integer
11649 // expression.
11650 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11651 /*StrictlyPositive=*/true))
11652 return nullptr;
11653
11654 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11655}
Alexey Bataev382967a2015-12-08 12:06:20 +000011656
11657OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11658 SourceLocation StartLoc,
11659 SourceLocation LParenLoc,
11660 SourceLocation EndLoc) {
11661 Expr *ValExpr = NumTasks;
11662
11663 // OpenMP [2.9.2, taskloop Constrcut]
11664 // The parameter of the num_tasks clause must be a positive integer
11665 // expression.
11666 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11667 /*StrictlyPositive=*/true))
11668 return nullptr;
11669
11670 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11671}
11672
Alexey Bataev28c75412015-12-15 08:19:24 +000011673OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11674 SourceLocation LParenLoc,
11675 SourceLocation EndLoc) {
11676 // OpenMP [2.13.2, critical construct, Description]
11677 // ... where hint-expression is an integer constant expression that evaluates
11678 // to a valid lock hint.
11679 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11680 if (HintExpr.isInvalid())
11681 return nullptr;
11682 return new (Context)
11683 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11684}
11685
Carlo Bertollib4adf552016-01-15 18:50:31 +000011686OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11687 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11688 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11689 SourceLocation EndLoc) {
11690 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11691 std::string Values;
11692 Values += "'";
11693 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11694 Values += "'";
11695 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11696 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11697 return nullptr;
11698 }
11699 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011700 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011701 if (ChunkSize) {
11702 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11703 !ChunkSize->isInstantiationDependent() &&
11704 !ChunkSize->containsUnexpandedParameterPack()) {
11705 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11706 ExprResult Val =
11707 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11708 if (Val.isInvalid())
11709 return nullptr;
11710
11711 ValExpr = Val.get();
11712
11713 // OpenMP [2.7.1, Restrictions]
11714 // chunk_size must be a loop invariant integer expression with a positive
11715 // value.
11716 llvm::APSInt Result;
11717 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11718 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11719 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11720 << "dist_schedule" << ChunkSize->getSourceRange();
11721 return nullptr;
11722 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011723 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11724 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011725 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11726 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11727 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011728 }
11729 }
11730 }
11731
11732 return new (Context)
11733 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011734 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011735}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011736
11737OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11738 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11739 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11740 SourceLocation KindLoc, SourceLocation EndLoc) {
11741 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011742 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011743 std::string Value;
11744 SourceLocation Loc;
11745 Value += "'";
11746 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11747 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011748 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011749 Loc = MLoc;
11750 } else {
11751 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011752 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011753 Loc = KindLoc;
11754 }
11755 Value += "'";
11756 Diag(Loc, diag::err_omp_unexpected_clause_value)
11757 << Value << getOpenMPClauseName(OMPC_defaultmap);
11758 return nullptr;
11759 }
11760
11761 return new (Context)
11762 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11763}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011764
11765bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11766 DeclContext *CurLexicalContext = getCurLexicalContext();
11767 if (!CurLexicalContext->isFileContext() &&
11768 !CurLexicalContext->isExternCContext() &&
11769 !CurLexicalContext->isExternCXXContext()) {
11770 Diag(Loc, diag::err_omp_region_not_file_context);
11771 return false;
11772 }
11773 if (IsInOpenMPDeclareTargetContext) {
11774 Diag(Loc, diag::err_omp_enclosed_declare_target);
11775 return false;
11776 }
11777
11778 IsInOpenMPDeclareTargetContext = true;
11779 return true;
11780}
11781
11782void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11783 assert(IsInOpenMPDeclareTargetContext &&
11784 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11785
11786 IsInOpenMPDeclareTargetContext = false;
11787}
11788
David Majnemer9d168222016-08-05 17:44:54 +000011789void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11790 CXXScopeSpec &ScopeSpec,
11791 const DeclarationNameInfo &Id,
11792 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11793 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011794 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11795 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11796
11797 if (Lookup.isAmbiguous())
11798 return;
11799 Lookup.suppressDiagnostics();
11800
11801 if (!Lookup.isSingleResult()) {
11802 if (TypoCorrection Corrected =
11803 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11804 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11805 CTK_ErrorRecovery)) {
11806 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11807 << Id.getName());
11808 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11809 return;
11810 }
11811
11812 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11813 return;
11814 }
11815
11816 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11817 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11818 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11819 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11820
11821 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11822 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11823 ND->addAttr(A);
11824 if (ASTMutationListener *ML = Context.getASTMutationListener())
11825 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11826 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11827 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11828 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11829 << Id.getName();
11830 }
11831 } else
11832 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11833}
11834
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011835static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11836 Sema &SemaRef, Decl *D) {
11837 if (!D)
11838 return;
11839 Decl *LD = nullptr;
11840 if (isa<TagDecl>(D)) {
11841 LD = cast<TagDecl>(D)->getDefinition();
11842 } else if (isa<VarDecl>(D)) {
11843 LD = cast<VarDecl>(D)->getDefinition();
11844
11845 // If this is an implicit variable that is legal and we do not need to do
11846 // anything.
11847 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011848 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11849 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11850 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011851 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011852 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011853 return;
11854 }
11855
11856 } else if (isa<FunctionDecl>(D)) {
11857 const FunctionDecl *FD = nullptr;
11858 if (cast<FunctionDecl>(D)->hasBody(FD))
11859 LD = const_cast<FunctionDecl *>(FD);
11860
11861 // If the definition is associated with the current declaration in the
11862 // target region (it can be e.g. a lambda) that is legal and we do not need
11863 // to do anything else.
11864 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011865 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11866 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11867 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011868 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011869 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011870 return;
11871 }
11872 }
11873 if (!LD)
11874 LD = D;
11875 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11876 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11877 // Outlined declaration is not declared target.
11878 if (LD->isOutOfLine()) {
11879 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11880 SemaRef.Diag(SL, diag::note_used_here) << SR;
11881 } else {
11882 DeclContext *DC = LD->getDeclContext();
11883 while (DC) {
11884 if (isa<FunctionDecl>(DC) &&
11885 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11886 break;
11887 DC = DC->getParent();
11888 }
11889 if (DC)
11890 return;
11891
11892 // Is not declared in target context.
11893 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11894 SemaRef.Diag(SL, diag::note_used_here) << SR;
11895 }
11896 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011897 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11898 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11899 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011900 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011901 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011902 }
11903}
11904
11905static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11906 Sema &SemaRef, DSAStackTy *Stack,
11907 ValueDecl *VD) {
11908 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11909 return true;
11910 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11911 return false;
11912 return true;
11913}
11914
11915void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11916 if (!D || D->isInvalidDecl())
11917 return;
11918 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11919 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11920 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11921 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11922 if (DSAStack->isThreadPrivate(VD)) {
11923 Diag(SL, diag::err_omp_threadprivate_in_target);
11924 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11925 return;
11926 }
11927 }
11928 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11929 // Problem if any with var declared with incomplete type will be reported
11930 // as normal, so no need to check it here.
11931 if ((E || !VD->getType()->isIncompleteType()) &&
11932 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11933 // Mark decl as declared target to prevent further diagnostic.
11934 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011935 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11936 Context, OMPDeclareTargetDeclAttr::MT_To);
11937 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011938 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011939 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011940 }
11941 return;
11942 }
11943 }
11944 if (!E) {
11945 // Checking declaration inside declare target region.
11946 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11947 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011948 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11949 Context, OMPDeclareTargetDeclAttr::MT_To);
11950 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011951 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011952 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011953 }
11954 return;
11955 }
11956 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11957}
Samuel Antao661c0902016-05-26 17:39:58 +000011958
11959OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11960 SourceLocation StartLoc,
11961 SourceLocation LParenLoc,
11962 SourceLocation EndLoc) {
11963 MappableVarListInfo MVLI(VarList);
11964 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11965 if (MVLI.ProcessedVarList.empty())
11966 return nullptr;
11967
11968 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11969 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11970 MVLI.VarComponents);
11971}
Samuel Antaoec172c62016-05-26 17:49:04 +000011972
11973OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11974 SourceLocation StartLoc,
11975 SourceLocation LParenLoc,
11976 SourceLocation EndLoc) {
11977 MappableVarListInfo MVLI(VarList);
11978 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11979 if (MVLI.ProcessedVarList.empty())
11980 return nullptr;
11981
11982 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11983 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11984 MVLI.VarComponents);
11985}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011986
11987OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11988 SourceLocation StartLoc,
11989 SourceLocation LParenLoc,
11990 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011991 MappableVarListInfo MVLI(VarList);
11992 SmallVector<Expr *, 8> PrivateCopies;
11993 SmallVector<Expr *, 8> Inits;
11994
Carlo Bertolli2404b172016-07-13 15:37:16 +000011995 for (auto &RefExpr : VarList) {
11996 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11997 SourceLocation ELoc;
11998 SourceRange ERange;
11999 Expr *SimpleRefExpr = RefExpr;
12000 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12001 if (Res.second) {
12002 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012003 MVLI.ProcessedVarList.push_back(RefExpr);
12004 PrivateCopies.push_back(nullptr);
12005 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012006 }
12007 ValueDecl *D = Res.first;
12008 if (!D)
12009 continue;
12010
12011 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012012 Type = Type.getNonReferenceType().getUnqualifiedType();
12013
12014 auto *VD = dyn_cast<VarDecl>(D);
12015
12016 // Item should be a pointer or reference to pointer.
12017 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012018 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12019 << 0 << RefExpr->getSourceRange();
12020 continue;
12021 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012022
12023 // Build the private variable and the expression that refers to it.
12024 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12025 D->hasAttrs() ? &D->getAttrs() : nullptr);
12026 if (VDPrivate->isInvalidDecl())
12027 continue;
12028
12029 CurContext->addDecl(VDPrivate);
12030 auto VDPrivateRefExpr = buildDeclRefExpr(
12031 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12032
12033 // Add temporary variable to initialize the private copy of the pointer.
12034 auto *VDInit =
12035 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12036 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12037 RefExpr->getExprLoc());
12038 AddInitializerToDecl(VDPrivate,
12039 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012040 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012041
12042 // If required, build a capture to implement the privatization initialized
12043 // with the current list item value.
12044 DeclRefExpr *Ref = nullptr;
12045 if (!VD)
12046 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12047 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12048 PrivateCopies.push_back(VDPrivateRefExpr);
12049 Inits.push_back(VDInitRefExpr);
12050
12051 // We need to add a data sharing attribute for this variable to make sure it
12052 // is correctly captured. A variable that shows up in a use_device_ptr has
12053 // similar properties of a first private variable.
12054 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12055
12056 // Create a mappable component for the list item. List items in this clause
12057 // only need a component.
12058 MVLI.VarBaseDeclarations.push_back(D);
12059 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12060 MVLI.VarComponents.back().push_back(
12061 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012062 }
12063
Samuel Antaocc10b852016-07-28 14:23:26 +000012064 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012065 return nullptr;
12066
Samuel Antaocc10b852016-07-28 14:23:26 +000012067 return OMPUseDevicePtrClause::Create(
12068 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12069 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012070}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012071
12072OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12073 SourceLocation StartLoc,
12074 SourceLocation LParenLoc,
12075 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012076 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012077 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012078 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012079 SourceLocation ELoc;
12080 SourceRange ERange;
12081 Expr *SimpleRefExpr = RefExpr;
12082 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12083 if (Res.second) {
12084 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012085 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012086 }
12087 ValueDecl *D = Res.first;
12088 if (!D)
12089 continue;
12090
12091 QualType Type = D->getType();
12092 // item should be a pointer or array or reference to pointer or array
12093 if (!Type.getNonReferenceType()->isPointerType() &&
12094 !Type.getNonReferenceType()->isArrayType()) {
12095 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12096 << 0 << RefExpr->getSourceRange();
12097 continue;
12098 }
Samuel Antao6890b092016-07-28 14:25:09 +000012099
12100 // Check if the declaration in the clause does not show up in any data
12101 // sharing attribute.
12102 auto DVar = DSAStack->getTopDSA(D, false);
12103 if (isOpenMPPrivate(DVar.CKind)) {
12104 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12105 << getOpenMPClauseName(DVar.CKind)
12106 << getOpenMPClauseName(OMPC_is_device_ptr)
12107 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12108 ReportOriginalDSA(*this, DSAStack, D, DVar);
12109 continue;
12110 }
12111
12112 Expr *ConflictExpr;
12113 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012114 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012115 [&ConflictExpr](
12116 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12117 OpenMPClauseKind) -> bool {
12118 ConflictExpr = R.front().getAssociatedExpression();
12119 return true;
12120 })) {
12121 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12122 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12123 << ConflictExpr->getSourceRange();
12124 continue;
12125 }
12126
12127 // Store the components in the stack so that they can be used to check
12128 // against other clauses later on.
12129 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12130 DSAStack->addMappableExpressionComponents(
12131 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12132
12133 // Record the expression we've just processed.
12134 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12135
12136 // Create a mappable component for the list item. List items in this clause
12137 // only need a component. We use a null declaration to signal fields in
12138 // 'this'.
12139 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12140 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12141 "Unexpected device pointer expression!");
12142 MVLI.VarBaseDeclarations.push_back(
12143 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12144 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12145 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012146 }
12147
Samuel Antao6890b092016-07-28 14:25:09 +000012148 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012149 return nullptr;
12150
Samuel Antao6890b092016-07-28 14:25:09 +000012151 return OMPIsDevicePtrClause::Create(
12152 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12153 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012154}