blob: fd6c19592699d267ed7183b71679f034643920b7 [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 Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000034#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000035using namespace clang;
36
Alexey Bataev758e55e2013-09-06 18:03:48 +000037//===----------------------------------------------------------------------===//
38// Stack of data-sharing attributes for variables
39//===----------------------------------------------------------------------===//
40
41namespace {
42/// \brief Default data sharing attributes, which can be applied to directive.
43enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000044 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
45 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
46 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000047};
Alexey Bataev7ff55242014-06-19 09:13:45 +000048
Alexey Bataev758e55e2013-09-06 18:03:48 +000049/// \brief Stack for tracking declarations used in OpenMP directives and
50/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000051class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000052public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000053 struct DSAVarData final {
54 OpenMPDirectiveKind DKind = OMPD_unknown;
55 OpenMPClauseKind CKind = OMPC_unknown;
56 Expr *RefExpr = nullptr;
57 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000058 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000059 DSAVarData() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +000060 };
Alexey Bataev8b427062016-05-25 12:36:08 +000061 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
62 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000063
Alexey Bataev758e55e2013-09-06 18:03:48 +000064private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 struct DSAInfo final {
66 OpenMPClauseKind Attributes = OMPC_unknown;
67 /// Pointer to a reference expression and a flag which shows that the
68 /// variable is marked as lastprivate(true) or not (false).
69 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
70 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000071 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000072 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
73 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000074 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
75 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000076 /// Struct that associates a component with the clause kind where they are
77 /// found.
78 struct MappedExprComponentTy {
79 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
80 OpenMPClauseKind Kind = OMPC_unknown;
81 };
82 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000083 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000084 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
85 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000086 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
87 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +000088 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +000089 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +000090 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +000091 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +000092 ReductionData() = default;
93 void set(BinaryOperatorKind BO, SourceRange RR) {
94 ReductionRange = RR;
95 ReductionOp = BO;
96 }
97 void set(const Expr *RefExpr, SourceRange RR) {
98 ReductionRange = RR;
99 ReductionOp = RefExpr;
100 }
101 };
102 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000103
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000104 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000105 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000107 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000108 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000109 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000110 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000111 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000112 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000113 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000114 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000115 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000116 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
117 /// get the data (loop counters etc.) about enclosing loop-based construct.
118 /// This data is required during codegen.
119 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000120 /// \brief first argument (Expr *) contains optional argument of the
121 /// 'ordered' clause, the second one is true if the regions has 'ordered'
122 /// clause, false otherwise.
123 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 bool NowaitRegion = false;
125 bool CancelRegion = false;
126 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000127 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000128 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000129 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000130 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
131 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000132 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000133 };
134
Axel Naumann323862e2016-02-03 10:45:22 +0000135 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136
137 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000138 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000139 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
140 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000141 /// \brief true, if check for DSA must be from parent directive, false, if
142 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000143 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000144 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000145 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000146 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000147
148 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
149
David Majnemer9d168222016-08-05 17:44:54 +0000150 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000151
152 /// \brief Checks if the variable is a local for OpenMP region.
153 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000154
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 bool isStackEmpty() const {
156 return Stack.empty() ||
157 Stack.back().second != CurrentNonCapturingFunctionScope ||
158 Stack.back().first.empty();
159 }
160
Alexey Bataev758e55e2013-09-06 18:03:48 +0000161public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000162 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000163
Alexey Bataevaac108a2015-06-23 04:51:00 +0000164 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
165 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000166
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000167 bool isForceVarCapturing() const { return ForceCapturing; }
168 void setForceVarCapturing(bool V) { ForceCapturing = V; }
169
Alexey Bataev758e55e2013-09-06 18:03:48 +0000170 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000171 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000172 if (Stack.empty() ||
173 Stack.back().second != CurrentNonCapturingFunctionScope)
174 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
175 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
176 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177 }
178
179 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000180 assert(!Stack.back().first.empty() &&
181 "Data-sharing attributes stack is empty!");
182 Stack.back().first.pop_back();
183 }
184
185 /// Start new OpenMP region stack in new non-capturing function.
186 void pushFunction() {
187 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
188 assert(!isa<CapturingScopeInfo>(CurFnScope));
189 CurrentNonCapturingFunctionScope = CurFnScope;
190 }
191 /// Pop region stack for non-capturing function.
192 void popFunction(const FunctionScopeInfo *OldFSI) {
193 if (!Stack.empty() && Stack.back().second == OldFSI) {
194 assert(Stack.back().first.empty());
195 Stack.pop_back();
196 }
197 CurrentNonCapturingFunctionScope = nullptr;
198 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
199 if (!isa<CapturingScopeInfo>(FSI)) {
200 CurrentNonCapturingFunctionScope = FSI;
201 break;
202 }
203 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000204 }
205
Alexey Bataev28c75412015-12-15 08:19:24 +0000206 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
207 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
208 }
209 const std::pair<OMPCriticalDirective *, llvm::APSInt>
210 getCriticalWithHint(const DeclarationNameInfo &Name) const {
211 auto I = Criticals.find(Name.getAsString());
212 if (I != Criticals.end())
213 return I->second;
214 return std::make_pair(nullptr, llvm::APSInt());
215 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000216 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000217 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000218 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000219 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000220
Alexey Bataev9c821032015-04-30 04:23:23 +0000221 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000222 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000223 /// \brief Check if the specified variable is a loop control variable for
224 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000225 /// \return The index of the loop control variable in the list of associated
226 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000227 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000228 /// \brief Check if the specified variable is a loop control variable for
229 /// parent region.
230 /// \return The index of the loop control variable in the list of associated
231 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000232 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000233 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
234 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000235 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000236
Alexey Bataev758e55e2013-09-06 18:03:48 +0000237 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000238 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
239 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
Alexey Bataevfa312f32017-07-21 18:48:21 +0000241 /// Adds additional information for the reduction items with the reduction id
242 /// represented as an operator.
243 void addReductionData(ValueDecl *D, SourceRange SR, BinaryOperatorKind BOK);
244 /// Adds additional information for the reduction items with the reduction id
245 /// represented as reduction identifier.
246 void addReductionData(ValueDecl *D, SourceRange SR, const Expr *ReductionRef);
247 /// Returns the location and reduction operation from the innermost parent
248 /// region for the given \p D.
249 bool getTopMostReductionData(ValueDecl *D, SourceRange &SR,
250 BinaryOperatorKind &BOK);
251 /// Returns the location and reduction operation from the innermost parent
252 /// region for the given \p D.
253 bool getTopMostReductionData(ValueDecl *D, SourceRange &SR,
254 const Expr *&ReductionRef);
255
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256 /// \brief Returns data sharing attributes from top of the stack for the
257 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000258 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000259 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000260 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000261 /// \brief Checks if the specified variables has data-sharing attributes which
262 /// match specified \a CPred predicate in any directive which matches \a DPred
263 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000264 DSAVarData hasDSA(ValueDecl *D,
265 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
266 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
267 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000268 /// \brief Checks if the specified variables has data-sharing attributes which
269 /// match specified \a CPred predicate in any innermost directive which
270 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000271 DSAVarData
272 hasInnermostDSA(ValueDecl *D,
273 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
274 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
275 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000276 /// \brief Checks if the specified variables has explicit data-sharing
277 /// attributes which match specified \a CPred predicate at the specified
278 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000279 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000280 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000281 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000282
283 /// \brief Returns true if the directive at level \Level matches in the
284 /// specified \a DPred predicate.
285 bool hasExplicitDirective(
286 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
287 unsigned Level);
288
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000289 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000290 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
291 const DeclarationNameInfo &,
292 SourceLocation)> &DPred,
293 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000294
Alexey Bataev758e55e2013-09-06 18:03:48 +0000295 /// \brief Returns currently analyzed directive.
296 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000297 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000298 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000299 /// \brief Returns parent directive.
300 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000301 if (isStackEmpty() || Stack.back().first.size() == 1)
302 return OMPD_unknown;
303 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000304 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000305
306 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000307 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000308 assert(!isStackEmpty());
309 Stack.back().first.back().DefaultAttr = DSA_none;
310 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000311 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000312 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000313 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000314 assert(!isStackEmpty());
315 Stack.back().first.back().DefaultAttr = DSA_shared;
316 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000317 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000318
319 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000320 return isStackEmpty() ? DSA_unspecified
321 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000322 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000323 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000324 return isStackEmpty() ? SourceLocation()
325 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000326 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000327
Alexey Bataevf29276e2014-06-18 04:14:57 +0000328 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000329 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000330 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000331 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000332 }
333
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000334 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000335 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000336 assert(!isStackEmpty());
337 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
338 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000339 }
340 /// \brief Returns true, if parent region is ordered (has associated
341 /// 'ordered' clause), false - otherwise.
342 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000343 if (isStackEmpty() || Stack.back().first.size() == 1)
344 return false;
345 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000346 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000347 /// \brief Returns optional parameter for the ordered region.
348 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000349 if (isStackEmpty() || Stack.back().first.size() == 1)
350 return nullptr;
351 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000352 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000353 /// \brief Marks current region as nowait (it has a 'nowait' clause).
354 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000355 assert(!isStackEmpty());
356 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000357 }
358 /// \brief Returns true, if parent region is nowait (has associated
359 /// 'nowait' clause), false - otherwise.
360 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000361 if (isStackEmpty() || Stack.back().first.size() == 1)
362 return false;
363 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000364 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000365 /// \brief Marks parent region as cancel region.
366 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000367 if (!isStackEmpty() && Stack.back().first.size() > 1) {
368 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
369 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
370 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000371 }
372 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000373 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000374 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000375 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000376
Alexey Bataev9c821032015-04-30 04:23:23 +0000377 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000378 void setAssociatedLoops(unsigned Val) {
379 assert(!isStackEmpty());
380 Stack.back().first.back().AssociatedLoops = Val;
381 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000382 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000383 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000385 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000386
Alexey Bataev13314bf2014-10-09 04:18:56 +0000387 /// \brief Marks current target region as one with closely nested teams
388 /// region.
389 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000390 if (!isStackEmpty() && Stack.back().first.size() > 1) {
391 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
392 TeamsRegionLoc;
393 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000394 }
395 /// \brief Returns true, if current region has closely nested teams region.
396 bool hasInnerTeamsRegion() const {
397 return getInnerTeamsRegionLoc().isValid();
398 }
399 /// \brief Returns location of the nested teams region (if any).
400 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000401 return isStackEmpty() ? SourceLocation()
402 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000403 }
404
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000405 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000406 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000407 }
408 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000409 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000410 }
411 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000412 return isStackEmpty() ? SourceLocation()
413 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000414 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000415
Samuel Antao4c8035b2016-12-12 18:00:20 +0000416 /// Do the check specified in \a Check to all component lists and return true
417 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000418 bool checkMappableExprComponentListsForDecl(
419 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000420 const llvm::function_ref<
421 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
422 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000423 if (isStackEmpty())
424 return false;
425 auto SI = Stack.back().first.rbegin();
426 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000427
428 if (SI == SE)
429 return false;
430
431 if (CurrentRegionOnly) {
432 SE = std::next(SI);
433 } else {
434 ++SI;
435 }
436
437 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000438 auto MI = SI->MappedExprComponents.find(VD);
439 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000440 for (auto &L : MI->second.Components)
441 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000442 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000443 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000444 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000445 }
446
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000447 /// Do the check specified in \a Check to all component lists at a given level
448 /// and return true if any issue is found.
449 bool checkMappableExprComponentListsForDeclAtLevel(
450 ValueDecl *VD, unsigned Level,
451 const llvm::function_ref<
452 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
453 OpenMPClauseKind)> &Check) {
454 if (isStackEmpty())
455 return false;
456
457 auto StartI = Stack.back().first.begin();
458 auto EndI = Stack.back().first.end();
459 if (std::distance(StartI, EndI) <= (int)Level)
460 return false;
461 std::advance(StartI, Level);
462
463 auto MI = StartI->MappedExprComponents.find(VD);
464 if (MI != StartI->MappedExprComponents.end())
465 for (auto &L : MI->second.Components)
466 if (Check(L, MI->second.Kind))
467 return true;
468 return false;
469 }
470
Samuel Antao4c8035b2016-12-12 18:00:20 +0000471 /// Create a new mappable expression component list associated with a given
472 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000473 void addMappableExpressionComponents(
474 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000475 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
476 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000477 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000478 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000479 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000480 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000481 MEC.Components.resize(MEC.Components.size() + 1);
482 MEC.Components.back().append(Components.begin(), Components.end());
483 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000484 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000485
486 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000487 assert(!isStackEmpty());
488 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000489 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000490 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000491 assert(!isStackEmpty() && Stack.back().first.size() > 1);
492 auto &StackElem = *std::next(Stack.back().first.rbegin());
493 assert(isOpenMPWorksharingDirective(StackElem.Directive));
494 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000495 }
496 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
497 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000498 assert(!isStackEmpty());
499 auto &StackElem = Stack.back().first.back();
500 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
501 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000502 return llvm::make_range(Ref.begin(), Ref.end());
503 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000504 return llvm::make_range(StackElem.DoacrossDepends.end(),
505 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000506 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000507};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000508bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000509 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
510 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000511}
Alexey Bataeved09d242014-05-28 05:53:51 +0000512} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000513
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000514static Expr *getExprAsWritten(Expr *E) {
515 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
516 E = ExprTemp->getSubExpr();
517
518 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
519 E = MTE->GetTemporaryExpr();
520
521 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
522 E = Binder->getSubExpr();
523
524 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
525 E = ICE->getSubExprAsWritten();
526 return E->IgnoreParens();
527}
528
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000529static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000530 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
531 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
532 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000533 auto *VD = dyn_cast<VarDecl>(D);
534 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000535 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000536 VD = VD->getCanonicalDecl();
537 D = VD;
538 } else {
539 assert(FD);
540 FD = FD->getCanonicalDecl();
541 D = FD;
542 }
543 return D;
544}
545
David Majnemer9d168222016-08-05 17:44:54 +0000546DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000547 ValueDecl *D) {
548 D = getCanonicalDecl(D);
549 auto *VD = dyn_cast<VarDecl>(D);
550 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000551 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000552 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000553 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
554 // in a region but not in construct]
555 // File-scope or namespace-scope variables referenced in called routines
556 // in the region are shared unless they appear in a threadprivate
557 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000558 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000559 DVar.CKind = OMPC_shared;
560
561 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
562 // in a region but not in construct]
563 // Variables with static storage duration that are declared in called
564 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000565 if (VD && VD->hasGlobalStorage())
566 DVar.CKind = OMPC_shared;
567
568 // Non-static data members are shared by default.
569 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000570 DVar.CKind = OMPC_shared;
571
Alexey Bataev758e55e2013-09-06 18:03:48 +0000572 return DVar;
573 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000574
Alexey Bataevec3da872014-01-31 05:15:34 +0000575 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
576 // in a Construct, C/C++, predetermined, p.1]
577 // Variables with automatic storage duration that are declared in a scope
578 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000579 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
580 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000581 DVar.CKind = OMPC_private;
582 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000583 }
584
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000585 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000586 // Explicitly specified attributes and local variables with predetermined
587 // attributes.
588 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000589 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000590 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000591 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000592 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000593 return DVar;
594 }
595
596 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
597 // in a Construct, C/C++, implicitly determined, p.1]
598 // In a parallel or task construct, the data-sharing attributes of these
599 // variables are determined by the default clause, if present.
600 switch (Iter->DefaultAttr) {
601 case DSA_shared:
602 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000603 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000604 return DVar;
605 case DSA_none:
606 return DVar;
607 case DSA_unspecified:
608 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
609 // in a Construct, implicitly determined, p.2]
610 // In a parallel construct, if no default clause is present, these
611 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000612 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000613 if (isOpenMPParallelDirective(DVar.DKind) ||
614 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000615 DVar.CKind = OMPC_shared;
616 return DVar;
617 }
618
619 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
620 // in a Construct, implicitly determined, p.4]
621 // In a task construct, if no default clause is present, a variable that in
622 // the enclosing context is determined to be shared by all implicit tasks
623 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000624 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000625 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000626 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000627 do {
628 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000629 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000630 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000631 // In a task construct, if no default clause is present, a variable
632 // whose data-sharing attribute is not determined by the rules above is
633 // firstprivate.
634 DVarTemp = getDSA(I, D);
635 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000636 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000637 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000638 return DVar;
639 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000640 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000641 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000642 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000643 return DVar;
644 }
645 }
646 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
647 // in a Construct, implicitly determined, p.3]
648 // For constructs other than task, if no default clause is present, these
649 // variables inherit their data-sharing attributes from the enclosing
650 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000651 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652}
653
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000654Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000655 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000656 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000657 auto &StackElem = Stack.back().first.back();
658 auto It = StackElem.AlignedMap.find(D);
659 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000660 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000661 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000662 return nullptr;
663 } else {
664 assert(It->second && "Unexpected nullptr expr in the aligned map");
665 return It->second;
666 }
667 return nullptr;
668}
669
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000670void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000671 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000672 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000673 auto &StackElem = Stack.back().first.back();
674 StackElem.LCVMap.insert(
675 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000676}
677
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000678DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000679 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000680 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000681 auto &StackElem = Stack.back().first.back();
682 auto It = StackElem.LCVMap.find(D);
683 if (It != StackElem.LCVMap.end())
684 return It->second;
685 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000686}
687
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000688DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000689 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
690 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000691 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000692 auto &StackElem = *std::next(Stack.back().first.rbegin());
693 auto It = StackElem.LCVMap.find(D);
694 if (It != StackElem.LCVMap.end())
695 return It->second;
696 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000697}
698
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000699ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000700 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
701 "Data-sharing attributes stack is empty");
702 auto &StackElem = *std::next(Stack.back().first.rbegin());
703 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000704 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000705 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000706 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000707 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000708 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000709}
710
Alexey Bataev90c228f2016-02-08 09:29:13 +0000711void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
712 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000713 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000714 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000715 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000716 Data.Attributes = A;
717 Data.RefExpr.setPointer(E);
718 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000720 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
721 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000722 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
723 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
724 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
725 (isLoopControlVariable(D).first && A == OMPC_private));
726 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
727 Data.RefExpr.setInt(/*IntVal=*/true);
728 return;
729 }
730 const bool IsLastprivate =
731 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
732 Data.Attributes = A;
733 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
734 Data.PrivateCopy = PrivateCopy;
735 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000737 Data.Attributes = A;
738 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
739 Data.PrivateCopy = nullptr;
740 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000741 }
742}
743
Alexey Bataevfa312f32017-07-21 18:48:21 +0000744void DSAStackTy::addReductionData(ValueDecl *D, SourceRange SR,
745 BinaryOperatorKind BOK) {
746 D = getCanonicalDecl(D);
747 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000748 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000749 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000750 "Additional reduction info may be specified only for reduction items.");
751 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
752 assert(ReductionData.ReductionRange.isInvalid() &&
753 "Additional reduction info may be specified only once for reduction "
754 "items.");
755 ReductionData.set(BOK, SR);
756}
757
758void DSAStackTy::addReductionData(ValueDecl *D, SourceRange SR,
759 const Expr *ReductionRef) {
760 D = getCanonicalDecl(D);
761 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000762 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000763 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000764 "Additional reduction info may be specified only for reduction items.");
765 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
766 assert(ReductionData.ReductionRange.isInvalid() &&
767 "Additional reduction info may be specified only once for reduction "
768 "items.");
769 ReductionData.set(ReductionRef, SR);
770}
771
772bool DSAStackTy::getTopMostReductionData(ValueDecl *D, SourceRange &SR,
773 BinaryOperatorKind &BOK) {
774 D = getCanonicalDecl(D);
775 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
776 "Data-sharing attributes stack is empty or has only 1 region.");
777 for (auto I = std::next(Stack.back().first.rbegin(), 0),
778 E = Stack.back().first.rend();
779 I != E; std::advance(I, 1)) {
780 auto &Data = I->SharingMap[D];
781 if (Data.Attributes != OMPC_reduction)
782 continue;
783 auto &ReductionData = I->ReductionMap[D];
784 if (!ReductionData.ReductionOp ||
785 ReductionData.ReductionOp.is<const Expr *>())
786 return false;
787 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000788 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000789 return true;
790 }
791 return false;
792}
793
794bool DSAStackTy::getTopMostReductionData(ValueDecl *D, SourceRange &SR,
795 const Expr *&ReductionRef) {
796 D = getCanonicalDecl(D);
797 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
798 "Data-sharing attributes stack is empty or has only 1 region.");
799 for (auto I = std::next(Stack.back().first.rbegin(), 0),
800 E = Stack.back().first.rend();
801 I != E; std::advance(I, 1)) {
802 auto &Data = I->SharingMap[D];
803 if (Data.Attributes != OMPC_reduction)
804 continue;
805 auto &ReductionData = I->ReductionMap[D];
806 if (!ReductionData.ReductionOp ||
807 !ReductionData.ReductionOp.is<const Expr *>())
808 return false;
809 SR = ReductionData.ReductionRange;
810 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
811 return true;
812 }
813 return false;
814}
815
Alexey Bataeved09d242014-05-28 05:53:51 +0000816bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000817 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000818 if (!isStackEmpty() && Stack.back().first.size() > 1) {
819 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000820 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000821 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000822 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000823 if (I == E)
824 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000825 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000826 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000827 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000828 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000829 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000830 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000831 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000832}
833
Alexey Bataev39f915b82015-05-08 10:41:21 +0000834/// \brief Build a variable declaration for OpenMP loop iteration variable.
835static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000836 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000837 DeclContext *DC = SemaRef.CurContext;
838 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
839 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
840 VarDecl *Decl =
841 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000842 if (Attrs) {
843 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
844 I != E; ++I)
845 Decl->addAttr(*I);
846 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000847 Decl->setImplicit();
848 return Decl;
849}
850
851static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
852 SourceLocation Loc,
853 bool RefersToCapture = false) {
854 D->setReferenced();
855 D->markUsed(S.Context);
856 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
857 SourceLocation(), D, RefersToCapture, Loc, Ty,
858 VK_LValue);
859}
860
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000861DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
862 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000863 DSAVarData DVar;
864
865 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
866 // in a Construct, C/C++, predetermined, p.1]
867 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000868 auto *VD = dyn_cast<VarDecl>(D);
869 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
870 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000871 SemaRef.getLangOpts().OpenMPUseTLS &&
872 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000873 (VD && VD->getStorageClass() == SC_Register &&
874 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
875 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000876 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000877 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000878 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000879 auto TI = Threadprivates.find(D);
880 if (TI != Threadprivates.end()) {
881 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000882 DVar.CKind = OMPC_threadprivate;
883 return DVar;
884 }
885
Alexey Bataev4b465392017-04-26 15:06:24 +0000886 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000887 // Not in OpenMP execution region and top scope was already checked.
888 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000889
Alexey Bataev758e55e2013-09-06 18:03:48 +0000890 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000891 // in a Construct, C/C++, predetermined, p.4]
892 // Static data members are shared.
893 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
894 // in a Construct, C/C++, predetermined, p.7]
895 // Variables with static storage duration that are declared in a scope
896 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000897 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000898 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000899 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000900 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000901 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000902
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000903 DVar.CKind = OMPC_shared;
904 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000905 }
906
907 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000908 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
909 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000910 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
911 // in a Construct, C/C++, predetermined, p.6]
912 // Variables with const qualified type having no mutable member are
913 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000914 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000915 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000916 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
917 if (auto *CTD = CTSD->getSpecializedTemplate())
918 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000919 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000920 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
921 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000922 // Variables with const-qualified type having no mutable member may be
923 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000924 DSAVarData DVarTemp = hasDSA(
925 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
926 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000927 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
928 return DVar;
929
Alexey Bataev758e55e2013-09-06 18:03:48 +0000930 DVar.CKind = OMPC_shared;
931 return DVar;
932 }
933
Alexey Bataev758e55e2013-09-06 18:03:48 +0000934 // Explicitly specified attributes and local variables with predetermined
935 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000936 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000937 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000938 if (FromParent && I != EndI)
939 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000940 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000941 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000942 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000943 DVar.CKind = I->SharingMap[D].Attributes;
944 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000945 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000946 }
947
948 return DVar;
949}
950
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000951DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
952 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000953 if (isStackEmpty()) {
954 StackTy::reverse_iterator I;
955 return getDSA(I, D);
956 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000957 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000958 auto StartI = Stack.back().first.rbegin();
959 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000960 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000961 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000962 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000963}
964
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000965DSAStackTy::DSAVarData
966DSAStackTy::hasDSA(ValueDecl *D,
967 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
968 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
969 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000970 if (isStackEmpty())
971 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000972 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000973 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000974 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000975 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +0000976 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000977 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000978 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000979 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000980 auto NewI = I;
981 DSAVarData DVar = getDSA(NewI, D);
982 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000983 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +0000984 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000985 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000986}
987
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000988DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
989 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
990 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
991 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000992 if (isStackEmpty())
993 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000994 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000995 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000996 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000997 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000998 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +0000999 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001000 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001001 auto NewI = StartI;
1002 DSAVarData DVar = getDSA(NewI, D);
1003 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001004}
1005
Alexey Bataevaac108a2015-06-23 04:51:00 +00001006bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001007 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001008 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001009 if (CPred(ClauseKindMode))
1010 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001011 if (isStackEmpty())
1012 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001013 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001014 auto StartI = Stack.back().first.begin();
1015 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001016 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001017 return false;
1018 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001019 return (StartI->SharingMap.count(D) > 0) &&
1020 StartI->SharingMap[D].RefExpr.getPointer() &&
1021 CPred(StartI->SharingMap[D].Attributes) &&
1022 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001023}
1024
Samuel Antao4be30e92015-10-02 17:14:03 +00001025bool DSAStackTy::hasExplicitDirective(
1026 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1027 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001028 if (isStackEmpty())
1029 return false;
1030 auto StartI = Stack.back().first.begin();
1031 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001032 if (std::distance(StartI, EndI) <= (int)Level)
1033 return false;
1034 std::advance(StartI, Level);
1035 return DPred(StartI->Directive);
1036}
1037
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001038bool DSAStackTy::hasDirective(
1039 const llvm::function_ref<bool(OpenMPDirectiveKind,
1040 const DeclarationNameInfo &, SourceLocation)>
1041 &DPred,
1042 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001043 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001044 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001045 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001046 auto StartI = std::next(Stack.back().first.rbegin());
1047 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001048 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001049 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001050 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1051 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1052 return true;
1053 }
1054 return false;
1055}
1056
Alexey Bataev758e55e2013-09-06 18:03:48 +00001057void Sema::InitDataSharingAttributesStack() {
1058 VarDataSharingAttributesStack = new DSAStackTy(*this);
1059}
1060
1061#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1062
Alexey Bataev4b465392017-04-26 15:06:24 +00001063void Sema::pushOpenMPFunctionRegion() {
1064 DSAStack->pushFunction();
1065}
1066
1067void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1068 DSAStack->popFunction(OldFSI);
1069}
1070
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001071bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001072 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1073
1074 auto &Ctx = getASTContext();
1075 bool IsByRef = true;
1076
1077 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001078 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001079
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001080 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001081 // This table summarizes how a given variable should be passed to the device
1082 // given its type and the clauses where it appears. This table is based on
1083 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1084 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1085 //
1086 // =========================================================================
1087 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1088 // | |(tofrom:scalar)| | pvt | | | |
1089 // =========================================================================
1090 // | scl | | | | - | | bycopy|
1091 // | scl | | - | x | - | - | bycopy|
1092 // | scl | | x | - | - | - | null |
1093 // | scl | x | | | - | | byref |
1094 // | scl | x | - | x | - | - | bycopy|
1095 // | scl | x | x | - | - | - | null |
1096 // | scl | | - | - | - | x | byref |
1097 // | scl | x | - | - | - | x | byref |
1098 //
1099 // | agg | n.a. | | | - | | byref |
1100 // | agg | n.a. | - | x | - | - | byref |
1101 // | agg | n.a. | x | - | - | - | null |
1102 // | agg | n.a. | - | - | - | x | byref |
1103 // | agg | n.a. | - | - | - | x[] | byref |
1104 //
1105 // | ptr | n.a. | | | - | | bycopy|
1106 // | ptr | n.a. | - | x | - | - | bycopy|
1107 // | ptr | n.a. | x | - | - | - | null |
1108 // | ptr | n.a. | - | - | - | x | byref |
1109 // | ptr | n.a. | - | - | - | x[] | bycopy|
1110 // | ptr | n.a. | - | - | x | | bycopy|
1111 // | ptr | n.a. | - | - | x | x | bycopy|
1112 // | ptr | n.a. | - | - | x | x[] | bycopy|
1113 // =========================================================================
1114 // Legend:
1115 // scl - scalar
1116 // ptr - pointer
1117 // agg - aggregate
1118 // x - applies
1119 // - - invalid in this combination
1120 // [] - mapped with an array section
1121 // byref - should be mapped by reference
1122 // byval - should be mapped by value
1123 // null - initialize a local variable to null on the device
1124 //
1125 // Observations:
1126 // - All scalar declarations that show up in a map clause have to be passed
1127 // by reference, because they may have been mapped in the enclosing data
1128 // environment.
1129 // - If the scalar value does not fit the size of uintptr, it has to be
1130 // passed by reference, regardless the result in the table above.
1131 // - For pointers mapped by value that have either an implicit map or an
1132 // array section, the runtime library may pass the NULL value to the
1133 // device instead of the value passed to it by the compiler.
1134
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001135 if (Ty->isReferenceType())
1136 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001137
1138 // Locate map clauses and see if the variable being captured is referred to
1139 // in any of those clauses. Here we only care about variables, not fields,
1140 // because fields are part of aggregates.
1141 bool IsVariableUsedInMapClause = false;
1142 bool IsVariableAssociatedWithSection = false;
1143
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001144 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1145 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001146 MapExprComponents,
1147 OpenMPClauseKind WhereFoundClauseKind) {
1148 // Only the map clause information influences how a variable is
1149 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001150 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001151 if (WhereFoundClauseKind != OMPC_map)
1152 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001153
1154 auto EI = MapExprComponents.rbegin();
1155 auto EE = MapExprComponents.rend();
1156
1157 assert(EI != EE && "Invalid map expression!");
1158
1159 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1160 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1161
1162 ++EI;
1163 if (EI == EE)
1164 return false;
1165
1166 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1167 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1168 isa<MemberExpr>(EI->getAssociatedExpression())) {
1169 IsVariableAssociatedWithSection = true;
1170 // There is nothing more we need to know about this variable.
1171 return true;
1172 }
1173
1174 // Keep looking for more map info.
1175 return false;
1176 });
1177
1178 if (IsVariableUsedInMapClause) {
1179 // If variable is identified in a map clause it is always captured by
1180 // reference except if it is a pointer that is dereferenced somehow.
1181 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1182 } else {
1183 // By default, all the data that has a scalar type is mapped by copy.
1184 IsByRef = !Ty->isScalarType();
1185 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001186 }
1187
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001188 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1189 IsByRef = !DSAStack->hasExplicitDSA(
1190 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1191 Level, /*NotLastprivate=*/true);
1192 }
1193
Samuel Antao86ace552016-04-27 22:40:57 +00001194 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001195 // and alignment, because the runtime library only deals with uintptr types.
1196 // If it does not fit the uintptr size, we need to pass the data by reference
1197 // instead.
1198 if (!IsByRef &&
1199 (Ctx.getTypeSizeInChars(Ty) >
1200 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001201 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001202 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001203 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001204
1205 return IsByRef;
1206}
1207
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001208unsigned Sema::getOpenMPNestingLevel() const {
1209 assert(getLangOpts().OpenMP);
1210 return DSAStack->getNestingLevel();
1211}
1212
Alexey Bataev90c228f2016-02-08 09:29:13 +00001213VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001214 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001215 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001216
1217 // If we are attempting to capture a global variable in a directive with
1218 // 'target' we return true so that this global is also mapped to the device.
1219 //
1220 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1221 // then it should not be captured. Therefore, an extra check has to be
1222 // inserted here once support for 'declare target' is added.
1223 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001224 auto *VD = dyn_cast<VarDecl>(D);
1225 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001226 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001227 !DSAStack->isClauseParsingMode())
1228 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001229 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001230 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1231 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001232 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001233 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001234 false))
1235 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001236 }
1237
Alexey Bataev48977c32015-08-04 08:10:48 +00001238 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1239 (!DSAStack->isClauseParsingMode() ||
1240 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001241 auto &&Info = DSAStack->isLoopControlVariable(D);
1242 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001243 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001244 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001245 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001246 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001247 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001248 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001249 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001250 DVarPrivate = DSAStack->hasDSA(
1251 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1252 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001253 if (DVarPrivate.CKind != OMPC_unknown)
1254 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001255 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001256 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001257}
1258
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001259bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001260 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1261 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001262 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001263}
1264
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001265bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001266 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1267 // Return true if the current level is no longer enclosed in a target region.
1268
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001269 auto *VD = dyn_cast<VarDecl>(D);
1270 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001271 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1272 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001273}
1274
Alexey Bataeved09d242014-05-28 05:53:51 +00001275void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001276
1277void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1278 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001279 Scope *CurScope, SourceLocation Loc) {
1280 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001281 PushExpressionEvaluationContext(
1282 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001283}
1284
Alexey Bataevaac108a2015-06-23 04:51:00 +00001285void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1286 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001287}
1288
Alexey Bataevaac108a2015-06-23 04:51:00 +00001289void Sema::EndOpenMPClause() {
1290 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001291}
1292
Alexey Bataev758e55e2013-09-06 18:03:48 +00001293void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001294 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1295 // A variable of class type (or array thereof) that appears in a lastprivate
1296 // clause requires an accessible, unambiguous default constructor for the
1297 // class type, unless the list item is also specified in a firstprivate
1298 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001299 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001300 for (auto *C : D->clauses()) {
1301 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1302 SmallVector<Expr *, 8> PrivateCopies;
1303 for (auto *DE : Clause->varlists()) {
1304 if (DE->isValueDependent() || DE->isTypeDependent()) {
1305 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001306 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001307 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001308 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001309 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1310 QualType Type = VD->getType().getNonReferenceType();
1311 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001312 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001313 // Generate helper private variable and initialize it with the
1314 // default value. The address of the original variable is replaced
1315 // by the address of the new private variable in CodeGen. This new
1316 // variable is not added to IdResolver, so the code in the OpenMP
1317 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001318 auto *VDPrivate = buildVarDecl(
1319 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001320 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001321 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001322 if (VDPrivate->isInvalidDecl())
1323 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001324 PrivateCopies.push_back(buildDeclRefExpr(
1325 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001326 } else {
1327 // The variable is also a firstprivate, so initialization sequence
1328 // for private copy is generated already.
1329 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001330 }
1331 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001332 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001333 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001334 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001335 }
1336 }
1337 }
1338
Alexey Bataev758e55e2013-09-06 18:03:48 +00001339 DSAStack->pop();
1340 DiscardCleanupsInEvaluationContext();
1341 PopExpressionEvaluationContext();
1342}
1343
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001344static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1345 Expr *NumIterations, Sema &SemaRef,
1346 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001347
Alexey Bataeva769e072013-03-22 06:34:35 +00001348namespace {
1349
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001350class VarDeclFilterCCC : public CorrectionCandidateCallback {
1351private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001352 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001353
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001354public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001355 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001356 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001357 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001358 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001359 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001360 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1361 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001362 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001363 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001364 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001365};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001366
1367class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1368private:
1369 Sema &SemaRef;
1370
1371public:
1372 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1373 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1374 NamedDecl *ND = Candidate.getCorrectionDecl();
1375 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1376 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1377 SemaRef.getCurScope());
1378 }
1379 return false;
1380 }
1381};
1382
Alexey Bataeved09d242014-05-28 05:53:51 +00001383} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001384
1385ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1386 CXXScopeSpec &ScopeSpec,
1387 const DeclarationNameInfo &Id) {
1388 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1389 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1390
1391 if (Lookup.isAmbiguous())
1392 return ExprError();
1393
1394 VarDecl *VD;
1395 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001396 if (TypoCorrection Corrected = CorrectTypo(
1397 Id, LookupOrdinaryName, CurScope, nullptr,
1398 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001399 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001400 PDiag(Lookup.empty()
1401 ? diag::err_undeclared_var_use_suggest
1402 : diag::err_omp_expected_var_arg_suggest)
1403 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001404 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001405 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001406 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1407 : diag::err_omp_expected_var_arg)
1408 << Id.getName();
1409 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001410 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001411 } else {
1412 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001413 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001414 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1415 return ExprError();
1416 }
1417 }
1418 Lookup.suppressDiagnostics();
1419
1420 // OpenMP [2.9.2, Syntax, C/C++]
1421 // Variables must be file-scope, namespace-scope, or static block-scope.
1422 if (!VD->hasGlobalStorage()) {
1423 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001424 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1425 bool IsDecl =
1426 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001427 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001428 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1429 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001430 return ExprError();
1431 }
1432
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001433 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1434 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001435 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1436 // A threadprivate directive for file-scope variables must appear outside
1437 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001438 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1439 !getCurLexicalContext()->isTranslationUnit()) {
1440 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001441 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1442 bool IsDecl =
1443 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1444 Diag(VD->getLocation(),
1445 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1446 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001447 return ExprError();
1448 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001449 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1450 // A threadprivate directive for static class member variables must appear
1451 // in the class definition, in the same scope in which the member
1452 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001453 if (CanonicalVD->isStaticDataMember() &&
1454 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1455 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001456 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1457 bool IsDecl =
1458 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1459 Diag(VD->getLocation(),
1460 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1461 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001462 return ExprError();
1463 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001464 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1465 // A threadprivate directive for namespace-scope variables must appear
1466 // outside any definition or declaration other than the namespace
1467 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001468 if (CanonicalVD->getDeclContext()->isNamespace() &&
1469 (!getCurLexicalContext()->isFileContext() ||
1470 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1471 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001472 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1473 bool IsDecl =
1474 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1475 Diag(VD->getLocation(),
1476 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1477 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001478 return ExprError();
1479 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001480 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1481 // A threadprivate directive for static block-scope variables must appear
1482 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001483 if (CanonicalVD->isStaticLocal() && CurScope &&
1484 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001485 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001486 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1487 bool IsDecl =
1488 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1489 Diag(VD->getLocation(),
1490 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1491 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001492 return ExprError();
1493 }
1494
1495 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1496 // A threadprivate directive must lexically precede all references to any
1497 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001498 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001499 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001500 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001501 return ExprError();
1502 }
1503
1504 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001505 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1506 SourceLocation(), VD,
1507 /*RefersToEnclosingVariableOrCapture=*/false,
1508 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001509}
1510
Alexey Bataeved09d242014-05-28 05:53:51 +00001511Sema::DeclGroupPtrTy
1512Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1513 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001514 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001515 CurContext->addDecl(D);
1516 return DeclGroupPtrTy::make(DeclGroupRef(D));
1517 }
David Blaikie0403cb12016-01-15 23:43:25 +00001518 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001519}
1520
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001521namespace {
1522class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1523 Sema &SemaRef;
1524
1525public:
1526 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001527 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001528 if (VD->hasLocalStorage()) {
1529 SemaRef.Diag(E->getLocStart(),
1530 diag::err_omp_local_var_in_threadprivate_init)
1531 << E->getSourceRange();
1532 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1533 << VD << VD->getSourceRange();
1534 return true;
1535 }
1536 }
1537 return false;
1538 }
1539 bool VisitStmt(const Stmt *S) {
1540 for (auto Child : S->children()) {
1541 if (Child && Visit(Child))
1542 return true;
1543 }
1544 return false;
1545 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001546 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001547};
1548} // namespace
1549
Alexey Bataeved09d242014-05-28 05:53:51 +00001550OMPThreadPrivateDecl *
1551Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001552 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001553 for (auto &RefExpr : VarList) {
1554 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001555 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1556 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001557
Alexey Bataev376b4a42016-02-09 09:41:09 +00001558 // Mark variable as used.
1559 VD->setReferenced();
1560 VD->markUsed(Context);
1561
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001562 QualType QType = VD->getType();
1563 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1564 // It will be analyzed later.
1565 Vars.push_back(DE);
1566 continue;
1567 }
1568
Alexey Bataeva769e072013-03-22 06:34:35 +00001569 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1570 // A threadprivate variable must not have an incomplete type.
1571 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001572 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001573 continue;
1574 }
1575
1576 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1577 // A threadprivate variable must not have a reference type.
1578 if (VD->getType()->isReferenceType()) {
1579 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001580 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1581 bool IsDecl =
1582 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1583 Diag(VD->getLocation(),
1584 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1585 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001586 continue;
1587 }
1588
Samuel Antaof8b50122015-07-13 22:54:53 +00001589 // Check if this is a TLS variable. If TLS is not being supported, produce
1590 // the corresponding diagnostic.
1591 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1592 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1593 getLangOpts().OpenMPUseTLS &&
1594 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001595 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1596 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001597 Diag(ILoc, diag::err_omp_var_thread_local)
1598 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001599 bool IsDecl =
1600 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1601 Diag(VD->getLocation(),
1602 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1603 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001604 continue;
1605 }
1606
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001607 // Check if initial value of threadprivate variable reference variable with
1608 // local storage (it is not supported by runtime).
1609 if (auto Init = VD->getAnyInitializer()) {
1610 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001611 if (Checker.Visit(Init))
1612 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001613 }
1614
Alexey Bataeved09d242014-05-28 05:53:51 +00001615 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001616 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001617 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1618 Context, SourceRange(Loc, Loc)));
1619 if (auto *ML = Context.getASTMutationListener())
1620 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001621 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001622 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001623 if (!Vars.empty()) {
1624 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1625 Vars);
1626 D->setAccess(AS_public);
1627 }
1628 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001629}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001630
Alexey Bataev7ff55242014-06-19 09:13:45 +00001631static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001632 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001633 bool IsLoopIterVar = false) {
1634 if (DVar.RefExpr) {
1635 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1636 << getOpenMPClauseName(DVar.CKind);
1637 return;
1638 }
1639 enum {
1640 PDSA_StaticMemberShared,
1641 PDSA_StaticLocalVarShared,
1642 PDSA_LoopIterVarPrivate,
1643 PDSA_LoopIterVarLinear,
1644 PDSA_LoopIterVarLastprivate,
1645 PDSA_ConstVarShared,
1646 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001647 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001648 PDSA_LocalVarPrivate,
1649 PDSA_Implicit
1650 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001651 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001652 auto ReportLoc = D->getLocation();
1653 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001654 if (IsLoopIterVar) {
1655 if (DVar.CKind == OMPC_private)
1656 Reason = PDSA_LoopIterVarPrivate;
1657 else if (DVar.CKind == OMPC_lastprivate)
1658 Reason = PDSA_LoopIterVarLastprivate;
1659 else
1660 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001661 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1662 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001663 Reason = PDSA_TaskVarFirstprivate;
1664 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001665 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001666 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001667 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001668 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001669 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001670 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001671 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001672 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001673 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001674 ReportHint = true;
1675 Reason = PDSA_LocalVarPrivate;
1676 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001677 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001678 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001679 << Reason << ReportHint
1680 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1681 } else if (DVar.ImplicitDSALoc.isValid()) {
1682 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1683 << getOpenMPClauseName(DVar.CKind);
1684 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001685}
1686
Alexey Bataev758e55e2013-09-06 18:03:48 +00001687namespace {
1688class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1689 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001690 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001691 bool ErrorFound;
1692 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001693 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001694 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001695
Alexey Bataev758e55e2013-09-06 18:03:48 +00001696public:
1697 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001698 if (E->isTypeDependent() || E->isValueDependent() ||
1699 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1700 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001701 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001702 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001703 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1704 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001705
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001706 auto DVar = Stack->getTopDSA(VD, false);
1707 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001708 if (DVar.RefExpr)
1709 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001710
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001711 auto ELoc = E->getExprLoc();
1712 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001713 // The default(none) clause requires that each variable that is referenced
1714 // in the construct, and does not have a predetermined data-sharing
1715 // attribute, must have its data-sharing attribute explicitly determined
1716 // by being listed in a data-sharing attribute clause.
1717 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001718 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001719 VarsWithInheritedDSA.count(VD) == 0) {
1720 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001721 return;
1722 }
1723
1724 // OpenMP [2.9.3.6, Restrictions, p.2]
1725 // A list item that appears in a reduction clause of the innermost
1726 // enclosing worksharing or parallel construct may not be accessed in an
1727 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001728 DVar = Stack->hasInnermostDSA(
1729 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1730 [](OpenMPDirectiveKind K) -> bool {
1731 return isOpenMPParallelDirective(K) ||
1732 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1733 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001734 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001735 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001736 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001737 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1738 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001739 return;
1740 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001741
1742 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001743 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001744 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1745 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001746 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001747 }
1748 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001749 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001750 if (E->isTypeDependent() || E->isValueDependent() ||
1751 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1752 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001753 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1754 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1755 auto DVar = Stack->getTopDSA(FD, false);
1756 // Check if the variable has explicit DSA set and stop analysis if it
1757 // so.
1758 if (DVar.RefExpr)
1759 return;
1760
1761 auto ELoc = E->getExprLoc();
1762 auto DKind = Stack->getCurrentDirective();
1763 // OpenMP [2.9.3.6, Restrictions, p.2]
1764 // A list item that appears in a reduction clause of the innermost
1765 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001766 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001767 DVar = Stack->hasInnermostDSA(
1768 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1769 [](OpenMPDirectiveKind K) -> bool {
1770 return isOpenMPParallelDirective(K) ||
1771 isOpenMPWorksharingDirective(K) ||
1772 isOpenMPTeamsDirective(K);
1773 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001774 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001775 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001776 ErrorFound = true;
1777 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1778 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1779 return;
1780 }
1781
1782 // Define implicit data-sharing attributes for task.
1783 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001784 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1785 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001786 ImplicitFirstprivate.push_back(E);
1787 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001788 } else
1789 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001790 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001791 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001792 for (auto *C : S->clauses()) {
1793 // Skip analysis of arguments of implicitly defined firstprivate clause
1794 // for task directives.
1795 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1796 for (auto *CC : C->children()) {
1797 if (CC)
1798 Visit(CC);
1799 }
1800 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001801 }
1802 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001803 for (auto *C : S->children()) {
1804 if (C && !isa<OMPExecutableDirective>(C))
1805 Visit(C);
1806 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001807 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001808
1809 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001810 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001811 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001812 return VarsWithInheritedDSA;
1813 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001814
Alexey Bataev7ff55242014-06-19 09:13:45 +00001815 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1816 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001817};
Alexey Bataeved09d242014-05-28 05:53:51 +00001818} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001819
Alexey Bataevbae9a792014-06-27 10:37:06 +00001820void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001821 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001822 case OMPD_parallel:
1823 case OMPD_parallel_for:
1824 case OMPD_parallel_for_simd:
1825 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001826 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001827 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001828 QualType KmpInt32PtrTy =
1829 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001830 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001831 std::make_pair(".global_tid.", KmpInt32PtrTy),
1832 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1833 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001834 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001835 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1836 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001837 break;
1838 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001839 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001840 case OMPD_target_parallel: {
1841 Sema::CapturedParamNameType ParamsTarget[] = {
1842 std::make_pair(StringRef(), QualType()) // __context with shared vars
1843 };
1844 // Start a captured region for 'target' with no implicit parameters.
1845 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1846 ParamsTarget);
1847 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1848 QualType KmpInt32PtrTy =
1849 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001850 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001851 std::make_pair(".global_tid.", KmpInt32PtrTy),
1852 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1853 std::make_pair(StringRef(), QualType()) // __context with shared vars
1854 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001855 // Start a captured region for 'teams' or 'parallel'. Both regions have
1856 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001857 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001858 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001859 break;
1860 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001861 case OMPD_simd:
1862 case OMPD_for:
1863 case OMPD_for_simd:
1864 case OMPD_sections:
1865 case OMPD_section:
1866 case OMPD_single:
1867 case OMPD_master:
1868 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001869 case OMPD_taskgroup:
1870 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001871 case OMPD_ordered:
1872 case OMPD_atomic:
1873 case OMPD_target_data:
1874 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001875 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001876 case OMPD_target_parallel_for_simd:
1877 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001878 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001879 std::make_pair(StringRef(), QualType()) // __context with shared vars
1880 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001881 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1882 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001883 break;
1884 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001885 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001886 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001887 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1888 FunctionProtoType::ExtProtoInfo EPI;
1889 EPI.Variadic = true;
1890 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001891 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001892 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001893 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1894 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1895 std::make_pair(".copy_fn.",
1896 Context.getPointerType(CopyFnType).withConst()),
1897 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001898 std::make_pair(StringRef(), QualType()) // __context with shared vars
1899 };
1900 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1901 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001902 // Mark this captured region as inlined, because we don't use outlined
1903 // function directly.
1904 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1905 AlwaysInlineAttr::CreateImplicit(
1906 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001907 break;
1908 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001909 case OMPD_taskloop:
1910 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001911 QualType KmpInt32Ty =
1912 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1913 QualType KmpUInt64Ty =
1914 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1915 QualType KmpInt64Ty =
1916 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1917 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1918 FunctionProtoType::ExtProtoInfo EPI;
1919 EPI.Variadic = true;
1920 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001921 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001922 std::make_pair(".global_tid.", KmpInt32Ty),
1923 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1924 std::make_pair(".privates.",
1925 Context.VoidPtrTy.withConst().withRestrict()),
1926 std::make_pair(
1927 ".copy_fn.",
1928 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1929 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1930 std::make_pair(".lb.", KmpUInt64Ty),
1931 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1932 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001933 std::make_pair(".reductions.",
1934 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001935 std::make_pair(StringRef(), QualType()) // __context with shared vars
1936 };
1937 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1938 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001939 // Mark this captured region as inlined, because we don't use outlined
1940 // function directly.
1941 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1942 AlwaysInlineAttr::CreateImplicit(
1943 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001944 break;
1945 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001946 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001947 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001948 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001949 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001950 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001951 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001952 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001953 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001954 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001955 case OMPD_target_teams_distribute_parallel_for_simd:
1956 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001957 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1958 QualType KmpInt32PtrTy =
1959 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1960 Sema::CapturedParamNameType Params[] = {
1961 std::make_pair(".global_tid.", KmpInt32PtrTy),
1962 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1963 std::make_pair(".previous.lb.", Context.getSizeType()),
1964 std::make_pair(".previous.ub.", Context.getSizeType()),
1965 std::make_pair(StringRef(), QualType()) // __context with shared vars
1966 };
1967 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1968 Params);
1969 break;
1970 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001971 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001972 case OMPD_taskyield:
1973 case OMPD_barrier:
1974 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001975 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001976 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001977 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001978 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001979 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001980 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001981 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001982 case OMPD_declare_target:
1983 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001984 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001985 llvm_unreachable("OpenMP Directive is not allowed");
1986 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001987 llvm_unreachable("Unknown OpenMP directive");
1988 }
1989}
1990
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001991int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1992 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1993 getOpenMPCaptureRegions(CaptureRegions, DKind);
1994 return CaptureRegions.size();
1995}
1996
Alexey Bataev3392d762016-02-16 11:18:12 +00001997static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001998 Expr *CaptureExpr, bool WithInit,
1999 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002000 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002001 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002002 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002003 QualType Ty = Init->getType();
2004 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2005 if (S.getLangOpts().CPlusPlus)
2006 Ty = C.getLValueReferenceType(Ty);
2007 else {
2008 Ty = C.getPointerType(Ty);
2009 ExprResult Res =
2010 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2011 if (!Res.isUsable())
2012 return nullptr;
2013 Init = Res.get();
2014 }
Alexey Bataev61205072016-03-02 04:57:40 +00002015 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002016 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002017 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2018 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002019 if (!WithInit)
2020 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002021 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002022 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002023 return CED;
2024}
2025
Alexey Bataev61205072016-03-02 04:57:40 +00002026static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2027 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002028 OMPCapturedExprDecl *CD;
2029 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2030 CD = cast<OMPCapturedExprDecl>(VD);
2031 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002032 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2033 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002034 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002035 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002036}
2037
Alexey Bataev5a3af132016-03-29 08:58:54 +00002038static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2039 if (!Ref) {
2040 auto *CD =
2041 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2042 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2043 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2044 CaptureExpr->getExprLoc());
2045 }
2046 ExprResult Res = Ref;
2047 if (!S.getLangOpts().CPlusPlus &&
2048 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2049 Ref->getType()->isPointerType())
2050 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2051 if (!Res.isUsable())
2052 return ExprError();
2053 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002054}
2055
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002056namespace {
2057// OpenMP directives parsed in this section are represented as a
2058// CapturedStatement with an associated statement. If a syntax error
2059// is detected during the parsing of the associated statement, the
2060// compiler must abort processing and close the CapturedStatement.
2061//
2062// Combined directives such as 'target parallel' have more than one
2063// nested CapturedStatements. This RAII ensures that we unwind out
2064// of all the nested CapturedStatements when an error is found.
2065class CaptureRegionUnwinderRAII {
2066private:
2067 Sema &S;
2068 bool &ErrorFound;
2069 OpenMPDirectiveKind DKind;
2070
2071public:
2072 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2073 OpenMPDirectiveKind DKind)
2074 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2075 ~CaptureRegionUnwinderRAII() {
2076 if (ErrorFound) {
2077 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2078 while (--ThisCaptureLevel >= 0)
2079 S.ActOnCapturedRegionError();
2080 }
2081 }
2082};
2083} // namespace
2084
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002085StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2086 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002087 bool ErrorFound = false;
2088 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2089 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002090 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002091 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002092 return StmtError();
2093 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002094
2095 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002096 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002097 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002098 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002099 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002100 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002101 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002102 Clause->getClauseKind() == OMPC_copyprivate ||
2103 (getLangOpts().OpenMPUseTLS &&
2104 getASTContext().getTargetInfo().isTLSSupported() &&
2105 Clause->getClauseKind() == OMPC_copyin)) {
2106 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002107 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002108 for (auto *VarRef : Clause->children()) {
2109 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002110 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002111 }
2112 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002113 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002114 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002115 if (auto *C = OMPClauseWithPreInit::get(Clause))
2116 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002117 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2118 if (auto *E = C->getPostUpdateExpr())
2119 MarkDeclarationsReferencedInExpr(E);
2120 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002121 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002122 if (Clause->getClauseKind() == OMPC_schedule)
2123 SC = cast<OMPScheduleClause>(Clause);
2124 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002125 OC = cast<OMPOrderedClause>(Clause);
2126 else if (Clause->getClauseKind() == OMPC_linear)
2127 LCs.push_back(cast<OMPLinearClause>(Clause));
2128 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002129 // OpenMP, 2.7.1 Loop Construct, Restrictions
2130 // The nonmonotonic modifier cannot be specified if an ordered clause is
2131 // specified.
2132 if (SC &&
2133 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2134 SC->getSecondScheduleModifier() ==
2135 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2136 OC) {
2137 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2138 ? SC->getFirstScheduleModifierLoc()
2139 : SC->getSecondScheduleModifierLoc(),
2140 diag::err_omp_schedule_nonmonotonic_ordered)
2141 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2142 ErrorFound = true;
2143 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002144 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2145 for (auto *C : LCs) {
2146 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2147 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2148 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002149 ErrorFound = true;
2150 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002151 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2152 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2153 OC->getNumForLoops()) {
2154 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2155 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2156 ErrorFound = true;
2157 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002158 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002159 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002160 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002161 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002162 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2163 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2164 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2165 // Mark all variables in private list clauses as used in inner region.
2166 // Required for proper codegen of combined directives.
2167 // TODO: add processing for other clauses.
2168 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2169 for (auto *C : PICs) {
2170 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2171 // Find the particular capture region for the clause if the
2172 // directive is a combined one with multiple capture regions.
2173 // If the directive is not a combined one, the capture region
2174 // associated with the clause is OMPD_unknown and is generated
2175 // only once.
2176 if (CaptureRegion == ThisCaptureRegion ||
2177 CaptureRegion == OMPD_unknown) {
2178 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2179 for (auto *D : DS->decls())
2180 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2181 }
2182 }
2183 }
2184 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002185 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002186 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002187 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002188}
2189
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002190static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2191 OpenMPDirectiveKind CancelRegion,
2192 SourceLocation StartLoc) {
2193 // CancelRegion is only needed for cancel and cancellation_point.
2194 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2195 return false;
2196
2197 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2198 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2199 return false;
2200
2201 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2202 << getOpenMPDirectiveName(CancelRegion);
2203 return true;
2204}
2205
2206static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002207 OpenMPDirectiveKind CurrentRegion,
2208 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002209 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002210 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002211 if (Stack->getCurScope()) {
2212 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002213 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002214 bool NestingProhibited = false;
2215 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002216 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002217 enum {
2218 NoRecommend,
2219 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002220 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002221 ShouldBeInTargetRegion,
2222 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002223 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002224 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002225 // OpenMP [2.16, Nesting of Regions]
2226 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002227 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002228 // An ordered construct with the simd clause is the only OpenMP
2229 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002230 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002231 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2232 // message.
2233 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2234 ? diag::err_omp_prohibited_region_simd
2235 : diag::warn_omp_nesting_simd);
2236 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002237 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002238 if (ParentRegion == OMPD_atomic) {
2239 // OpenMP [2.16, Nesting of Regions]
2240 // OpenMP constructs may not be nested inside an atomic region.
2241 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2242 return true;
2243 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002244 if (CurrentRegion == OMPD_section) {
2245 // OpenMP [2.7.2, sections Construct, Restrictions]
2246 // Orphaned section directives are prohibited. That is, the section
2247 // directives must appear within the sections construct and must not be
2248 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002249 if (ParentRegion != OMPD_sections &&
2250 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002251 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2252 << (ParentRegion != OMPD_unknown)
2253 << getOpenMPDirectiveName(ParentRegion);
2254 return true;
2255 }
2256 return false;
2257 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002258 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002259 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002260 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002261 if (ParentRegion == OMPD_unknown &&
2262 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002263 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002264 if (CurrentRegion == OMPD_cancellation_point ||
2265 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002266 // OpenMP [2.16, Nesting of Regions]
2267 // A cancellation point construct for which construct-type-clause is
2268 // taskgroup must be nested inside a task construct. A cancellation
2269 // point construct for which construct-type-clause is not taskgroup must
2270 // be closely nested inside an OpenMP construct that matches the type
2271 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002272 // A cancel construct for which construct-type-clause is taskgroup must be
2273 // nested inside a task construct. A cancel construct for which
2274 // construct-type-clause is not taskgroup must be closely nested inside an
2275 // OpenMP construct that matches the type specified in
2276 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002277 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002278 !((CancelRegion == OMPD_parallel &&
2279 (ParentRegion == OMPD_parallel ||
2280 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002281 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002282 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2283 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002284 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2285 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002286 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2287 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002288 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002289 // OpenMP [2.16, Nesting of Regions]
2290 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002291 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002292 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002293 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002294 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2295 // OpenMP [2.16, Nesting of Regions]
2296 // A critical region may not be nested (closely or otherwise) inside a
2297 // critical region with the same name. Note that this restriction is not
2298 // sufficient to prevent deadlock.
2299 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002300 bool DeadLock = Stack->hasDirective(
2301 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2302 const DeclarationNameInfo &DNI,
2303 SourceLocation Loc) -> bool {
2304 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2305 PreviousCriticalLoc = Loc;
2306 return true;
2307 } else
2308 return false;
2309 },
2310 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002311 if (DeadLock) {
2312 SemaRef.Diag(StartLoc,
2313 diag::err_omp_prohibited_region_critical_same_name)
2314 << CurrentName.getName();
2315 if (PreviousCriticalLoc.isValid())
2316 SemaRef.Diag(PreviousCriticalLoc,
2317 diag::note_omp_previous_critical_region);
2318 return true;
2319 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002320 } else if (CurrentRegion == OMPD_barrier) {
2321 // OpenMP [2.16, Nesting of Regions]
2322 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002323 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002324 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2325 isOpenMPTaskingDirective(ParentRegion) ||
2326 ParentRegion == OMPD_master ||
2327 ParentRegion == OMPD_critical ||
2328 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002329 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002330 !isOpenMPParallelDirective(CurrentRegion) &&
2331 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002332 // OpenMP [2.16, Nesting of Regions]
2333 // A worksharing region may not be closely nested inside a worksharing,
2334 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002335 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2336 isOpenMPTaskingDirective(ParentRegion) ||
2337 ParentRegion == OMPD_master ||
2338 ParentRegion == OMPD_critical ||
2339 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002340 Recommend = ShouldBeInParallelRegion;
2341 } else if (CurrentRegion == OMPD_ordered) {
2342 // OpenMP [2.16, Nesting of Regions]
2343 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002344 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002345 // An ordered region must be closely nested inside a loop region (or
2346 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002347 // OpenMP [2.8.1,simd Construct, Restrictions]
2348 // An ordered construct with the simd clause is the only OpenMP construct
2349 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002350 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002351 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002352 !(isOpenMPSimdDirective(ParentRegion) ||
2353 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002354 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002355 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002356 // OpenMP [2.16, Nesting of Regions]
2357 // If specified, a teams construct must be contained within a target
2358 // construct.
2359 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002360 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002361 Recommend = ShouldBeInTargetRegion;
2362 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2363 }
Kelvin Libf594a52016-12-17 05:48:59 +00002364 if (!NestingProhibited &&
2365 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2366 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2367 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002368 // OpenMP [2.16, Nesting of Regions]
2369 // distribute, parallel, parallel sections, parallel workshare, and the
2370 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2371 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002372 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2373 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002374 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002375 }
David Majnemer9d168222016-08-05 17:44:54 +00002376 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002377 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002378 // OpenMP 4.5 [2.17 Nesting of Regions]
2379 // The region associated with the distribute construct must be strictly
2380 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002381 NestingProhibited =
2382 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002383 Recommend = ShouldBeInTeamsRegion;
2384 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002385 if (!NestingProhibited &&
2386 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2387 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2388 // OpenMP 4.5 [2.17 Nesting of Regions]
2389 // If a target, target update, target data, target enter data, or
2390 // target exit data construct is encountered during execution of a
2391 // target region, the behavior is unspecified.
2392 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002393 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2394 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002395 if (isOpenMPTargetExecutionDirective(K)) {
2396 OffendingRegion = K;
2397 return true;
2398 } else
2399 return false;
2400 },
2401 false /* don't skip top directive */);
2402 CloseNesting = false;
2403 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002404 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002405 if (OrphanSeen) {
2406 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2407 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2408 } else {
2409 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2410 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2411 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2412 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002413 return true;
2414 }
2415 }
2416 return false;
2417}
2418
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002419static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2420 ArrayRef<OMPClause *> Clauses,
2421 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2422 bool ErrorFound = false;
2423 unsigned NamedModifiersNumber = 0;
2424 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2425 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002426 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002427 for (const auto *C : Clauses) {
2428 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2429 // At most one if clause without a directive-name-modifier can appear on
2430 // the directive.
2431 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2432 if (FoundNameModifiers[CurNM]) {
2433 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2434 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2435 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2436 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002437 } else if (CurNM != OMPD_unknown) {
2438 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002439 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002440 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002441 FoundNameModifiers[CurNM] = IC;
2442 if (CurNM == OMPD_unknown)
2443 continue;
2444 // Check if the specified name modifier is allowed for the current
2445 // directive.
2446 // At most one if clause with the particular directive-name-modifier can
2447 // appear on the directive.
2448 bool MatchFound = false;
2449 for (auto NM : AllowedNameModifiers) {
2450 if (CurNM == NM) {
2451 MatchFound = true;
2452 break;
2453 }
2454 }
2455 if (!MatchFound) {
2456 S.Diag(IC->getNameModifierLoc(),
2457 diag::err_omp_wrong_if_directive_name_modifier)
2458 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2459 ErrorFound = true;
2460 }
2461 }
2462 }
2463 // If any if clause on the directive includes a directive-name-modifier then
2464 // all if clauses on the directive must include a directive-name-modifier.
2465 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2466 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2467 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2468 diag::err_omp_no_more_if_clause);
2469 } else {
2470 std::string Values;
2471 std::string Sep(", ");
2472 unsigned AllowedCnt = 0;
2473 unsigned TotalAllowedNum =
2474 AllowedNameModifiers.size() - NamedModifiersNumber;
2475 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2476 ++Cnt) {
2477 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2478 if (!FoundNameModifiers[NM]) {
2479 Values += "'";
2480 Values += getOpenMPDirectiveName(NM);
2481 Values += "'";
2482 if (AllowedCnt + 2 == TotalAllowedNum)
2483 Values += " or ";
2484 else if (AllowedCnt + 1 != TotalAllowedNum)
2485 Values += Sep;
2486 ++AllowedCnt;
2487 }
2488 }
2489 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2490 diag::err_omp_unnamed_if_clause)
2491 << (TotalAllowedNum > 1) << Values;
2492 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002493 for (auto Loc : NameModifierLoc) {
2494 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2495 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002496 ErrorFound = true;
2497 }
2498 return ErrorFound;
2499}
2500
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002501StmtResult Sema::ActOnOpenMPExecutableDirective(
2502 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2503 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2504 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002505 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002506 // First check CancelRegion which is then used in checkNestingOfRegions.
2507 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2508 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002509 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002510 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002511
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002512 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002513 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002514 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002515 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002516 if (AStmt) {
2517 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2518
2519 // Check default data sharing attributes for referenced variables.
2520 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002521 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2522 Stmt *S = AStmt;
2523 while (--ThisCaptureLevel >= 0)
2524 S = cast<CapturedStmt>(S)->getCapturedStmt();
2525 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002526 if (DSAChecker.isErrorFound())
2527 return StmtError();
2528 // Generate list of implicitly defined firstprivate variables.
2529 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002530
2531 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2532 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2533 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2534 SourceLocation(), SourceLocation())) {
2535 ClausesWithImplicit.push_back(Implicit);
2536 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2537 DSAChecker.getImplicitFirstprivate().size();
2538 } else
2539 ErrorFound = true;
2540 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002541 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002542
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002543 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002544 switch (Kind) {
2545 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002546 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2547 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002548 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002549 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002550 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002551 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2552 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002553 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002554 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002555 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2556 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002557 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002558 case OMPD_for_simd:
2559 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2560 EndLoc, VarsWithInheritedDSA);
2561 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002562 case OMPD_sections:
2563 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2564 EndLoc);
2565 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002566 case OMPD_section:
2567 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002568 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002569 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2570 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002571 case OMPD_single:
2572 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2573 EndLoc);
2574 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002575 case OMPD_master:
2576 assert(ClausesWithImplicit.empty() &&
2577 "No clauses are allowed for 'omp master' directive");
2578 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2579 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002580 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002581 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2582 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002583 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002584 case OMPD_parallel_for:
2585 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2586 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002587 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002588 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002589 case OMPD_parallel_for_simd:
2590 Res = ActOnOpenMPParallelForSimdDirective(
2591 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002592 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002593 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002594 case OMPD_parallel_sections:
2595 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2596 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002597 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002598 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002599 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002600 Res =
2601 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002602 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002603 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002604 case OMPD_taskyield:
2605 assert(ClausesWithImplicit.empty() &&
2606 "No clauses are allowed for 'omp taskyield' directive");
2607 assert(AStmt == nullptr &&
2608 "No associated statement allowed for 'omp taskyield' directive");
2609 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2610 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002611 case OMPD_barrier:
2612 assert(ClausesWithImplicit.empty() &&
2613 "No clauses are allowed for 'omp barrier' directive");
2614 assert(AStmt == nullptr &&
2615 "No associated statement allowed for 'omp barrier' directive");
2616 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2617 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002618 case OMPD_taskwait:
2619 assert(ClausesWithImplicit.empty() &&
2620 "No clauses are allowed for 'omp taskwait' directive");
2621 assert(AStmt == nullptr &&
2622 "No associated statement allowed for 'omp taskwait' directive");
2623 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2624 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002625 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002626 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2627 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002628 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002629 case OMPD_flush:
2630 assert(AStmt == nullptr &&
2631 "No associated statement allowed for 'omp flush' directive");
2632 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2633 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002634 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002635 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2636 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002637 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002638 case OMPD_atomic:
2639 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2640 EndLoc);
2641 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002642 case OMPD_teams:
2643 Res =
2644 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2645 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002646 case OMPD_target:
2647 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2648 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002649 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002650 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002651 case OMPD_target_parallel:
2652 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2653 StartLoc, EndLoc);
2654 AllowedNameModifiers.push_back(OMPD_target);
2655 AllowedNameModifiers.push_back(OMPD_parallel);
2656 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002657 case OMPD_target_parallel_for:
2658 Res = ActOnOpenMPTargetParallelForDirective(
2659 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2660 AllowedNameModifiers.push_back(OMPD_target);
2661 AllowedNameModifiers.push_back(OMPD_parallel);
2662 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002663 case OMPD_cancellation_point:
2664 assert(ClausesWithImplicit.empty() &&
2665 "No clauses are allowed for 'omp cancellation point' directive");
2666 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2667 "cancellation point' directive");
2668 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2669 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002670 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002671 assert(AStmt == nullptr &&
2672 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002673 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2674 CancelRegion);
2675 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002676 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002677 case OMPD_target_data:
2678 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2679 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002680 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002681 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002682 case OMPD_target_enter_data:
2683 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2684 EndLoc);
2685 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2686 break;
Samuel Antao72590762016-01-19 20:04:50 +00002687 case OMPD_target_exit_data:
2688 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2689 EndLoc);
2690 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2691 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002692 case OMPD_taskloop:
2693 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2694 EndLoc, VarsWithInheritedDSA);
2695 AllowedNameModifiers.push_back(OMPD_taskloop);
2696 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002697 case OMPD_taskloop_simd:
2698 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2699 EndLoc, VarsWithInheritedDSA);
2700 AllowedNameModifiers.push_back(OMPD_taskloop);
2701 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002702 case OMPD_distribute:
2703 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2704 EndLoc, VarsWithInheritedDSA);
2705 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002706 case OMPD_target_update:
2707 assert(!AStmt && "Statement is not allowed for target update");
2708 Res =
2709 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2710 AllowedNameModifiers.push_back(OMPD_target_update);
2711 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002712 case OMPD_distribute_parallel_for:
2713 Res = ActOnOpenMPDistributeParallelForDirective(
2714 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2715 AllowedNameModifiers.push_back(OMPD_parallel);
2716 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002717 case OMPD_distribute_parallel_for_simd:
2718 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2719 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2720 AllowedNameModifiers.push_back(OMPD_parallel);
2721 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002722 case OMPD_distribute_simd:
2723 Res = ActOnOpenMPDistributeSimdDirective(
2724 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2725 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002726 case OMPD_target_parallel_for_simd:
2727 Res = ActOnOpenMPTargetParallelForSimdDirective(
2728 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2729 AllowedNameModifiers.push_back(OMPD_target);
2730 AllowedNameModifiers.push_back(OMPD_parallel);
2731 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002732 case OMPD_target_simd:
2733 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2734 EndLoc, VarsWithInheritedDSA);
2735 AllowedNameModifiers.push_back(OMPD_target);
2736 break;
Kelvin Li02532872016-08-05 14:37:37 +00002737 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002738 Res = ActOnOpenMPTeamsDistributeDirective(
2739 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002740 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002741 case OMPD_teams_distribute_simd:
2742 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2743 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2744 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002745 case OMPD_teams_distribute_parallel_for_simd:
2746 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2747 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2748 AllowedNameModifiers.push_back(OMPD_parallel);
2749 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002750 case OMPD_teams_distribute_parallel_for:
2751 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2752 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2753 AllowedNameModifiers.push_back(OMPD_parallel);
2754 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002755 case OMPD_target_teams:
2756 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2757 EndLoc);
2758 AllowedNameModifiers.push_back(OMPD_target);
2759 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002760 case OMPD_target_teams_distribute:
2761 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2762 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2763 AllowedNameModifiers.push_back(OMPD_target);
2764 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002765 case OMPD_target_teams_distribute_parallel_for:
2766 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2767 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2768 AllowedNameModifiers.push_back(OMPD_target);
2769 AllowedNameModifiers.push_back(OMPD_parallel);
2770 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002771 case OMPD_target_teams_distribute_parallel_for_simd:
2772 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2773 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2774 AllowedNameModifiers.push_back(OMPD_target);
2775 AllowedNameModifiers.push_back(OMPD_parallel);
2776 break;
Kelvin Lida681182017-01-10 18:08:18 +00002777 case OMPD_target_teams_distribute_simd:
2778 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2779 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2780 AllowedNameModifiers.push_back(OMPD_target);
2781 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002782 case OMPD_declare_target:
2783 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002784 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002785 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002786 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002787 llvm_unreachable("OpenMP Directive is not allowed");
2788 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002789 llvm_unreachable("Unknown OpenMP directive");
2790 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002791
Alexey Bataev4acb8592014-07-07 13:01:15 +00002792 for (auto P : VarsWithInheritedDSA) {
2793 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2794 << P.first << P.second->getSourceRange();
2795 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002796 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2797
2798 if (!AllowedNameModifiers.empty())
2799 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2800 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002801
Alexey Bataeved09d242014-05-28 05:53:51 +00002802 if (ErrorFound)
2803 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002804 return Res;
2805}
2806
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002807Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2808 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002809 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002810 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2811 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002812 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002813 assert(Linears.size() == LinModifiers.size());
2814 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002815 if (!DG || DG.get().isNull())
2816 return DeclGroupPtrTy();
2817
2818 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002819 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002820 return DG;
2821 }
2822 auto *ADecl = DG.get().getSingleDecl();
2823 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2824 ADecl = FTD->getTemplatedDecl();
2825
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002826 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2827 if (!FD) {
2828 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002829 return DeclGroupPtrTy();
2830 }
2831
Alexey Bataev2af33e32016-04-07 12:45:37 +00002832 // OpenMP [2.8.2, declare simd construct, Description]
2833 // The parameter of the simdlen clause must be a constant positive integer
2834 // expression.
2835 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002836 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002837 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002838 // OpenMP [2.8.2, declare simd construct, Description]
2839 // The special this pointer can be used as if was one of the arguments to the
2840 // function in any of the linear, aligned, or uniform clauses.
2841 // The uniform clause declares one or more arguments to have an invariant
2842 // value for all concurrent invocations of the function in the execution of a
2843 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002844 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2845 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002846 for (auto *E : Uniforms) {
2847 E = E->IgnoreParenImpCasts();
2848 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2849 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2850 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2851 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002852 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2853 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002854 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002855 }
2856 if (isa<CXXThisExpr>(E)) {
2857 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002858 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002859 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002860 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2861 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002862 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002863 // OpenMP [2.8.2, declare simd construct, Description]
2864 // The aligned clause declares that the object to which each list item points
2865 // is aligned to the number of bytes expressed in the optional parameter of
2866 // the aligned clause.
2867 // The special this pointer can be used as if was one of the arguments to the
2868 // function in any of the linear, aligned, or uniform clauses.
2869 // The type of list items appearing in the aligned clause must be array,
2870 // pointer, reference to array, or reference to pointer.
2871 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2872 Expr *AlignedThis = nullptr;
2873 for (auto *E : Aligneds) {
2874 E = E->IgnoreParenImpCasts();
2875 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2876 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2877 auto *CanonPVD = PVD->getCanonicalDecl();
2878 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2879 FD->getParamDecl(PVD->getFunctionScopeIndex())
2880 ->getCanonicalDecl() == CanonPVD) {
2881 // OpenMP [2.8.1, simd construct, Restrictions]
2882 // A list-item cannot appear in more than one aligned clause.
2883 if (AlignedArgs.count(CanonPVD) > 0) {
2884 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2885 << 1 << E->getSourceRange();
2886 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2887 diag::note_omp_explicit_dsa)
2888 << getOpenMPClauseName(OMPC_aligned);
2889 continue;
2890 }
2891 AlignedArgs[CanonPVD] = E;
2892 QualType QTy = PVD->getType()
2893 .getNonReferenceType()
2894 .getUnqualifiedType()
2895 .getCanonicalType();
2896 const Type *Ty = QTy.getTypePtrOrNull();
2897 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2898 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2899 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2900 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2901 }
2902 continue;
2903 }
2904 }
2905 if (isa<CXXThisExpr>(E)) {
2906 if (AlignedThis) {
2907 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2908 << 2 << E->getSourceRange();
2909 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2910 << getOpenMPClauseName(OMPC_aligned);
2911 }
2912 AlignedThis = E;
2913 continue;
2914 }
2915 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2916 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2917 }
2918 // The optional parameter of the aligned clause, alignment, must be a constant
2919 // positive integer expression. If no optional parameter is specified,
2920 // implementation-defined default alignments for SIMD instructions on the
2921 // target platforms are assumed.
2922 SmallVector<Expr *, 4> NewAligns;
2923 for (auto *E : Alignments) {
2924 ExprResult Align;
2925 if (E)
2926 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2927 NewAligns.push_back(Align.get());
2928 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002929 // OpenMP [2.8.2, declare simd construct, Description]
2930 // The linear clause declares one or more list items to be private to a SIMD
2931 // lane and to have a linear relationship with respect to the iteration space
2932 // of a loop.
2933 // The special this pointer can be used as if was one of the arguments to the
2934 // function in any of the linear, aligned, or uniform clauses.
2935 // When a linear-step expression is specified in a linear clause it must be
2936 // either a constant integer expression or an integer-typed parameter that is
2937 // specified in a uniform clause on the directive.
2938 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2939 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2940 auto MI = LinModifiers.begin();
2941 for (auto *E : Linears) {
2942 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2943 ++MI;
2944 E = E->IgnoreParenImpCasts();
2945 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2946 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2947 auto *CanonPVD = PVD->getCanonicalDecl();
2948 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2949 FD->getParamDecl(PVD->getFunctionScopeIndex())
2950 ->getCanonicalDecl() == CanonPVD) {
2951 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2952 // A list-item cannot appear in more than one linear clause.
2953 if (LinearArgs.count(CanonPVD) > 0) {
2954 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2955 << getOpenMPClauseName(OMPC_linear)
2956 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2957 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2958 diag::note_omp_explicit_dsa)
2959 << getOpenMPClauseName(OMPC_linear);
2960 continue;
2961 }
2962 // Each argument can appear in at most one uniform or linear clause.
2963 if (UniformedArgs.count(CanonPVD) > 0) {
2964 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2965 << getOpenMPClauseName(OMPC_linear)
2966 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2967 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2968 diag::note_omp_explicit_dsa)
2969 << getOpenMPClauseName(OMPC_uniform);
2970 continue;
2971 }
2972 LinearArgs[CanonPVD] = E;
2973 if (E->isValueDependent() || E->isTypeDependent() ||
2974 E->isInstantiationDependent() ||
2975 E->containsUnexpandedParameterPack())
2976 continue;
2977 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2978 PVD->getOriginalType());
2979 continue;
2980 }
2981 }
2982 if (isa<CXXThisExpr>(E)) {
2983 if (UniformedLinearThis) {
2984 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2985 << getOpenMPClauseName(OMPC_linear)
2986 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2987 << E->getSourceRange();
2988 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2989 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2990 : OMPC_linear);
2991 continue;
2992 }
2993 UniformedLinearThis = E;
2994 if (E->isValueDependent() || E->isTypeDependent() ||
2995 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2996 continue;
2997 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2998 E->getType());
2999 continue;
3000 }
3001 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3002 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3003 }
3004 Expr *Step = nullptr;
3005 Expr *NewStep = nullptr;
3006 SmallVector<Expr *, 4> NewSteps;
3007 for (auto *E : Steps) {
3008 // Skip the same step expression, it was checked already.
3009 if (Step == E || !E) {
3010 NewSteps.push_back(E ? NewStep : nullptr);
3011 continue;
3012 }
3013 Step = E;
3014 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3015 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3016 auto *CanonPVD = PVD->getCanonicalDecl();
3017 if (UniformedArgs.count(CanonPVD) == 0) {
3018 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3019 << Step->getSourceRange();
3020 } else if (E->isValueDependent() || E->isTypeDependent() ||
3021 E->isInstantiationDependent() ||
3022 E->containsUnexpandedParameterPack() ||
3023 CanonPVD->getType()->hasIntegerRepresentation())
3024 NewSteps.push_back(Step);
3025 else {
3026 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3027 << Step->getSourceRange();
3028 }
3029 continue;
3030 }
3031 NewStep = Step;
3032 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3033 !Step->isInstantiationDependent() &&
3034 !Step->containsUnexpandedParameterPack()) {
3035 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3036 .get();
3037 if (NewStep)
3038 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3039 }
3040 NewSteps.push_back(NewStep);
3041 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003042 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3043 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003044 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003045 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3046 const_cast<Expr **>(Linears.data()), Linears.size(),
3047 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3048 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003049 ADecl->addAttr(NewAttr);
3050 return ConvertDeclToDeclGroup(ADecl);
3051}
3052
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003053StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3054 Stmt *AStmt,
3055 SourceLocation StartLoc,
3056 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003057 if (!AStmt)
3058 return StmtError();
3059
Alexey Bataev9959db52014-05-06 10:08:46 +00003060 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3061 // 1.2.2 OpenMP Language Terminology
3062 // Structured block - An executable statement with a single entry at the
3063 // top and a single exit at the bottom.
3064 // The point of exit cannot be a branch out of the structured block.
3065 // longjmp() and throw() must not violate the entry/exit criteria.
3066 CS->getCapturedDecl()->setNothrow();
3067
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003068 getCurFunction()->setHasBranchProtectedScope();
3069
Alexey Bataev25e5b442015-09-15 12:52:43 +00003070 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3071 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003072}
3073
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003074namespace {
3075/// \brief Helper class for checking canonical form of the OpenMP loops and
3076/// extracting iteration space of each loop in the loop nest, that will be used
3077/// for IR generation.
3078class OpenMPIterationSpaceChecker {
3079 /// \brief Reference to Sema.
3080 Sema &SemaRef;
3081 /// \brief A location for diagnostics (when there is no some better location).
3082 SourceLocation DefaultLoc;
3083 /// \brief A location for diagnostics (when increment is not compatible).
3084 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003085 /// \brief A source location for referring to loop init later.
3086 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003087 /// \brief A source location for referring to condition later.
3088 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003089 /// \brief A source location for referring to increment later.
3090 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003092 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003093 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003094 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003095 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003096 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003097 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003098 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003099 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003100 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003101 /// \brief This flag is true when condition is one of:
3102 /// Var < UB
3103 /// Var <= UB
3104 /// UB > Var
3105 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003106 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003107 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003108 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003109 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003110 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111
3112public:
3113 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003114 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115 /// \brief Check init-expr for canonical loop form and save loop counter
3116 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003117 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003118 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3119 /// for less/greater and for strict/non-strict comparison.
3120 bool CheckCond(Expr *S);
3121 /// \brief Check incr-expr for canonical loop form and return true if it
3122 /// does not conform, otherwise save loop step (#Step).
3123 bool CheckInc(Expr *S);
3124 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003125 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003126 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003127 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003128 /// \brief Source range of the loop init.
3129 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3130 /// \brief Source range of the loop condition.
3131 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3132 /// \brief Source range of the loop increment.
3133 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3134 /// \brief True if the step should be subtracted.
3135 bool ShouldSubtractStep() const { return SubtractStep; }
3136 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003137 Expr *
3138 BuildNumIterations(Scope *S, const bool LimitedType,
3139 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003140 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003141 Expr *BuildPreCond(Scope *S, Expr *Cond,
3142 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003143 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003144 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3145 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003146 /// \brief Build reference expression to the private counter be used for
3147 /// codegen.
3148 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003149 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003150 Expr *BuildCounterInit() const;
3151 /// \brief Build step of the counter be used for codegen.
3152 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003153 /// \brief Return true if any expression is dependent.
3154 bool Dependent() const;
3155
3156private:
3157 /// \brief Check the right-hand side of an assignment in the increment
3158 /// expression.
3159 bool CheckIncRHS(Expr *RHS);
3160 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003161 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003162 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003163 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003164 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003165 /// \brief Helper to set loop increment.
3166 bool SetStep(Expr *NewStep, bool Subtract);
3167};
3168
3169bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003170 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003171 assert(!LB && !UB && !Step);
3172 return false;
3173 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 return LCDecl->getType()->isDependentType() ||
3175 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3176 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003177}
3178
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003179bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3180 Expr *NewLCRefExpr,
3181 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003182 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003183 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003184 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003185 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003187 LCDecl = getCanonicalDecl(NewLCDecl);
3188 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003189 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3190 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003191 if ((Ctor->isCopyOrMoveConstructor() ||
3192 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3193 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003194 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003195 LB = NewLB;
3196 return false;
3197}
3198
3199bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003200 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003201 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003202 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3203 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003204 if (!NewUB)
3205 return true;
3206 UB = NewUB;
3207 TestIsLessOp = LessOp;
3208 TestIsStrictOp = StrictOp;
3209 ConditionSrcRange = SR;
3210 ConditionLoc = SL;
3211 return false;
3212}
3213
3214bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3215 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003216 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003217 if (!NewStep)
3218 return true;
3219 if (!NewStep->isValueDependent()) {
3220 // Check that the step is integer expression.
3221 SourceLocation StepLoc = NewStep->getLocStart();
3222 ExprResult Val =
3223 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3224 if (Val.isInvalid())
3225 return true;
3226 NewStep = Val.get();
3227
3228 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3229 // If test-expr is of form var relational-op b and relational-op is < or
3230 // <= then incr-expr must cause var to increase on each iteration of the
3231 // loop. If test-expr is of form var relational-op b and relational-op is
3232 // > or >= then incr-expr must cause var to decrease on each iteration of
3233 // the loop.
3234 // If test-expr is of form b relational-op var and relational-op is < or
3235 // <= then incr-expr must cause var to decrease on each iteration of the
3236 // loop. If test-expr is of form b relational-op var and relational-op is
3237 // > or >= then incr-expr must cause var to increase on each iteration of
3238 // the loop.
3239 llvm::APSInt Result;
3240 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3241 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3242 bool IsConstNeg =
3243 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003244 bool IsConstPos =
3245 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003246 bool IsConstZero = IsConstant && !Result.getBoolValue();
3247 if (UB && (IsConstZero ||
3248 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003249 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003250 SemaRef.Diag(NewStep->getExprLoc(),
3251 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003252 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003253 SemaRef.Diag(ConditionLoc,
3254 diag::note_omp_loop_cond_requres_compatible_incr)
3255 << TestIsLessOp << ConditionSrcRange;
3256 return true;
3257 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003258 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003259 NewStep =
3260 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3261 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003262 Subtract = !Subtract;
3263 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003264 }
3265
3266 Step = NewStep;
3267 SubtractStep = Subtract;
3268 return false;
3269}
3270
Alexey Bataev9c821032015-04-30 04:23:23 +00003271bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003272 // Check init-expr for canonical loop form and save loop counter
3273 // variable - #Var and its initialization value - #LB.
3274 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3275 // var = lb
3276 // integer-type var = lb
3277 // random-access-iterator-type var = lb
3278 // pointer-type var = lb
3279 //
3280 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003281 if (EmitDiags) {
3282 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3283 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003284 return true;
3285 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003286 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3287 if (!ExprTemp->cleanupsHaveSideEffects())
3288 S = ExprTemp->getSubExpr();
3289
Alexander Musmana5f070a2014-10-01 06:03:56 +00003290 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003291 if (Expr *E = dyn_cast<Expr>(S))
3292 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003293 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003294 if (BO->getOpcode() == BO_Assign) {
3295 auto *LHS = BO->getLHS()->IgnoreParens();
3296 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3297 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3298 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3299 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3300 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3301 }
3302 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3303 if (ME->isArrow() &&
3304 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3305 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3306 }
3307 }
David Majnemer9d168222016-08-05 17:44:54 +00003308 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003309 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003310 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003311 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003312 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003313 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003314 SemaRef.Diag(S->getLocStart(),
3315 diag::ext_omp_loop_not_canonical_init)
3316 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003317 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003318 }
3319 }
3320 }
David Majnemer9d168222016-08-05 17:44:54 +00003321 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003322 if (CE->getOperator() == OO_Equal) {
3323 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003324 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003325 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3326 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3327 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3328 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3329 }
3330 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3331 if (ME->isArrow() &&
3332 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3333 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3334 }
3335 }
3336 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003337
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003338 if (Dependent() || SemaRef.CurContext->isDependentContext())
3339 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003340 if (EmitDiags) {
3341 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3342 << S->getSourceRange();
3343 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003344 return true;
3345}
3346
Alexey Bataev23b69422014-06-18 07:08:49 +00003347/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003348/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003349static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003350 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003351 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003352 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003353 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3354 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003355 if ((Ctor->isCopyOrMoveConstructor() ||
3356 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3357 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003358 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003359 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003360 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003361 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003362 }
3363 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3364 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3365 return getCanonicalDecl(ME->getMemberDecl());
3366 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003367}
3368
3369bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3370 // Check test-expr for canonical form, save upper-bound UB, flags for
3371 // less/greater and for strict/non-strict comparison.
3372 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3373 // var relational-op b
3374 // b relational-op var
3375 //
3376 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003377 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003378 return true;
3379 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003380 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003381 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003382 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003383 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003384 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003385 return SetUB(BO->getRHS(),
3386 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3387 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3388 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003389 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003390 return SetUB(BO->getLHS(),
3391 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3392 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3393 BO->getSourceRange(), BO->getOperatorLoc());
3394 }
David Majnemer9d168222016-08-05 17:44:54 +00003395 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003396 if (CE->getNumArgs() == 2) {
3397 auto Op = CE->getOperator();
3398 switch (Op) {
3399 case OO_Greater:
3400 case OO_GreaterEqual:
3401 case OO_Less:
3402 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003403 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003404 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3405 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3406 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003407 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003408 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3409 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3410 CE->getOperatorLoc());
3411 break;
3412 default:
3413 break;
3414 }
3415 }
3416 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003417 if (Dependent() || SemaRef.CurContext->isDependentContext())
3418 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003419 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003420 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003421 return true;
3422}
3423
3424bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3425 // RHS of canonical loop form increment can be:
3426 // var + incr
3427 // incr + var
3428 // var - incr
3429 //
3430 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003431 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003432 if (BO->isAdditiveOp()) {
3433 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003434 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003435 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003436 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003437 return SetStep(BO->getLHS(), false);
3438 }
David Majnemer9d168222016-08-05 17:44:54 +00003439 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003440 bool IsAdd = CE->getOperator() == OO_Plus;
3441 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003442 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003443 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003444 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003445 return SetStep(CE->getArg(0), false);
3446 }
3447 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448 if (Dependent() || SemaRef.CurContext->isDependentContext())
3449 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003450 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003451 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452 return true;
3453}
3454
3455bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3456 // Check incr-expr for canonical loop form and return true if it
3457 // does not conform.
3458 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3459 // ++var
3460 // var++
3461 // --var
3462 // var--
3463 // var += incr
3464 // var -= incr
3465 // var = var + incr
3466 // var = incr + var
3467 // var = var - incr
3468 //
3469 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003470 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003471 return true;
3472 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003473 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3474 if (!ExprTemp->cleanupsHaveSideEffects())
3475 S = ExprTemp->getSubExpr();
3476
Alexander Musmana5f070a2014-10-01 06:03:56 +00003477 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003478 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003479 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003480 if (UO->isIncrementDecrementOp() &&
3481 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003482 return SetStep(SemaRef
3483 .ActOnIntegerConstant(UO->getLocStart(),
3484 (UO->isDecrementOp() ? -1 : 1))
3485 .get(),
3486 false);
3487 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003488 switch (BO->getOpcode()) {
3489 case BO_AddAssign:
3490 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003491 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003492 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3493 break;
3494 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003495 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003496 return CheckIncRHS(BO->getRHS());
3497 break;
3498 default:
3499 break;
3500 }
David Majnemer9d168222016-08-05 17:44:54 +00003501 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003502 switch (CE->getOperator()) {
3503 case OO_PlusPlus:
3504 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003505 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003506 return SetStep(SemaRef
3507 .ActOnIntegerConstant(
3508 CE->getLocStart(),
3509 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3510 .get(),
3511 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003512 break;
3513 case OO_PlusEqual:
3514 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003515 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003516 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3517 break;
3518 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003519 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003520 return CheckIncRHS(CE->getArg(1));
3521 break;
3522 default:
3523 break;
3524 }
3525 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003526 if (Dependent() || SemaRef.CurContext->isDependentContext())
3527 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003528 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003529 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003530 return true;
3531}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003532
Alexey Bataev5a3af132016-03-29 08:58:54 +00003533static ExprResult
3534tryBuildCapture(Sema &SemaRef, Expr *Capture,
3535 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003536 if (SemaRef.CurContext->isDependentContext())
3537 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003538 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3539 return SemaRef.PerformImplicitConversion(
3540 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3541 /*AllowExplicit=*/true);
3542 auto I = Captures.find(Capture);
3543 if (I != Captures.end())
3544 return buildCapture(SemaRef, Capture, I->second);
3545 DeclRefExpr *Ref = nullptr;
3546 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3547 Captures[Capture] = Ref;
3548 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003549}
3550
Alexander Musmana5f070a2014-10-01 06:03:56 +00003551/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003552Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3553 Scope *S, const bool LimitedType,
3554 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003555 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003556 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003557 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003558 SemaRef.getLangOpts().CPlusPlus) {
3559 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003560 auto *UBExpr = TestIsLessOp ? UB : LB;
3561 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003562 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3563 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003564 if (!Upper || !Lower)
3565 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003566
3567 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3568
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003569 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003570 // BuildBinOp already emitted error, this one is to point user to upper
3571 // and lower bound, and to tell what is passed to 'operator-'.
3572 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3573 << Upper->getSourceRange() << Lower->getSourceRange();
3574 return nullptr;
3575 }
3576 }
3577
3578 if (!Diff.isUsable())
3579 return nullptr;
3580
3581 // Upper - Lower [- 1]
3582 if (TestIsStrictOp)
3583 Diff = SemaRef.BuildBinOp(
3584 S, DefaultLoc, BO_Sub, Diff.get(),
3585 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3586 if (!Diff.isUsable())
3587 return nullptr;
3588
3589 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003590 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3591 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003592 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003593 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003594 if (!Diff.isUsable())
3595 return nullptr;
3596
3597 // Parentheses (for dumping/debugging purposes only).
3598 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3599 if (!Diff.isUsable())
3600 return nullptr;
3601
3602 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003603 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003604 if (!Diff.isUsable())
3605 return nullptr;
3606
Alexander Musman174b3ca2014-10-06 11:16:29 +00003607 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003608 QualType Type = Diff.get()->getType();
3609 auto &C = SemaRef.Context;
3610 bool UseVarType = VarType->hasIntegerRepresentation() &&
3611 C.getTypeSize(Type) > C.getTypeSize(VarType);
3612 if (!Type->isIntegerType() || UseVarType) {
3613 unsigned NewSize =
3614 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3615 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3616 : Type->hasSignedIntegerRepresentation();
3617 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003618 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3619 Diff = SemaRef.PerformImplicitConversion(
3620 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3621 if (!Diff.isUsable())
3622 return nullptr;
3623 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003624 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003625 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003626 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3627 if (NewSize != C.getTypeSize(Type)) {
3628 if (NewSize < C.getTypeSize(Type)) {
3629 assert(NewSize == 64 && "incorrect loop var size");
3630 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3631 << InitSrcRange << ConditionSrcRange;
3632 }
3633 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003634 NewSize, Type->hasSignedIntegerRepresentation() ||
3635 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003636 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3637 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3638 Sema::AA_Converting, true);
3639 if (!Diff.isUsable())
3640 return nullptr;
3641 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003642 }
3643 }
3644
Alexander Musmana5f070a2014-10-01 06:03:56 +00003645 return Diff.get();
3646}
3647
Alexey Bataev5a3af132016-03-29 08:58:54 +00003648Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3649 Scope *S, Expr *Cond,
3650 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003651 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3652 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3653 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003654
Alexey Bataev5a3af132016-03-29 08:58:54 +00003655 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3656 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3657 if (!NewLB.isUsable() || !NewUB.isUsable())
3658 return nullptr;
3659
Alexey Bataev62dbb972015-04-22 11:59:37 +00003660 auto CondExpr = SemaRef.BuildBinOp(
3661 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3662 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003663 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003664 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003665 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3666 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003667 CondExpr = SemaRef.PerformImplicitConversion(
3668 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3669 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003670 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003671 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3672 // Otherwise use original loop conditon and evaluate it in runtime.
3673 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3674}
3675
Alexander Musmana5f070a2014-10-01 06:03:56 +00003676/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003677DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003678 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003679 auto *VD = dyn_cast<VarDecl>(LCDecl);
3680 if (!VD) {
3681 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3682 auto *Ref = buildDeclRefExpr(
3683 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003684 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3685 // If the loop control decl is explicitly marked as private, do not mark it
3686 // as captured again.
3687 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3688 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003689 return Ref;
3690 }
3691 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003692 DefaultLoc);
3693}
3694
3695Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 if (LCDecl && !LCDecl->isInvalidDecl()) {
3697 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003698 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003699 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3700 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003701 if (PrivateVar->isInvalidDecl())
3702 return nullptr;
3703 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3704 }
3705 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003706}
3707
Samuel Antao4c8035b2016-12-12 18:00:20 +00003708/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003709Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3710
3711/// \brief Build step of the counter be used for codegen.
3712Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3713
3714/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003715struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003716 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003717 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003718 /// \brief This expression calculates the number of iterations in the loop.
3719 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003720 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003721 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003722 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003723 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003724 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003725 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003726 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003727 /// \brief This is step for the #CounterVar used to generate its update:
3728 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003729 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003730 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003731 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003732 /// \brief Source range of the loop init.
3733 SourceRange InitSrcRange;
3734 /// \brief Source range of the loop condition.
3735 SourceRange CondSrcRange;
3736 /// \brief Source range of the loop increment.
3737 SourceRange IncSrcRange;
3738};
3739
Alexey Bataev23b69422014-06-18 07:08:49 +00003740} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003741
Alexey Bataev9c821032015-04-30 04:23:23 +00003742void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3743 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3744 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003745 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3746 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003747 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3748 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003749 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3750 if (auto *D = ISC.GetLoopDecl()) {
3751 auto *VD = dyn_cast<VarDecl>(D);
3752 if (!VD) {
3753 if (auto *Private = IsOpenMPCapturedDecl(D))
3754 VD = Private;
3755 else {
3756 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3757 /*WithInit=*/false);
3758 VD = cast<VarDecl>(Ref->getDecl());
3759 }
3760 }
3761 DSAStack->addLoopControlVariable(D, VD);
3762 }
3763 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003764 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003765 }
3766}
3767
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003768/// \brief Called on a for stmt to check and extract its iteration space
3769/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003770static bool CheckOpenMPIterationSpace(
3771 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3772 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003773 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003774 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003775 LoopIterationSpace &ResultIterSpace,
3776 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 // OpenMP [2.6, Canonical Loop Form]
3778 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003779 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003780 if (!For) {
3781 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003782 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3783 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3784 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3785 if (NestedLoopCount > 1) {
3786 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3787 SemaRef.Diag(DSA.getConstructLoc(),
3788 diag::note_omp_collapse_ordered_expr)
3789 << 2 << CollapseLoopCountExpr->getSourceRange()
3790 << OrderedLoopCountExpr->getSourceRange();
3791 else if (CollapseLoopCountExpr)
3792 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3793 diag::note_omp_collapse_ordered_expr)
3794 << 0 << CollapseLoopCountExpr->getSourceRange();
3795 else
3796 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3797 diag::note_omp_collapse_ordered_expr)
3798 << 1 << OrderedLoopCountExpr->getSourceRange();
3799 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003800 return true;
3801 }
3802 assert(For->getBody());
3803
3804 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3805
3806 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003807 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003808 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003809 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003810
3811 bool HasErrors = false;
3812
3813 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003814 if (auto *LCDecl = ISC.GetLoopDecl()) {
3815 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003816
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003817 // OpenMP [2.6, Canonical Loop Form]
3818 // Var is one of the following:
3819 // A variable of signed or unsigned integer type.
3820 // For C++, a variable of a random access iterator type.
3821 // For C, a variable of a pointer type.
3822 auto VarType = LCDecl->getType().getNonReferenceType();
3823 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3824 !VarType->isPointerType() &&
3825 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3826 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3827 << SemaRef.getLangOpts().CPlusPlus;
3828 HasErrors = true;
3829 }
3830
3831 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3832 // a Construct
3833 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3834 // parallel for construct is (are) private.
3835 // The loop iteration variable in the associated for-loop of a simd
3836 // construct with just one associated for-loop is linear with a
3837 // constant-linear-step that is the increment of the associated for-loop.
3838 // Exclude loop var from the list of variables with implicitly defined data
3839 // sharing attributes.
3840 VarsWithImplicitDSA.erase(LCDecl);
3841
3842 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3843 // in a Construct, C/C++].
3844 // The loop iteration variable in the associated for-loop of a simd
3845 // construct with just one associated for-loop may be listed in a linear
3846 // clause with a constant-linear-step that is the increment of the
3847 // associated for-loop.
3848 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3849 // parallel for construct may be listed in a private or lastprivate clause.
3850 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3851 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3852 // declared in the loop and it is predetermined as a private.
3853 auto PredeterminedCKind =
3854 isOpenMPSimdDirective(DKind)
3855 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3856 : OMPC_private;
3857 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3858 DVar.CKind != PredeterminedCKind) ||
3859 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3860 isOpenMPDistributeDirective(DKind)) &&
3861 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3862 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3863 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3864 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3865 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3866 << getOpenMPClauseName(PredeterminedCKind);
3867 if (DVar.RefExpr == nullptr)
3868 DVar.CKind = PredeterminedCKind;
3869 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3870 HasErrors = true;
3871 } else if (LoopDeclRefExpr != nullptr) {
3872 // Make the loop iteration variable private (for worksharing constructs),
3873 // linear (for simd directives with the only one associated loop) or
3874 // lastprivate (for simd directives with several collapsed or ordered
3875 // loops).
3876 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003877 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3878 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003879 /*FromParent=*/false);
3880 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3881 }
3882
3883 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3884
3885 // Check test-expr.
3886 HasErrors |= ISC.CheckCond(For->getCond());
3887
3888 // Check incr-expr.
3889 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003890 }
3891
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003893 return HasErrors;
3894
Alexander Musmana5f070a2014-10-01 06:03:56 +00003895 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003896 ResultIterSpace.PreCond =
3897 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003898 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003899 DSA.getCurScope(),
3900 (isOpenMPWorksharingDirective(DKind) ||
3901 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3902 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003903 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003904 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003905 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3906 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3907 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3908 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3909 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3910 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3911
Alexey Bataev62dbb972015-04-22 11:59:37 +00003912 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3913 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003914 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003915 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003916 ResultIterSpace.CounterInit == nullptr ||
3917 ResultIterSpace.CounterStep == nullptr);
3918
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003919 return HasErrors;
3920}
3921
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003922/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003923static ExprResult
3924BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3925 ExprResult Start,
3926 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003927 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003928 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3929 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003930 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003931 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003932 VarRef.get()->getType())) {
3933 NewStart = SemaRef.PerformImplicitConversion(
3934 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3935 /*AllowExplicit=*/true);
3936 if (!NewStart.isUsable())
3937 return ExprError();
3938 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003939
3940 auto Init =
3941 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3942 return Init;
3943}
3944
Alexander Musmana5f070a2014-10-01 06:03:56 +00003945/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003946static ExprResult
3947BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3948 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3949 ExprResult Step, bool Subtract,
3950 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003951 // Add parentheses (for debugging purposes only).
3952 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3953 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3954 !Step.isUsable())
3955 return ExprError();
3956
Alexey Bataev5a3af132016-03-29 08:58:54 +00003957 ExprResult NewStep = Step;
3958 if (Captures)
3959 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003960 if (NewStep.isInvalid())
3961 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003962 ExprResult Update =
3963 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003964 if (!Update.isUsable())
3965 return ExprError();
3966
Alexey Bataevc0214e02016-02-16 12:13:49 +00003967 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3968 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003969 ExprResult NewStart = Start;
3970 if (Captures)
3971 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003972 if (NewStart.isInvalid())
3973 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003974
Alexey Bataevc0214e02016-02-16 12:13:49 +00003975 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3976 ExprResult SavedUpdate = Update;
3977 ExprResult UpdateVal;
3978 if (VarRef.get()->getType()->isOverloadableType() ||
3979 NewStart.get()->getType()->isOverloadableType() ||
3980 Update.get()->getType()->isOverloadableType()) {
3981 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3982 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3983 Update =
3984 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3985 if (Update.isUsable()) {
3986 UpdateVal =
3987 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3988 VarRef.get(), SavedUpdate.get());
3989 if (UpdateVal.isUsable()) {
3990 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3991 UpdateVal.get());
3992 }
3993 }
3994 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3995 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003996
Alexey Bataevc0214e02016-02-16 12:13:49 +00003997 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3998 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3999 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4000 NewStart.get(), SavedUpdate.get());
4001 if (!Update.isUsable())
4002 return ExprError();
4003
Alexey Bataev11481f52016-02-17 10:29:05 +00004004 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4005 VarRef.get()->getType())) {
4006 Update = SemaRef.PerformImplicitConversion(
4007 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4008 if (!Update.isUsable())
4009 return ExprError();
4010 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004011
4012 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4013 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004014 return Update;
4015}
4016
4017/// \brief Convert integer expression \a E to make it have at least \a Bits
4018/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004019static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004020 if (E == nullptr)
4021 return ExprError();
4022 auto &C = SemaRef.Context;
4023 QualType OldType = E->getType();
4024 unsigned HasBits = C.getTypeSize(OldType);
4025 if (HasBits >= Bits)
4026 return ExprResult(E);
4027 // OK to convert to signed, because new type has more bits than old.
4028 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4029 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4030 true);
4031}
4032
4033/// \brief Check if the given expression \a E is a constant integer that fits
4034/// into \a Bits bits.
4035static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4036 if (E == nullptr)
4037 return false;
4038 llvm::APSInt Result;
4039 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4040 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4041 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004042}
4043
Alexey Bataev5a3af132016-03-29 08:58:54 +00004044/// Build preinits statement for the given declarations.
4045static Stmt *buildPreInits(ASTContext &Context,
4046 SmallVectorImpl<Decl *> &PreInits) {
4047 if (!PreInits.empty()) {
4048 return new (Context) DeclStmt(
4049 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4050 SourceLocation(), SourceLocation());
4051 }
4052 return nullptr;
4053}
4054
4055/// Build preinits statement for the given declarations.
4056static Stmt *buildPreInits(ASTContext &Context,
4057 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4058 if (!Captures.empty()) {
4059 SmallVector<Decl *, 16> PreInits;
4060 for (auto &Pair : Captures)
4061 PreInits.push_back(Pair.second->getDecl());
4062 return buildPreInits(Context, PreInits);
4063 }
4064 return nullptr;
4065}
4066
4067/// Build postupdate expression for the given list of postupdates expressions.
4068static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4069 Expr *PostUpdate = nullptr;
4070 if (!PostUpdates.empty()) {
4071 for (auto *E : PostUpdates) {
4072 Expr *ConvE = S.BuildCStyleCastExpr(
4073 E->getExprLoc(),
4074 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4075 E->getExprLoc(), E)
4076 .get();
4077 PostUpdate = PostUpdate
4078 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4079 PostUpdate, ConvE)
4080 .get()
4081 : ConvE;
4082 }
4083 }
4084 return PostUpdate;
4085}
4086
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004087/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004088/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4089/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004090static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004091CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4092 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4093 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004094 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004095 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004096 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004097 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004098 // Found 'collapse' clause - calculate collapse number.
4099 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004100 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004101 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004102 }
4103 if (OrderedLoopCountExpr) {
4104 // Found 'ordered' clause - calculate collapse number.
4105 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004106 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4107 if (Result.getLimitedValue() < NestedLoopCount) {
4108 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4109 diag::err_omp_wrong_ordered_loop_count)
4110 << OrderedLoopCountExpr->getSourceRange();
4111 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4112 diag::note_collapse_loop_count)
4113 << CollapseLoopCountExpr->getSourceRange();
4114 }
4115 NestedLoopCount = Result.getLimitedValue();
4116 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004117 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004118 // This is helper routine for loop directives (e.g., 'for', 'simd',
4119 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004120 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004121 SmallVector<LoopIterationSpace, 4> IterSpaces;
4122 IterSpaces.resize(NestedLoopCount);
4123 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004124 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004125 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004126 NestedLoopCount, CollapseLoopCountExpr,
4127 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004128 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004129 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004130 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004131 // OpenMP [2.8.1, simd construct, Restrictions]
4132 // All loops associated with the construct must be perfectly nested; that
4133 // is, there must be no intervening code nor any OpenMP directive between
4134 // any two loops.
4135 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004136 }
4137
Alexander Musmana5f070a2014-10-01 06:03:56 +00004138 Built.clear(/* size */ NestedLoopCount);
4139
4140 if (SemaRef.CurContext->isDependentContext())
4141 return NestedLoopCount;
4142
4143 // An example of what is generated for the following code:
4144 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004145 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004146 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004147 // for (k = 0; k < NK; ++k)
4148 // for (j = J0; j < NJ; j+=2) {
4149 // <loop body>
4150 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004151 //
4152 // We generate the code below.
4153 // Note: the loop body may be outlined in CodeGen.
4154 // Note: some counters may be C++ classes, operator- is used to find number of
4155 // iterations and operator+= to calculate counter value.
4156 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4157 // or i64 is currently supported).
4158 //
4159 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4160 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4161 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4162 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4163 // // similar updates for vars in clauses (e.g. 'linear')
4164 // <loop body (using local i and j)>
4165 // }
4166 // i = NI; // assign final values of counters
4167 // j = NJ;
4168 //
4169
4170 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4171 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004172 // Precondition tests if there is at least one iteration (all conditions are
4173 // true).
4174 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004175 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004176 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004177 32 /* Bits */, SemaRef
4178 .PerformImplicitConversion(
4179 N0->IgnoreImpCasts(), N0->getType(),
4180 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004181 .get(),
4182 SemaRef);
4183 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004184 64 /* Bits */, SemaRef
4185 .PerformImplicitConversion(
4186 N0->IgnoreImpCasts(), N0->getType(),
4187 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004188 .get(),
4189 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004190
4191 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4192 return NestedLoopCount;
4193
4194 auto &C = SemaRef.Context;
4195 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4196
4197 Scope *CurScope = DSA.getCurScope();
4198 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004199 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004200 PreCond =
4201 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4202 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004203 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004204 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004205 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004206 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4207 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004208 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004209 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004210 SemaRef
4211 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4212 Sema::AA_Converting,
4213 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004214 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004215 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004216 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004217 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004218 SemaRef
4219 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4220 Sema::AA_Converting,
4221 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004222 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004223 }
4224
4225 // Choose either the 32-bit or 64-bit version.
4226 ExprResult LastIteration = LastIteration64;
4227 if (LastIteration32.isUsable() &&
4228 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4229 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4230 FitsInto(
4231 32 /* Bits */,
4232 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4233 LastIteration64.get(), SemaRef)))
4234 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004235 QualType VType = LastIteration.get()->getType();
4236 QualType RealVType = VType;
4237 QualType StrideVType = VType;
4238 if (isOpenMPTaskLoopDirective(DKind)) {
4239 VType =
4240 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4241 StrideVType =
4242 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4243 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004244
4245 if (!LastIteration.isUsable())
4246 return 0;
4247
4248 // Save the number of iterations.
4249 ExprResult NumIterations = LastIteration;
4250 {
4251 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004252 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4253 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004254 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4255 if (!LastIteration.isUsable())
4256 return 0;
4257 }
4258
4259 // Calculate the last iteration number beforehand instead of doing this on
4260 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4261 llvm::APSInt Result;
4262 bool IsConstant =
4263 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4264 ExprResult CalcLastIteration;
4265 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004266 ExprResult SaveRef =
4267 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004268 LastIteration = SaveRef;
4269
4270 // Prepare SaveRef + 1.
4271 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004272 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004273 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4274 if (!NumIterations.isUsable())
4275 return 0;
4276 }
4277
4278 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4279
David Majnemer9d168222016-08-05 17:44:54 +00004280 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004281 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004282 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4283 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004284 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004285 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4286 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004287 SemaRef.AddInitializerToDecl(LBDecl,
4288 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4289 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004290
4291 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004292 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4293 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004294 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004295 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004296
4297 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4298 // This will be used to implement clause 'lastprivate'.
4299 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004300 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4301 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004302 SemaRef.AddInitializerToDecl(ILDecl,
4303 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4304 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004305
4306 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004307 VarDecl *STDecl =
4308 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4309 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004310 SemaRef.AddInitializerToDecl(STDecl,
4311 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4312 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004313
4314 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004315 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004316 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4317 UB.get(), LastIteration.get());
4318 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4319 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4320 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4321 CondOp.get());
4322 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004323
4324 // If we have a combined directive that combines 'distribute', 'for' or
4325 // 'simd' we need to be able to access the bounds of the schedule of the
4326 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4327 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4328 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004329
Carlo Bertolliffafe102017-04-20 00:39:39 +00004330 // Lower bound variable, initialized with zero.
4331 VarDecl *CombLBDecl =
4332 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4333 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4334 SemaRef.AddInitializerToDecl(
4335 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4336 /*DirectInit*/ false);
4337
4338 // Upper bound variable, initialized with last iteration number.
4339 VarDecl *CombUBDecl =
4340 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4341 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4342 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4343 /*DirectInit*/ false);
4344
4345 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4346 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4347 ExprResult CombCondOp =
4348 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4349 LastIteration.get(), CombUB.get());
4350 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4351 CombCondOp.get());
4352 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4353
4354 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004355 // We expect to have at least 2 more parameters than the 'parallel'
4356 // directive does - the lower and upper bounds of the previous schedule.
4357 assert(CD->getNumParams() >= 4 &&
4358 "Unexpected number of parameters in loop combined directive");
4359
4360 // Set the proper type for the bounds given what we learned from the
4361 // enclosed loops.
4362 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4363 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4364
4365 // Previous lower and upper bounds are obtained from the region
4366 // parameters.
4367 PrevLB =
4368 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4369 PrevUB =
4370 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4371 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004372 }
4373
4374 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004375 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004376 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004377 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004378 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4379 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004380 Expr *RHS =
4381 (isOpenMPWorksharingDirective(DKind) ||
4382 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4383 ? LB.get()
4384 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004385 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4386 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004387
4388 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4389 Expr *CombRHS =
4390 (isOpenMPWorksharingDirective(DKind) ||
4391 isOpenMPTaskLoopDirective(DKind) ||
4392 isOpenMPDistributeDirective(DKind))
4393 ? CombLB.get()
4394 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4395 CombInit =
4396 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4397 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4398 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004399 }
4400
Alexander Musmanc6388682014-12-15 07:07:06 +00004401 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004402 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004403 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004404 (isOpenMPWorksharingDirective(DKind) ||
4405 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004406 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4407 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4408 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004409 ExprResult CombCond;
4410 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4411 CombCond =
4412 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4413 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004414 // Loop increment (IV = IV + 1)
4415 SourceLocation IncLoc;
4416 ExprResult Inc =
4417 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4418 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4419 if (!Inc.isUsable())
4420 return 0;
4421 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004422 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4423 if (!Inc.isUsable())
4424 return 0;
4425
4426 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4427 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004428 // In combined construct, add combined version that use CombLB and CombUB
4429 // base variables for the update
4430 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004431 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4432 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004433 // LB + ST
4434 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4435 if (!NextLB.isUsable())
4436 return 0;
4437 // LB = LB + ST
4438 NextLB =
4439 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4440 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4441 if (!NextLB.isUsable())
4442 return 0;
4443 // UB + ST
4444 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4445 if (!NextUB.isUsable())
4446 return 0;
4447 // UB = UB + ST
4448 NextUB =
4449 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4450 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4451 if (!NextUB.isUsable())
4452 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004453 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4454 CombNextLB =
4455 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4456 if (!NextLB.isUsable())
4457 return 0;
4458 // LB = LB + ST
4459 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4460 CombNextLB.get());
4461 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4462 if (!CombNextLB.isUsable())
4463 return 0;
4464 // UB + ST
4465 CombNextUB =
4466 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4467 if (!CombNextUB.isUsable())
4468 return 0;
4469 // UB = UB + ST
4470 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4471 CombNextUB.get());
4472 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4473 if (!CombNextUB.isUsable())
4474 return 0;
4475 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004476 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004477
Carlo Bertolliffafe102017-04-20 00:39:39 +00004478 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004479 // directive with for as IV = IV + ST; ensure upper bound expression based
4480 // on PrevUB instead of NumIterations - used to implement 'for' when found
4481 // in combination with 'distribute', like in 'distribute parallel for'
4482 SourceLocation DistIncLoc;
4483 ExprResult DistCond, DistInc, PrevEUB;
4484 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4485 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4486 assert(DistCond.isUsable() && "distribute cond expr was not built");
4487
4488 DistInc =
4489 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4490 assert(DistInc.isUsable() && "distribute inc expr was not built");
4491 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4492 DistInc.get());
4493 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4494 assert(DistInc.isUsable() && "distribute inc expr was not built");
4495
4496 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4497 // construct
4498 SourceLocation DistEUBLoc;
4499 ExprResult IsUBGreater =
4500 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4501 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4502 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4503 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4504 CondOp.get());
4505 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4506 }
4507
Alexander Musmana5f070a2014-10-01 06:03:56 +00004508 // Build updates and final values of the loop counters.
4509 bool HasErrors = false;
4510 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004511 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004512 Built.Updates.resize(NestedLoopCount);
4513 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004514 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004515 {
4516 ExprResult Div;
4517 // Go from inner nested loop to outer.
4518 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4519 LoopIterationSpace &IS = IterSpaces[Cnt];
4520 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4521 // Build: Iter = (IV / Div) % IS.NumIters
4522 // where Div is product of previous iterations' IS.NumIters.
4523 ExprResult Iter;
4524 if (Div.isUsable()) {
4525 Iter =
4526 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4527 } else {
4528 Iter = IV;
4529 assert((Cnt == (int)NestedLoopCount - 1) &&
4530 "unusable div expected on first iteration only");
4531 }
4532
4533 if (Cnt != 0 && Iter.isUsable())
4534 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4535 IS.NumIterations);
4536 if (!Iter.isUsable()) {
4537 HasErrors = true;
4538 break;
4539 }
4540
Alexey Bataev39f915b82015-05-08 10:41:21 +00004541 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004542 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4543 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4544 IS.CounterVar->getExprLoc(),
4545 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004546 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004547 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004548 if (!Init.isUsable()) {
4549 HasErrors = true;
4550 break;
4551 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004552 ExprResult Update = BuildCounterUpdate(
4553 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4554 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004555 if (!Update.isUsable()) {
4556 HasErrors = true;
4557 break;
4558 }
4559
4560 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4561 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004562 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004563 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004564 if (!Final.isUsable()) {
4565 HasErrors = true;
4566 break;
4567 }
4568
4569 // Build Div for the next iteration: Div <- Div * IS.NumIters
4570 if (Cnt != 0) {
4571 if (Div.isUnset())
4572 Div = IS.NumIterations;
4573 else
4574 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4575 IS.NumIterations);
4576
4577 // Add parentheses (for debugging purposes only).
4578 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004579 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004580 if (!Div.isUsable()) {
4581 HasErrors = true;
4582 break;
4583 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004584 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004585 }
4586 if (!Update.isUsable() || !Final.isUsable()) {
4587 HasErrors = true;
4588 break;
4589 }
4590 // Save results
4591 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004592 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004593 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004594 Built.Updates[Cnt] = Update.get();
4595 Built.Finals[Cnt] = Final.get();
4596 }
4597 }
4598
4599 if (HasErrors)
4600 return 0;
4601
4602 // Save results
4603 Built.IterationVarRef = IV.get();
4604 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004605 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004606 Built.CalcLastIteration =
4607 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004608 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004609 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004610 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004611 Built.Init = Init.get();
4612 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004613 Built.LB = LB.get();
4614 Built.UB = UB.get();
4615 Built.IL = IL.get();
4616 Built.ST = ST.get();
4617 Built.EUB = EUB.get();
4618 Built.NLB = NextLB.get();
4619 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004620 Built.PrevLB = PrevLB.get();
4621 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004622 Built.DistInc = DistInc.get();
4623 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004624 Built.DistCombinedFields.LB = CombLB.get();
4625 Built.DistCombinedFields.UB = CombUB.get();
4626 Built.DistCombinedFields.EUB = CombEUB.get();
4627 Built.DistCombinedFields.Init = CombInit.get();
4628 Built.DistCombinedFields.Cond = CombCond.get();
4629 Built.DistCombinedFields.NLB = CombNextLB.get();
4630 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004631
Alexey Bataev8b427062016-05-25 12:36:08 +00004632 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4633 // Fill data for doacross depend clauses.
4634 for (auto Pair : DSA.getDoacrossDependClauses()) {
4635 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4636 Pair.first->setCounterValue(CounterVal);
4637 else {
4638 if (NestedLoopCount != Pair.second.size() ||
4639 NestedLoopCount != LoopMultipliers.size() + 1) {
4640 // Erroneous case - clause has some problems.
4641 Pair.first->setCounterValue(CounterVal);
4642 continue;
4643 }
4644 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4645 auto I = Pair.second.rbegin();
4646 auto IS = IterSpaces.rbegin();
4647 auto ILM = LoopMultipliers.rbegin();
4648 Expr *UpCounterVal = CounterVal;
4649 Expr *Multiplier = nullptr;
4650 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4651 if (I->first) {
4652 assert(IS->CounterStep);
4653 Expr *NormalizedOffset =
4654 SemaRef
4655 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4656 I->first, IS->CounterStep)
4657 .get();
4658 if (Multiplier) {
4659 NormalizedOffset =
4660 SemaRef
4661 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4662 NormalizedOffset, Multiplier)
4663 .get();
4664 }
4665 assert(I->second == OO_Plus || I->second == OO_Minus);
4666 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004667 UpCounterVal = SemaRef
4668 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4669 UpCounterVal, NormalizedOffset)
4670 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004671 }
4672 Multiplier = *ILM;
4673 ++I;
4674 ++IS;
4675 ++ILM;
4676 }
4677 Pair.first->setCounterValue(UpCounterVal);
4678 }
4679 }
4680
Alexey Bataevabfc0692014-06-25 06:52:00 +00004681 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004682}
4683
Alexey Bataev10e775f2015-07-30 11:36:16 +00004684static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004685 auto CollapseClauses =
4686 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4687 if (CollapseClauses.begin() != CollapseClauses.end())
4688 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004689 return nullptr;
4690}
4691
Alexey Bataev10e775f2015-07-30 11:36:16 +00004692static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004693 auto OrderedClauses =
4694 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4695 if (OrderedClauses.begin() != OrderedClauses.end())
4696 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004697 return nullptr;
4698}
4699
Kelvin Lic5609492016-07-15 04:39:07 +00004700static bool checkSimdlenSafelenSpecified(Sema &S,
4701 const ArrayRef<OMPClause *> Clauses) {
4702 OMPSafelenClause *Safelen = nullptr;
4703 OMPSimdlenClause *Simdlen = nullptr;
4704
4705 for (auto *Clause : Clauses) {
4706 if (Clause->getClauseKind() == OMPC_safelen)
4707 Safelen = cast<OMPSafelenClause>(Clause);
4708 else if (Clause->getClauseKind() == OMPC_simdlen)
4709 Simdlen = cast<OMPSimdlenClause>(Clause);
4710 if (Safelen && Simdlen)
4711 break;
4712 }
4713
4714 if (Simdlen && Safelen) {
4715 llvm::APSInt SimdlenRes, SafelenRes;
4716 auto SimdlenLength = Simdlen->getSimdlen();
4717 auto SafelenLength = Safelen->getSafelen();
4718 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4719 SimdlenLength->isInstantiationDependent() ||
4720 SimdlenLength->containsUnexpandedParameterPack())
4721 return false;
4722 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4723 SafelenLength->isInstantiationDependent() ||
4724 SafelenLength->containsUnexpandedParameterPack())
4725 return false;
4726 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4727 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4728 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4729 // If both simdlen and safelen clauses are specified, the value of the
4730 // simdlen parameter must be less than or equal to the value of the safelen
4731 // parameter.
4732 if (SimdlenRes > SafelenRes) {
4733 S.Diag(SimdlenLength->getExprLoc(),
4734 diag::err_omp_wrong_simdlen_safelen_values)
4735 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4736 return true;
4737 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004738 }
4739 return false;
4740}
4741
Alexey Bataev4acb8592014-07-07 13:01:15 +00004742StmtResult Sema::ActOnOpenMPSimdDirective(
4743 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4744 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004745 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004746 if (!AStmt)
4747 return StmtError();
4748
4749 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004750 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004751 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4752 // define the nested loops number.
4753 unsigned NestedLoopCount = CheckOpenMPLoop(
4754 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4755 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004756 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004757 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004758
Alexander Musmana5f070a2014-10-01 06:03:56 +00004759 assert((CurContext->isDependentContext() || B.builtAll()) &&
4760 "omp simd loop exprs were not built");
4761
Alexander Musman3276a272015-03-21 10:12:56 +00004762 if (!CurContext->isDependentContext()) {
4763 // Finalize the clauses that need pre-built expressions for CodeGen.
4764 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004765 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004766 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004767 B.NumIterations, *this, CurScope,
4768 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004769 return StmtError();
4770 }
4771 }
4772
Kelvin Lic5609492016-07-15 04:39:07 +00004773 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004774 return StmtError();
4775
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004776 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004777 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4778 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004779}
4780
Alexey Bataev4acb8592014-07-07 13:01:15 +00004781StmtResult Sema::ActOnOpenMPForDirective(
4782 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4783 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004784 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004785 if (!AStmt)
4786 return StmtError();
4787
4788 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004789 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004790 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4791 // define the nested loops number.
4792 unsigned NestedLoopCount = CheckOpenMPLoop(
4793 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4794 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004795 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004796 return StmtError();
4797
Alexander Musmana5f070a2014-10-01 06:03:56 +00004798 assert((CurContext->isDependentContext() || B.builtAll()) &&
4799 "omp for loop exprs were not built");
4800
Alexey Bataev54acd402015-08-04 11:18:19 +00004801 if (!CurContext->isDependentContext()) {
4802 // Finalize the clauses that need pre-built expressions for CodeGen.
4803 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004804 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004805 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004806 B.NumIterations, *this, CurScope,
4807 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004808 return StmtError();
4809 }
4810 }
4811
Alexey Bataevf29276e2014-06-18 04:14:57 +00004812 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004813 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004814 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004815}
4816
Alexander Musmanf82886e2014-09-18 05:12:34 +00004817StmtResult Sema::ActOnOpenMPForSimdDirective(
4818 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4819 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004820 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004821 if (!AStmt)
4822 return StmtError();
4823
4824 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004825 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004826 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4827 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004828 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004829 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4830 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4831 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004832 if (NestedLoopCount == 0)
4833 return StmtError();
4834
Alexander Musmanc6388682014-12-15 07:07:06 +00004835 assert((CurContext->isDependentContext() || B.builtAll()) &&
4836 "omp for simd loop exprs were not built");
4837
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004838 if (!CurContext->isDependentContext()) {
4839 // Finalize the clauses that need pre-built expressions for CodeGen.
4840 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004841 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004842 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004843 B.NumIterations, *this, CurScope,
4844 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004845 return StmtError();
4846 }
4847 }
4848
Kelvin Lic5609492016-07-15 04:39:07 +00004849 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004850 return StmtError();
4851
Alexander Musmanf82886e2014-09-18 05:12:34 +00004852 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004853 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4854 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004855}
4856
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004857StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4858 Stmt *AStmt,
4859 SourceLocation StartLoc,
4860 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004861 if (!AStmt)
4862 return StmtError();
4863
4864 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004865 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004866 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004867 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004868 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004869 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004870 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004871 return StmtError();
4872 // All associated statements must be '#pragma omp section' except for
4873 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004874 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004875 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4876 if (SectionStmt)
4877 Diag(SectionStmt->getLocStart(),
4878 diag::err_omp_sections_substmt_not_section);
4879 return StmtError();
4880 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004881 cast<OMPSectionDirective>(SectionStmt)
4882 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004883 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004884 } else {
4885 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4886 return StmtError();
4887 }
4888
4889 getCurFunction()->setHasBranchProtectedScope();
4890
Alexey Bataev25e5b442015-09-15 12:52:43 +00004891 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4892 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004893}
4894
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004895StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4896 SourceLocation StartLoc,
4897 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004898 if (!AStmt)
4899 return StmtError();
4900
4901 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004902
4903 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004904 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004905
Alexey Bataev25e5b442015-09-15 12:52:43 +00004906 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4907 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004908}
4909
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004910StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4911 Stmt *AStmt,
4912 SourceLocation StartLoc,
4913 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004914 if (!AStmt)
4915 return StmtError();
4916
4917 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004918
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004919 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004920
Alexey Bataev3255bf32015-01-19 05:20:46 +00004921 // OpenMP [2.7.3, single Construct, Restrictions]
4922 // The copyprivate clause must not be used with the nowait clause.
4923 OMPClause *Nowait = nullptr;
4924 OMPClause *Copyprivate = nullptr;
4925 for (auto *Clause : Clauses) {
4926 if (Clause->getClauseKind() == OMPC_nowait)
4927 Nowait = Clause;
4928 else if (Clause->getClauseKind() == OMPC_copyprivate)
4929 Copyprivate = Clause;
4930 if (Copyprivate && Nowait) {
4931 Diag(Copyprivate->getLocStart(),
4932 diag::err_omp_single_copyprivate_with_nowait);
4933 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4934 return StmtError();
4935 }
4936 }
4937
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004938 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4939}
4940
Alexander Musman80c22892014-07-17 08:54:58 +00004941StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4942 SourceLocation StartLoc,
4943 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004944 if (!AStmt)
4945 return StmtError();
4946
4947 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004948
4949 getCurFunction()->setHasBranchProtectedScope();
4950
4951 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4952}
4953
Alexey Bataev28c75412015-12-15 08:19:24 +00004954StmtResult Sema::ActOnOpenMPCriticalDirective(
4955 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4956 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004957 if (!AStmt)
4958 return StmtError();
4959
4960 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004961
Alexey Bataev28c75412015-12-15 08:19:24 +00004962 bool ErrorFound = false;
4963 llvm::APSInt Hint;
4964 SourceLocation HintLoc;
4965 bool DependentHint = false;
4966 for (auto *C : Clauses) {
4967 if (C->getClauseKind() == OMPC_hint) {
4968 if (!DirName.getName()) {
4969 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4970 ErrorFound = true;
4971 }
4972 Expr *E = cast<OMPHintClause>(C)->getHint();
4973 if (E->isTypeDependent() || E->isValueDependent() ||
4974 E->isInstantiationDependent())
4975 DependentHint = true;
4976 else {
4977 Hint = E->EvaluateKnownConstInt(Context);
4978 HintLoc = C->getLocStart();
4979 }
4980 }
4981 }
4982 if (ErrorFound)
4983 return StmtError();
4984 auto Pair = DSAStack->getCriticalWithHint(DirName);
4985 if (Pair.first && DirName.getName() && !DependentHint) {
4986 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4987 Diag(StartLoc, diag::err_omp_critical_with_hint);
4988 if (HintLoc.isValid()) {
4989 Diag(HintLoc, diag::note_omp_critical_hint_here)
4990 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4991 } else
4992 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4993 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4994 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4995 << 1
4996 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4997 /*Radix=*/10, /*Signed=*/false);
4998 } else
4999 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5000 }
5001 }
5002
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005003 getCurFunction()->setHasBranchProtectedScope();
5004
Alexey Bataev28c75412015-12-15 08:19:24 +00005005 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5006 Clauses, AStmt);
5007 if (!Pair.first && DirName.getName() && !DependentHint)
5008 DSAStack->addCriticalWithHint(Dir, Hint);
5009 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005010}
5011
Alexey Bataev4acb8592014-07-07 13:01:15 +00005012StmtResult Sema::ActOnOpenMPParallelForDirective(
5013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5014 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005015 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005016 if (!AStmt)
5017 return StmtError();
5018
Alexey Bataev4acb8592014-07-07 13:01:15 +00005019 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5020 // 1.2.2 OpenMP Language Terminology
5021 // Structured block - An executable statement with a single entry at the
5022 // top and a single exit at the bottom.
5023 // The point of exit cannot be a branch out of the structured block.
5024 // longjmp() and throw() must not violate the entry/exit criteria.
5025 CS->getCapturedDecl()->setNothrow();
5026
Alexander Musmanc6388682014-12-15 07:07:06 +00005027 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005028 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5029 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005030 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005031 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5032 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5033 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005034 if (NestedLoopCount == 0)
5035 return StmtError();
5036
Alexander Musmana5f070a2014-10-01 06:03:56 +00005037 assert((CurContext->isDependentContext() || B.builtAll()) &&
5038 "omp parallel for loop exprs were not built");
5039
Alexey Bataev54acd402015-08-04 11:18:19 +00005040 if (!CurContext->isDependentContext()) {
5041 // Finalize the clauses that need pre-built expressions for CodeGen.
5042 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005043 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005044 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005045 B.NumIterations, *this, CurScope,
5046 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005047 return StmtError();
5048 }
5049 }
5050
Alexey Bataev4acb8592014-07-07 13:01:15 +00005051 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005052 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005053 NestedLoopCount, Clauses, AStmt, B,
5054 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005055}
5056
Alexander Musmane4e893b2014-09-23 09:33:00 +00005057StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5058 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5059 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005060 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005061 if (!AStmt)
5062 return StmtError();
5063
Alexander Musmane4e893b2014-09-23 09:33:00 +00005064 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5065 // 1.2.2 OpenMP Language Terminology
5066 // Structured block - An executable statement with a single entry at the
5067 // top and a single exit at the bottom.
5068 // The point of exit cannot be a branch out of the structured block.
5069 // longjmp() and throw() must not violate the entry/exit criteria.
5070 CS->getCapturedDecl()->setNothrow();
5071
Alexander Musmanc6388682014-12-15 07:07:06 +00005072 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005073 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5074 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005075 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005076 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5077 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5078 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005079 if (NestedLoopCount == 0)
5080 return StmtError();
5081
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005082 if (!CurContext->isDependentContext()) {
5083 // Finalize the clauses that need pre-built expressions for CodeGen.
5084 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005085 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005086 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005087 B.NumIterations, *this, CurScope,
5088 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005089 return StmtError();
5090 }
5091 }
5092
Kelvin Lic5609492016-07-15 04:39:07 +00005093 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005094 return StmtError();
5095
Alexander Musmane4e893b2014-09-23 09:33:00 +00005096 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005097 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005098 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005099}
5100
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005101StmtResult
5102Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5103 Stmt *AStmt, SourceLocation StartLoc,
5104 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005105 if (!AStmt)
5106 return StmtError();
5107
5108 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005109 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005110 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005111 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005112 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005113 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005114 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005115 return StmtError();
5116 // All associated statements must be '#pragma omp section' except for
5117 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005118 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005119 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5120 if (SectionStmt)
5121 Diag(SectionStmt->getLocStart(),
5122 diag::err_omp_parallel_sections_substmt_not_section);
5123 return StmtError();
5124 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005125 cast<OMPSectionDirective>(SectionStmt)
5126 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005127 }
5128 } else {
5129 Diag(AStmt->getLocStart(),
5130 diag::err_omp_parallel_sections_not_compound_stmt);
5131 return StmtError();
5132 }
5133
5134 getCurFunction()->setHasBranchProtectedScope();
5135
Alexey Bataev25e5b442015-09-15 12:52:43 +00005136 return OMPParallelSectionsDirective::Create(
5137 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005138}
5139
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005140StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5141 Stmt *AStmt, SourceLocation StartLoc,
5142 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005143 if (!AStmt)
5144 return StmtError();
5145
David Majnemer9d168222016-08-05 17:44:54 +00005146 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005147 // 1.2.2 OpenMP Language Terminology
5148 // Structured block - An executable statement with a single entry at the
5149 // top and a single exit at the bottom.
5150 // The point of exit cannot be a branch out of the structured block.
5151 // longjmp() and throw() must not violate the entry/exit criteria.
5152 CS->getCapturedDecl()->setNothrow();
5153
5154 getCurFunction()->setHasBranchProtectedScope();
5155
Alexey Bataev25e5b442015-09-15 12:52:43 +00005156 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5157 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005158}
5159
Alexey Bataev68446b72014-07-18 07:47:19 +00005160StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5161 SourceLocation EndLoc) {
5162 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5163}
5164
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005165StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5166 SourceLocation EndLoc) {
5167 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5168}
5169
Alexey Bataev2df347a2014-07-18 10:17:07 +00005170StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5171 SourceLocation EndLoc) {
5172 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5173}
5174
Alexey Bataev169d96a2017-07-18 20:17:46 +00005175StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5176 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005177 SourceLocation StartLoc,
5178 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005179 if (!AStmt)
5180 return StmtError();
5181
5182 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005183
5184 getCurFunction()->setHasBranchProtectedScope();
5185
Alexey Bataev169d96a2017-07-18 20:17:46 +00005186 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5187 AStmt);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005188}
5189
Alexey Bataev6125da92014-07-21 11:26:11 +00005190StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5191 SourceLocation StartLoc,
5192 SourceLocation EndLoc) {
5193 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5194 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5195}
5196
Alexey Bataev346265e2015-09-25 10:37:12 +00005197StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5198 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005199 SourceLocation StartLoc,
5200 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005201 OMPClause *DependFound = nullptr;
5202 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005203 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005204 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005205 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005206 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005207 for (auto *C : Clauses) {
5208 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5209 DependFound = C;
5210 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5211 if (DependSourceClause) {
5212 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5213 << getOpenMPDirectiveName(OMPD_ordered)
5214 << getOpenMPClauseName(OMPC_depend) << 2;
5215 ErrorFound = true;
5216 } else
5217 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005218 if (DependSinkClause) {
5219 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5220 << 0;
5221 ErrorFound = true;
5222 }
5223 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5224 if (DependSourceClause) {
5225 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5226 << 1;
5227 ErrorFound = true;
5228 }
5229 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005230 }
5231 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005232 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005233 else if (C->getClauseKind() == OMPC_simd)
5234 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005235 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005236 if (!ErrorFound && !SC &&
5237 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005238 // OpenMP [2.8.1,simd Construct, Restrictions]
5239 // An ordered construct with the simd clause is the only OpenMP construct
5240 // that can appear in the simd region.
5241 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005242 ErrorFound = true;
5243 } else if (DependFound && (TC || SC)) {
5244 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5245 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5246 ErrorFound = true;
5247 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5248 Diag(DependFound->getLocStart(),
5249 diag::err_omp_ordered_directive_without_param);
5250 ErrorFound = true;
5251 } else if (TC || Clauses.empty()) {
5252 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5253 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5254 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5255 << (TC != nullptr);
5256 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5257 ErrorFound = true;
5258 }
5259 }
5260 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005261 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005262
5263 if (AStmt) {
5264 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5265
5266 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005267 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005268
5269 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005270}
5271
Alexey Bataev1d160b12015-03-13 12:27:31 +00005272namespace {
5273/// \brief Helper class for checking expression in 'omp atomic [update]'
5274/// construct.
5275class OpenMPAtomicUpdateChecker {
5276 /// \brief Error results for atomic update expressions.
5277 enum ExprAnalysisErrorCode {
5278 /// \brief A statement is not an expression statement.
5279 NotAnExpression,
5280 /// \brief Expression is not builtin binary or unary operation.
5281 NotABinaryOrUnaryExpression,
5282 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5283 NotAnUnaryIncDecExpression,
5284 /// \brief An expression is not of scalar type.
5285 NotAScalarType,
5286 /// \brief A binary operation is not an assignment operation.
5287 NotAnAssignmentOp,
5288 /// \brief RHS part of the binary operation is not a binary expression.
5289 NotABinaryExpression,
5290 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5291 /// expression.
5292 NotABinaryOperator,
5293 /// \brief RHS binary operation does not have reference to the updated LHS
5294 /// part.
5295 NotAnUpdateExpression,
5296 /// \brief No errors is found.
5297 NoError
5298 };
5299 /// \brief Reference to Sema.
5300 Sema &SemaRef;
5301 /// \brief A location for note diagnostics (when error is found).
5302 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005303 /// \brief 'x' lvalue part of the source atomic expression.
5304 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005305 /// \brief 'expr' rvalue part of the source atomic expression.
5306 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005307 /// \brief Helper expression of the form
5308 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5309 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5310 Expr *UpdateExpr;
5311 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5312 /// important for non-associative operations.
5313 bool IsXLHSInRHSPart;
5314 BinaryOperatorKind Op;
5315 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005316 /// \brief true if the source expression is a postfix unary operation, false
5317 /// if it is a prefix unary operation.
5318 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005319
5320public:
5321 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005322 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005323 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005324 /// \brief Check specified statement that it is suitable for 'atomic update'
5325 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005326 /// expression. If DiagId and NoteId == 0, then only check is performed
5327 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005328 /// \param DiagId Diagnostic which should be emitted if error is found.
5329 /// \param NoteId Diagnostic note for the main error message.
5330 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005331 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005332 /// \brief Return the 'x' lvalue part of the source atomic expression.
5333 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005334 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5335 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005336 /// \brief Return the update expression used in calculation of the updated
5337 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5338 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5339 Expr *getUpdateExpr() const { return UpdateExpr; }
5340 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5341 /// false otherwise.
5342 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5343
Alexey Bataevb78ca832015-04-01 03:33:17 +00005344 /// \brief true if the source expression is a postfix unary operation, false
5345 /// if it is a prefix unary operation.
5346 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5347
Alexey Bataev1d160b12015-03-13 12:27:31 +00005348private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005349 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5350 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005351};
5352} // namespace
5353
5354bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5355 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5356 ExprAnalysisErrorCode ErrorFound = NoError;
5357 SourceLocation ErrorLoc, NoteLoc;
5358 SourceRange ErrorRange, NoteRange;
5359 // Allowed constructs are:
5360 // x = x binop expr;
5361 // x = expr binop x;
5362 if (AtomicBinOp->getOpcode() == BO_Assign) {
5363 X = AtomicBinOp->getLHS();
5364 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5365 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5366 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5367 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5368 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005369 Op = AtomicInnerBinOp->getOpcode();
5370 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005371 auto *LHS = AtomicInnerBinOp->getLHS();
5372 auto *RHS = AtomicInnerBinOp->getRHS();
5373 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5374 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5375 /*Canonical=*/true);
5376 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5377 /*Canonical=*/true);
5378 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5379 /*Canonical=*/true);
5380 if (XId == LHSId) {
5381 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005382 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005383 } else if (XId == RHSId) {
5384 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005385 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005386 } else {
5387 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5388 ErrorRange = AtomicInnerBinOp->getSourceRange();
5389 NoteLoc = X->getExprLoc();
5390 NoteRange = X->getSourceRange();
5391 ErrorFound = NotAnUpdateExpression;
5392 }
5393 } else {
5394 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5395 ErrorRange = AtomicInnerBinOp->getSourceRange();
5396 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5397 NoteRange = SourceRange(NoteLoc, NoteLoc);
5398 ErrorFound = NotABinaryOperator;
5399 }
5400 } else {
5401 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5402 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5403 ErrorFound = NotABinaryExpression;
5404 }
5405 } else {
5406 ErrorLoc = AtomicBinOp->getExprLoc();
5407 ErrorRange = AtomicBinOp->getSourceRange();
5408 NoteLoc = AtomicBinOp->getOperatorLoc();
5409 NoteRange = SourceRange(NoteLoc, NoteLoc);
5410 ErrorFound = NotAnAssignmentOp;
5411 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005412 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005413 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5414 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5415 return true;
5416 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005417 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005418 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005419}
5420
5421bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5422 unsigned NoteId) {
5423 ExprAnalysisErrorCode ErrorFound = NoError;
5424 SourceLocation ErrorLoc, NoteLoc;
5425 SourceRange ErrorRange, NoteRange;
5426 // Allowed constructs are:
5427 // x++;
5428 // x--;
5429 // ++x;
5430 // --x;
5431 // x binop= expr;
5432 // x = x binop expr;
5433 // x = expr binop x;
5434 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5435 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5436 if (AtomicBody->getType()->isScalarType() ||
5437 AtomicBody->isInstantiationDependent()) {
5438 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5439 AtomicBody->IgnoreParenImpCasts())) {
5440 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005441 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005442 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005443 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005444 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005445 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005446 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005447 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5448 AtomicBody->IgnoreParenImpCasts())) {
5449 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005450 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005451 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005452 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5453 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005454 // Check for Unary Operation
5455 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005456 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005457 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5458 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005459 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005460 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5461 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005462 } else {
5463 ErrorFound = NotAnUnaryIncDecExpression;
5464 ErrorLoc = AtomicUnaryOp->getExprLoc();
5465 ErrorRange = AtomicUnaryOp->getSourceRange();
5466 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5467 NoteRange = SourceRange(NoteLoc, NoteLoc);
5468 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005469 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005470 ErrorFound = NotABinaryOrUnaryExpression;
5471 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5472 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5473 }
5474 } else {
5475 ErrorFound = NotAScalarType;
5476 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5477 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5478 }
5479 } else {
5480 ErrorFound = NotAnExpression;
5481 NoteLoc = ErrorLoc = S->getLocStart();
5482 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5483 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005484 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005485 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5486 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5487 return true;
5488 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005489 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005490 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005491 // Build an update expression of form 'OpaqueValueExpr(x) binop
5492 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5493 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5494 auto *OVEX = new (SemaRef.getASTContext())
5495 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5496 auto *OVEExpr = new (SemaRef.getASTContext())
5497 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5498 auto Update =
5499 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5500 IsXLHSInRHSPart ? OVEExpr : OVEX);
5501 if (Update.isInvalid())
5502 return true;
5503 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5504 Sema::AA_Casting);
5505 if (Update.isInvalid())
5506 return true;
5507 UpdateExpr = Update.get();
5508 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005509 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005510}
5511
Alexey Bataev0162e452014-07-22 10:10:35 +00005512StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5513 Stmt *AStmt,
5514 SourceLocation StartLoc,
5515 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005516 if (!AStmt)
5517 return StmtError();
5518
David Majnemer9d168222016-08-05 17:44:54 +00005519 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005520 // 1.2.2 OpenMP Language Terminology
5521 // Structured block - An executable statement with a single entry at the
5522 // top and a single exit at the bottom.
5523 // The point of exit cannot be a branch out of the structured block.
5524 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005525 OpenMPClauseKind AtomicKind = OMPC_unknown;
5526 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005527 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005528 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005529 C->getClauseKind() == OMPC_update ||
5530 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005531 if (AtomicKind != OMPC_unknown) {
5532 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5533 << SourceRange(C->getLocStart(), C->getLocEnd());
5534 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5535 << getOpenMPClauseName(AtomicKind);
5536 } else {
5537 AtomicKind = C->getClauseKind();
5538 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005539 }
5540 }
5541 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005542
Alexey Bataev459dec02014-07-24 06:46:57 +00005543 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005544 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5545 Body = EWC->getSubExpr();
5546
Alexey Bataev62cec442014-11-18 10:14:22 +00005547 Expr *X = nullptr;
5548 Expr *V = nullptr;
5549 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005550 Expr *UE = nullptr;
5551 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005552 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005553 // OpenMP [2.12.6, atomic Construct]
5554 // In the next expressions:
5555 // * x and v (as applicable) are both l-value expressions with scalar type.
5556 // * During the execution of an atomic region, multiple syntactic
5557 // occurrences of x must designate the same storage location.
5558 // * Neither of v and expr (as applicable) may access the storage location
5559 // designated by x.
5560 // * Neither of x and expr (as applicable) may access the storage location
5561 // designated by v.
5562 // * expr is an expression with scalar type.
5563 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5564 // * binop, binop=, ++, and -- are not overloaded operators.
5565 // * The expression x binop expr must be numerically equivalent to x binop
5566 // (expr). This requirement is satisfied if the operators in expr have
5567 // precedence greater than binop, or by using parentheses around expr or
5568 // subexpressions of expr.
5569 // * The expression expr binop x must be numerically equivalent to (expr)
5570 // binop x. This requirement is satisfied if the operators in expr have
5571 // precedence equal to or greater than binop, or by using parentheses around
5572 // expr or subexpressions of expr.
5573 // * For forms that allow multiple occurrences of x, the number of times
5574 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005575 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005576 enum {
5577 NotAnExpression,
5578 NotAnAssignmentOp,
5579 NotAScalarType,
5580 NotAnLValue,
5581 NoError
5582 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005583 SourceLocation ErrorLoc, NoteLoc;
5584 SourceRange ErrorRange, NoteRange;
5585 // If clause is read:
5586 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005587 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5588 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005589 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5590 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5591 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5592 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5593 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5594 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5595 if (!X->isLValue() || !V->isLValue()) {
5596 auto NotLValueExpr = X->isLValue() ? V : X;
5597 ErrorFound = NotAnLValue;
5598 ErrorLoc = AtomicBinOp->getExprLoc();
5599 ErrorRange = AtomicBinOp->getSourceRange();
5600 NoteLoc = NotLValueExpr->getExprLoc();
5601 NoteRange = NotLValueExpr->getSourceRange();
5602 }
5603 } else if (!X->isInstantiationDependent() ||
5604 !V->isInstantiationDependent()) {
5605 auto NotScalarExpr =
5606 (X->isInstantiationDependent() || X->getType()->isScalarType())
5607 ? V
5608 : X;
5609 ErrorFound = NotAScalarType;
5610 ErrorLoc = AtomicBinOp->getExprLoc();
5611 ErrorRange = AtomicBinOp->getSourceRange();
5612 NoteLoc = NotScalarExpr->getExprLoc();
5613 NoteRange = NotScalarExpr->getSourceRange();
5614 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005615 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005616 ErrorFound = NotAnAssignmentOp;
5617 ErrorLoc = AtomicBody->getExprLoc();
5618 ErrorRange = AtomicBody->getSourceRange();
5619 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5620 : AtomicBody->getExprLoc();
5621 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5622 : AtomicBody->getSourceRange();
5623 }
5624 } else {
5625 ErrorFound = NotAnExpression;
5626 NoteLoc = ErrorLoc = Body->getLocStart();
5627 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005628 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005629 if (ErrorFound != NoError) {
5630 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5631 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005632 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5633 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005634 return StmtError();
5635 } else if (CurContext->isDependentContext())
5636 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005637 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005638 enum {
5639 NotAnExpression,
5640 NotAnAssignmentOp,
5641 NotAScalarType,
5642 NotAnLValue,
5643 NoError
5644 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005645 SourceLocation ErrorLoc, NoteLoc;
5646 SourceRange ErrorRange, NoteRange;
5647 // If clause is write:
5648 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005649 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5650 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005651 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5652 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005653 X = AtomicBinOp->getLHS();
5654 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005655 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5656 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5657 if (!X->isLValue()) {
5658 ErrorFound = NotAnLValue;
5659 ErrorLoc = AtomicBinOp->getExprLoc();
5660 ErrorRange = AtomicBinOp->getSourceRange();
5661 NoteLoc = X->getExprLoc();
5662 NoteRange = X->getSourceRange();
5663 }
5664 } else if (!X->isInstantiationDependent() ||
5665 !E->isInstantiationDependent()) {
5666 auto NotScalarExpr =
5667 (X->isInstantiationDependent() || X->getType()->isScalarType())
5668 ? E
5669 : X;
5670 ErrorFound = NotAScalarType;
5671 ErrorLoc = AtomicBinOp->getExprLoc();
5672 ErrorRange = AtomicBinOp->getSourceRange();
5673 NoteLoc = NotScalarExpr->getExprLoc();
5674 NoteRange = NotScalarExpr->getSourceRange();
5675 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005676 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005677 ErrorFound = NotAnAssignmentOp;
5678 ErrorLoc = AtomicBody->getExprLoc();
5679 ErrorRange = AtomicBody->getSourceRange();
5680 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5681 : AtomicBody->getExprLoc();
5682 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5683 : AtomicBody->getSourceRange();
5684 }
5685 } else {
5686 ErrorFound = NotAnExpression;
5687 NoteLoc = ErrorLoc = Body->getLocStart();
5688 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005689 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005690 if (ErrorFound != NoError) {
5691 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5692 << ErrorRange;
5693 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5694 << NoteRange;
5695 return StmtError();
5696 } else if (CurContext->isDependentContext())
5697 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005698 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005699 // If clause is update:
5700 // x++;
5701 // x--;
5702 // ++x;
5703 // --x;
5704 // x binop= expr;
5705 // x = x binop expr;
5706 // x = expr binop x;
5707 OpenMPAtomicUpdateChecker Checker(*this);
5708 if (Checker.checkStatement(
5709 Body, (AtomicKind == OMPC_update)
5710 ? diag::err_omp_atomic_update_not_expression_statement
5711 : diag::err_omp_atomic_not_expression_statement,
5712 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005713 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005714 if (!CurContext->isDependentContext()) {
5715 E = Checker.getExpr();
5716 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005717 UE = Checker.getUpdateExpr();
5718 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005719 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005720 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005721 enum {
5722 NotAnAssignmentOp,
5723 NotACompoundStatement,
5724 NotTwoSubstatements,
5725 NotASpecificExpression,
5726 NoError
5727 } ErrorFound = NoError;
5728 SourceLocation ErrorLoc, NoteLoc;
5729 SourceRange ErrorRange, NoteRange;
5730 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5731 // If clause is a capture:
5732 // v = x++;
5733 // v = x--;
5734 // v = ++x;
5735 // v = --x;
5736 // v = x binop= expr;
5737 // v = x = x binop expr;
5738 // v = x = expr binop x;
5739 auto *AtomicBinOp =
5740 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5741 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5742 V = AtomicBinOp->getLHS();
5743 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5744 OpenMPAtomicUpdateChecker Checker(*this);
5745 if (Checker.checkStatement(
5746 Body, diag::err_omp_atomic_capture_not_expression_statement,
5747 diag::note_omp_atomic_update))
5748 return StmtError();
5749 E = Checker.getExpr();
5750 X = Checker.getX();
5751 UE = Checker.getUpdateExpr();
5752 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5753 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005754 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005755 ErrorLoc = AtomicBody->getExprLoc();
5756 ErrorRange = AtomicBody->getSourceRange();
5757 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5758 : AtomicBody->getExprLoc();
5759 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5760 : AtomicBody->getSourceRange();
5761 ErrorFound = NotAnAssignmentOp;
5762 }
5763 if (ErrorFound != NoError) {
5764 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5765 << ErrorRange;
5766 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5767 return StmtError();
5768 } else if (CurContext->isDependentContext()) {
5769 UE = V = E = X = nullptr;
5770 }
5771 } else {
5772 // If clause is a capture:
5773 // { v = x; x = expr; }
5774 // { v = x; x++; }
5775 // { v = x; x--; }
5776 // { v = x; ++x; }
5777 // { v = x; --x; }
5778 // { v = x; x binop= expr; }
5779 // { v = x; x = x binop expr; }
5780 // { v = x; x = expr binop x; }
5781 // { x++; v = x; }
5782 // { x--; v = x; }
5783 // { ++x; v = x; }
5784 // { --x; v = x; }
5785 // { x binop= expr; v = x; }
5786 // { x = x binop expr; v = x; }
5787 // { x = expr binop x; v = x; }
5788 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5789 // Check that this is { expr1; expr2; }
5790 if (CS->size() == 2) {
5791 auto *First = CS->body_front();
5792 auto *Second = CS->body_back();
5793 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5794 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5795 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5796 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5797 // Need to find what subexpression is 'v' and what is 'x'.
5798 OpenMPAtomicUpdateChecker Checker(*this);
5799 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5800 BinaryOperator *BinOp = nullptr;
5801 if (IsUpdateExprFound) {
5802 BinOp = dyn_cast<BinaryOperator>(First);
5803 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5804 }
5805 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5806 // { v = x; x++; }
5807 // { v = x; x--; }
5808 // { v = x; ++x; }
5809 // { v = x; --x; }
5810 // { v = x; x binop= expr; }
5811 // { v = x; x = x binop expr; }
5812 // { v = x; x = expr binop x; }
5813 // Check that the first expression has form v = x.
5814 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5815 llvm::FoldingSetNodeID XId, PossibleXId;
5816 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5817 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5818 IsUpdateExprFound = XId == PossibleXId;
5819 if (IsUpdateExprFound) {
5820 V = BinOp->getLHS();
5821 X = Checker.getX();
5822 E = Checker.getExpr();
5823 UE = Checker.getUpdateExpr();
5824 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005825 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005826 }
5827 }
5828 if (!IsUpdateExprFound) {
5829 IsUpdateExprFound = !Checker.checkStatement(First);
5830 BinOp = nullptr;
5831 if (IsUpdateExprFound) {
5832 BinOp = dyn_cast<BinaryOperator>(Second);
5833 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5834 }
5835 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5836 // { x++; v = x; }
5837 // { x--; v = x; }
5838 // { ++x; v = x; }
5839 // { --x; v = x; }
5840 // { x binop= expr; v = x; }
5841 // { x = x binop expr; v = x; }
5842 // { x = expr binop x; v = x; }
5843 // Check that the second expression has form v = x.
5844 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5845 llvm::FoldingSetNodeID XId, PossibleXId;
5846 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5847 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5848 IsUpdateExprFound = XId == PossibleXId;
5849 if (IsUpdateExprFound) {
5850 V = BinOp->getLHS();
5851 X = Checker.getX();
5852 E = Checker.getExpr();
5853 UE = Checker.getUpdateExpr();
5854 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005855 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005856 }
5857 }
5858 }
5859 if (!IsUpdateExprFound) {
5860 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005861 auto *FirstExpr = dyn_cast<Expr>(First);
5862 auto *SecondExpr = dyn_cast<Expr>(Second);
5863 if (!FirstExpr || !SecondExpr ||
5864 !(FirstExpr->isInstantiationDependent() ||
5865 SecondExpr->isInstantiationDependent())) {
5866 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5867 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005868 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005869 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5870 : First->getLocStart();
5871 NoteRange = ErrorRange = FirstBinOp
5872 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005873 : SourceRange(ErrorLoc, ErrorLoc);
5874 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005875 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5876 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5877 ErrorFound = NotAnAssignmentOp;
5878 NoteLoc = ErrorLoc = SecondBinOp
5879 ? SecondBinOp->getOperatorLoc()
5880 : Second->getLocStart();
5881 NoteRange = ErrorRange =
5882 SecondBinOp ? SecondBinOp->getSourceRange()
5883 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005884 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005885 auto *PossibleXRHSInFirst =
5886 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5887 auto *PossibleXLHSInSecond =
5888 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5889 llvm::FoldingSetNodeID X1Id, X2Id;
5890 PossibleXRHSInFirst->Profile(X1Id, Context,
5891 /*Canonical=*/true);
5892 PossibleXLHSInSecond->Profile(X2Id, Context,
5893 /*Canonical=*/true);
5894 IsUpdateExprFound = X1Id == X2Id;
5895 if (IsUpdateExprFound) {
5896 V = FirstBinOp->getLHS();
5897 X = SecondBinOp->getLHS();
5898 E = SecondBinOp->getRHS();
5899 UE = nullptr;
5900 IsXLHSInRHSPart = false;
5901 IsPostfixUpdate = true;
5902 } else {
5903 ErrorFound = NotASpecificExpression;
5904 ErrorLoc = FirstBinOp->getExprLoc();
5905 ErrorRange = FirstBinOp->getSourceRange();
5906 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5907 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5908 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005909 }
5910 }
5911 }
5912 }
5913 } else {
5914 NoteLoc = ErrorLoc = Body->getLocStart();
5915 NoteRange = ErrorRange =
5916 SourceRange(Body->getLocStart(), Body->getLocStart());
5917 ErrorFound = NotTwoSubstatements;
5918 }
5919 } else {
5920 NoteLoc = ErrorLoc = Body->getLocStart();
5921 NoteRange = ErrorRange =
5922 SourceRange(Body->getLocStart(), Body->getLocStart());
5923 ErrorFound = NotACompoundStatement;
5924 }
5925 if (ErrorFound != NoError) {
5926 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5927 << ErrorRange;
5928 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5929 return StmtError();
5930 } else if (CurContext->isDependentContext()) {
5931 UE = V = E = X = nullptr;
5932 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005933 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005934 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005935
5936 getCurFunction()->setHasBranchProtectedScope();
5937
Alexey Bataev62cec442014-11-18 10:14:22 +00005938 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005939 X, V, E, UE, IsXLHSInRHSPart,
5940 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005941}
5942
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005943StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5944 Stmt *AStmt,
5945 SourceLocation StartLoc,
5946 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005947 if (!AStmt)
5948 return StmtError();
5949
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005950 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5951 // 1.2.2 OpenMP Language Terminology
5952 // Structured block - An executable statement with a single entry at the
5953 // top and a single exit at the bottom.
5954 // The point of exit cannot be a branch out of the structured block.
5955 // longjmp() and throw() must not violate the entry/exit criteria.
5956 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005957
Alexey Bataev13314bf2014-10-09 04:18:56 +00005958 // OpenMP [2.16, Nesting of Regions]
5959 // If specified, a teams construct must be contained within a target
5960 // construct. That target construct must contain no statements or directives
5961 // outside of the teams construct.
5962 if (DSAStack->hasInnerTeamsRegion()) {
5963 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5964 bool OMPTeamsFound = true;
5965 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5966 auto I = CS->body_begin();
5967 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005968 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005969 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5970 OMPTeamsFound = false;
5971 break;
5972 }
5973 ++I;
5974 }
5975 assert(I != CS->body_end() && "Not found statement");
5976 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005977 } else {
5978 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5979 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005980 }
5981 if (!OMPTeamsFound) {
5982 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5983 Diag(DSAStack->getInnerTeamsRegionLoc(),
5984 diag::note_omp_nested_teams_construct_here);
5985 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5986 << isa<OMPExecutableDirective>(S);
5987 return StmtError();
5988 }
5989 }
5990
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005991 getCurFunction()->setHasBranchProtectedScope();
5992
5993 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5994}
5995
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005996StmtResult
5997Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5998 Stmt *AStmt, SourceLocation StartLoc,
5999 SourceLocation EndLoc) {
6000 if (!AStmt)
6001 return StmtError();
6002
6003 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6004 // 1.2.2 OpenMP Language Terminology
6005 // Structured block - An executable statement with a single entry at the
6006 // top and a single exit at the bottom.
6007 // The point of exit cannot be a branch out of the structured block.
6008 // longjmp() and throw() must not violate the entry/exit criteria.
6009 CS->getCapturedDecl()->setNothrow();
6010
6011 getCurFunction()->setHasBranchProtectedScope();
6012
6013 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6014 AStmt);
6015}
6016
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006017StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6018 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6019 SourceLocation EndLoc,
6020 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6021 if (!AStmt)
6022 return StmtError();
6023
6024 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6025 // 1.2.2 OpenMP Language Terminology
6026 // Structured block - An executable statement with a single entry at the
6027 // top and a single exit at the bottom.
6028 // The point of exit cannot be a branch out of the structured block.
6029 // longjmp() and throw() must not violate the entry/exit criteria.
6030 CS->getCapturedDecl()->setNothrow();
6031
6032 OMPLoopDirective::HelperExprs B;
6033 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6034 // define the nested loops number.
6035 unsigned NestedLoopCount =
6036 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6037 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6038 VarsWithImplicitDSA, B);
6039 if (NestedLoopCount == 0)
6040 return StmtError();
6041
6042 assert((CurContext->isDependentContext() || B.builtAll()) &&
6043 "omp target parallel for loop exprs were not built");
6044
6045 if (!CurContext->isDependentContext()) {
6046 // Finalize the clauses that need pre-built expressions for CodeGen.
6047 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006048 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006049 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006050 B.NumIterations, *this, CurScope,
6051 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006052 return StmtError();
6053 }
6054 }
6055
6056 getCurFunction()->setHasBranchProtectedScope();
6057 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6058 NestedLoopCount, Clauses, AStmt,
6059 B, DSAStack->isCancelRegion());
6060}
6061
Alexey Bataev95b64a92017-05-30 16:00:04 +00006062/// Check for existence of a map clause in the list of clauses.
6063static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6064 const OpenMPClauseKind K) {
6065 return llvm::any_of(
6066 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6067}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006068
Alexey Bataev95b64a92017-05-30 16:00:04 +00006069template <typename... Params>
6070static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6071 const Params... ClauseTypes) {
6072 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006073}
6074
Michael Wong65f367f2015-07-21 13:44:28 +00006075StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6076 Stmt *AStmt,
6077 SourceLocation StartLoc,
6078 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006079 if (!AStmt)
6080 return StmtError();
6081
6082 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6083
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006084 // OpenMP [2.10.1, Restrictions, p. 97]
6085 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006086 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6087 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6088 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006089 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006090 return StmtError();
6091 }
6092
Michael Wong65f367f2015-07-21 13:44:28 +00006093 getCurFunction()->setHasBranchProtectedScope();
6094
6095 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6096 AStmt);
6097}
6098
Samuel Antaodf67fc42016-01-19 19:15:56 +00006099StmtResult
6100Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6101 SourceLocation StartLoc,
6102 SourceLocation EndLoc) {
6103 // OpenMP [2.10.2, Restrictions, p. 99]
6104 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006105 if (!hasClauses(Clauses, OMPC_map)) {
6106 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6107 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006108 return StmtError();
6109 }
6110
6111 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6112 Clauses);
6113}
6114
Samuel Antao72590762016-01-19 20:04:50 +00006115StmtResult
6116Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6117 SourceLocation StartLoc,
6118 SourceLocation EndLoc) {
6119 // OpenMP [2.10.3, Restrictions, p. 102]
6120 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006121 if (!hasClauses(Clauses, OMPC_map)) {
6122 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6123 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006124 return StmtError();
6125 }
6126
6127 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6128}
6129
Samuel Antao686c70c2016-05-26 17:30:50 +00006130StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6131 SourceLocation StartLoc,
6132 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006133 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006134 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6135 return StmtError();
6136 }
6137 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6138}
6139
Alexey Bataev13314bf2014-10-09 04:18:56 +00006140StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6141 Stmt *AStmt, SourceLocation StartLoc,
6142 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006143 if (!AStmt)
6144 return StmtError();
6145
Alexey Bataev13314bf2014-10-09 04:18:56 +00006146 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6147 // 1.2.2 OpenMP Language Terminology
6148 // Structured block - An executable statement with a single entry at the
6149 // top and a single exit at the bottom.
6150 // The point of exit cannot be a branch out of the structured block.
6151 // longjmp() and throw() must not violate the entry/exit criteria.
6152 CS->getCapturedDecl()->setNothrow();
6153
6154 getCurFunction()->setHasBranchProtectedScope();
6155
6156 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6157}
6158
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006159StmtResult
6160Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6161 SourceLocation EndLoc,
6162 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006163 if (DSAStack->isParentNowaitRegion()) {
6164 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6165 return StmtError();
6166 }
6167 if (DSAStack->isParentOrderedRegion()) {
6168 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6169 return StmtError();
6170 }
6171 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6172 CancelRegion);
6173}
6174
Alexey Bataev87933c72015-09-18 08:07:34 +00006175StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6176 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006177 SourceLocation EndLoc,
6178 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006179 if (DSAStack->isParentNowaitRegion()) {
6180 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6181 return StmtError();
6182 }
6183 if (DSAStack->isParentOrderedRegion()) {
6184 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6185 return StmtError();
6186 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006187 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006188 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6189 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006190}
6191
Alexey Bataev382967a2015-12-08 12:06:20 +00006192static bool checkGrainsizeNumTasksClauses(Sema &S,
6193 ArrayRef<OMPClause *> Clauses) {
6194 OMPClause *PrevClause = nullptr;
6195 bool ErrorFound = false;
6196 for (auto *C : Clauses) {
6197 if (C->getClauseKind() == OMPC_grainsize ||
6198 C->getClauseKind() == OMPC_num_tasks) {
6199 if (!PrevClause)
6200 PrevClause = C;
6201 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6202 S.Diag(C->getLocStart(),
6203 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6204 << getOpenMPClauseName(C->getClauseKind())
6205 << getOpenMPClauseName(PrevClause->getClauseKind());
6206 S.Diag(PrevClause->getLocStart(),
6207 diag::note_omp_previous_grainsize_num_tasks)
6208 << getOpenMPClauseName(PrevClause->getClauseKind());
6209 ErrorFound = true;
6210 }
6211 }
6212 }
6213 return ErrorFound;
6214}
6215
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006216static bool checkReductionClauseWithNogroup(Sema &S,
6217 ArrayRef<OMPClause *> Clauses) {
6218 OMPClause *ReductionClause = nullptr;
6219 OMPClause *NogroupClause = nullptr;
6220 for (auto *C : Clauses) {
6221 if (C->getClauseKind() == OMPC_reduction) {
6222 ReductionClause = C;
6223 if (NogroupClause)
6224 break;
6225 continue;
6226 }
6227 if (C->getClauseKind() == OMPC_nogroup) {
6228 NogroupClause = C;
6229 if (ReductionClause)
6230 break;
6231 continue;
6232 }
6233 }
6234 if (ReductionClause && NogroupClause) {
6235 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6236 << SourceRange(NogroupClause->getLocStart(),
6237 NogroupClause->getLocEnd());
6238 return true;
6239 }
6240 return false;
6241}
6242
Alexey Bataev49f6e782015-12-01 04:18:41 +00006243StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6244 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6245 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006246 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006247 if (!AStmt)
6248 return StmtError();
6249
6250 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6251 OMPLoopDirective::HelperExprs B;
6252 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6253 // define the nested loops number.
6254 unsigned NestedLoopCount =
6255 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006256 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006257 VarsWithImplicitDSA, B);
6258 if (NestedLoopCount == 0)
6259 return StmtError();
6260
6261 assert((CurContext->isDependentContext() || B.builtAll()) &&
6262 "omp for loop exprs were not built");
6263
Alexey Bataev382967a2015-12-08 12:06:20 +00006264 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6265 // The grainsize clause and num_tasks clause are mutually exclusive and may
6266 // not appear on the same taskloop directive.
6267 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6268 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006269 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6270 // If a reduction clause is present on the taskloop directive, the nogroup
6271 // clause must not be specified.
6272 if (checkReductionClauseWithNogroup(*this, Clauses))
6273 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006274
Alexey Bataev49f6e782015-12-01 04:18:41 +00006275 getCurFunction()->setHasBranchProtectedScope();
6276 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6277 NestedLoopCount, Clauses, AStmt, B);
6278}
6279
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006280StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6281 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6282 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006283 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006284 if (!AStmt)
6285 return StmtError();
6286
6287 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6288 OMPLoopDirective::HelperExprs B;
6289 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6290 // define the nested loops number.
6291 unsigned NestedLoopCount =
6292 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6293 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6294 VarsWithImplicitDSA, B);
6295 if (NestedLoopCount == 0)
6296 return StmtError();
6297
6298 assert((CurContext->isDependentContext() || B.builtAll()) &&
6299 "omp for loop exprs were not built");
6300
Alexey Bataev5a3af132016-03-29 08:58:54 +00006301 if (!CurContext->isDependentContext()) {
6302 // Finalize the clauses that need pre-built expressions for CodeGen.
6303 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006304 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006305 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006306 B.NumIterations, *this, CurScope,
6307 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006308 return StmtError();
6309 }
6310 }
6311
Alexey Bataev382967a2015-12-08 12:06:20 +00006312 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6313 // The grainsize clause and num_tasks clause are mutually exclusive and may
6314 // not appear on the same taskloop directive.
6315 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6316 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006317 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6318 // If a reduction clause is present on the taskloop directive, the nogroup
6319 // clause must not be specified.
6320 if (checkReductionClauseWithNogroup(*this, Clauses))
6321 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006322
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006323 getCurFunction()->setHasBranchProtectedScope();
6324 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6325 NestedLoopCount, Clauses, AStmt, B);
6326}
6327
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006328StmtResult Sema::ActOnOpenMPDistributeDirective(
6329 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6330 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006331 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006332 if (!AStmt)
6333 return StmtError();
6334
6335 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6336 OMPLoopDirective::HelperExprs B;
6337 // In presence of clause 'collapse' with number of loops, it will
6338 // define the nested loops number.
6339 unsigned NestedLoopCount =
6340 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6341 nullptr /*ordered not a clause on distribute*/, AStmt,
6342 *this, *DSAStack, VarsWithImplicitDSA, B);
6343 if (NestedLoopCount == 0)
6344 return StmtError();
6345
6346 assert((CurContext->isDependentContext() || B.builtAll()) &&
6347 "omp for loop exprs were not built");
6348
6349 getCurFunction()->setHasBranchProtectedScope();
6350 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6351 NestedLoopCount, Clauses, AStmt, B);
6352}
6353
Carlo Bertolli9925f152016-06-27 14:55:37 +00006354StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6355 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6356 SourceLocation EndLoc,
6357 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6358 if (!AStmt)
6359 return StmtError();
6360
6361 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6362 // 1.2.2 OpenMP Language Terminology
6363 // Structured block - An executable statement with a single entry at the
6364 // top and a single exit at the bottom.
6365 // The point of exit cannot be a branch out of the structured block.
6366 // longjmp() and throw() must not violate the entry/exit criteria.
6367 CS->getCapturedDecl()->setNothrow();
6368
6369 OMPLoopDirective::HelperExprs B;
6370 // In presence of clause 'collapse' with number of loops, it will
6371 // define the nested loops number.
6372 unsigned NestedLoopCount = CheckOpenMPLoop(
6373 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6374 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6375 VarsWithImplicitDSA, B);
6376 if (NestedLoopCount == 0)
6377 return StmtError();
6378
6379 assert((CurContext->isDependentContext() || B.builtAll()) &&
6380 "omp for loop exprs were not built");
6381
6382 getCurFunction()->setHasBranchProtectedScope();
6383 return OMPDistributeParallelForDirective::Create(
6384 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6385}
6386
Kelvin Li4a39add2016-07-05 05:00:15 +00006387StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6388 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6389 SourceLocation EndLoc,
6390 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6391 if (!AStmt)
6392 return StmtError();
6393
6394 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6395 // 1.2.2 OpenMP Language Terminology
6396 // Structured block - An executable statement with a single entry at the
6397 // top and a single exit at the bottom.
6398 // The point of exit cannot be a branch out of the structured block.
6399 // longjmp() and throw() must not violate the entry/exit criteria.
6400 CS->getCapturedDecl()->setNothrow();
6401
6402 OMPLoopDirective::HelperExprs B;
6403 // In presence of clause 'collapse' with number of loops, it will
6404 // define the nested loops number.
6405 unsigned NestedLoopCount = CheckOpenMPLoop(
6406 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6407 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6408 VarsWithImplicitDSA, B);
6409 if (NestedLoopCount == 0)
6410 return StmtError();
6411
6412 assert((CurContext->isDependentContext() || B.builtAll()) &&
6413 "omp for loop exprs were not built");
6414
Kelvin Lic5609492016-07-15 04:39:07 +00006415 if (checkSimdlenSafelenSpecified(*this, Clauses))
6416 return StmtError();
6417
Kelvin Li4a39add2016-07-05 05:00:15 +00006418 getCurFunction()->setHasBranchProtectedScope();
6419 return OMPDistributeParallelForSimdDirective::Create(
6420 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6421}
6422
Kelvin Li787f3fc2016-07-06 04:45:38 +00006423StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6424 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6425 SourceLocation EndLoc,
6426 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6427 if (!AStmt)
6428 return StmtError();
6429
6430 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6431 // 1.2.2 OpenMP Language Terminology
6432 // Structured block - An executable statement with a single entry at the
6433 // top and a single exit at the bottom.
6434 // The point of exit cannot be a branch out of the structured block.
6435 // longjmp() and throw() must not violate the entry/exit criteria.
6436 CS->getCapturedDecl()->setNothrow();
6437
6438 OMPLoopDirective::HelperExprs B;
6439 // In presence of clause 'collapse' with number of loops, it will
6440 // define the nested loops number.
6441 unsigned NestedLoopCount =
6442 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6443 nullptr /*ordered not a clause on distribute*/, AStmt,
6444 *this, *DSAStack, VarsWithImplicitDSA, B);
6445 if (NestedLoopCount == 0)
6446 return StmtError();
6447
6448 assert((CurContext->isDependentContext() || B.builtAll()) &&
6449 "omp for loop exprs were not built");
6450
Kelvin Lic5609492016-07-15 04:39:07 +00006451 if (checkSimdlenSafelenSpecified(*this, Clauses))
6452 return StmtError();
6453
Kelvin Li787f3fc2016-07-06 04:45:38 +00006454 getCurFunction()->setHasBranchProtectedScope();
6455 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6456 NestedLoopCount, Clauses, AStmt, B);
6457}
6458
Kelvin Lia579b912016-07-14 02:54:56 +00006459StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6460 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6461 SourceLocation EndLoc,
6462 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6463 if (!AStmt)
6464 return StmtError();
6465
6466 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6467 // 1.2.2 OpenMP Language Terminology
6468 // Structured block - An executable statement with a single entry at the
6469 // top and a single exit at the bottom.
6470 // The point of exit cannot be a branch out of the structured block.
6471 // longjmp() and throw() must not violate the entry/exit criteria.
6472 CS->getCapturedDecl()->setNothrow();
6473
6474 OMPLoopDirective::HelperExprs B;
6475 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6476 // define the nested loops number.
6477 unsigned NestedLoopCount = CheckOpenMPLoop(
6478 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6479 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6480 VarsWithImplicitDSA, B);
6481 if (NestedLoopCount == 0)
6482 return StmtError();
6483
6484 assert((CurContext->isDependentContext() || B.builtAll()) &&
6485 "omp target parallel for simd loop exprs were not built");
6486
6487 if (!CurContext->isDependentContext()) {
6488 // Finalize the clauses that need pre-built expressions for CodeGen.
6489 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006490 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006491 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6492 B.NumIterations, *this, CurScope,
6493 DSAStack))
6494 return StmtError();
6495 }
6496 }
Kelvin Lic5609492016-07-15 04:39:07 +00006497 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006498 return StmtError();
6499
6500 getCurFunction()->setHasBranchProtectedScope();
6501 return OMPTargetParallelForSimdDirective::Create(
6502 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6503}
6504
Kelvin Li986330c2016-07-20 22:57:10 +00006505StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6506 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6507 SourceLocation EndLoc,
6508 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6509 if (!AStmt)
6510 return StmtError();
6511
6512 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6513 // 1.2.2 OpenMP Language Terminology
6514 // Structured block - An executable statement with a single entry at the
6515 // top and a single exit at the bottom.
6516 // The point of exit cannot be a branch out of the structured block.
6517 // longjmp() and throw() must not violate the entry/exit criteria.
6518 CS->getCapturedDecl()->setNothrow();
6519
6520 OMPLoopDirective::HelperExprs B;
6521 // In presence of clause 'collapse' with number of loops, it will define the
6522 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006523 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006524 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6525 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6526 VarsWithImplicitDSA, B);
6527 if (NestedLoopCount == 0)
6528 return StmtError();
6529
6530 assert((CurContext->isDependentContext() || B.builtAll()) &&
6531 "omp target simd loop exprs were not built");
6532
6533 if (!CurContext->isDependentContext()) {
6534 // Finalize the clauses that need pre-built expressions for CodeGen.
6535 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006536 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006537 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6538 B.NumIterations, *this, CurScope,
6539 DSAStack))
6540 return StmtError();
6541 }
6542 }
6543
6544 if (checkSimdlenSafelenSpecified(*this, Clauses))
6545 return StmtError();
6546
6547 getCurFunction()->setHasBranchProtectedScope();
6548 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6549 NestedLoopCount, Clauses, AStmt, B);
6550}
6551
Kelvin Li02532872016-08-05 14:37:37 +00006552StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6553 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6554 SourceLocation EndLoc,
6555 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6556 if (!AStmt)
6557 return StmtError();
6558
6559 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6560 // 1.2.2 OpenMP Language Terminology
6561 // Structured block - An executable statement with a single entry at the
6562 // top and a single exit at the bottom.
6563 // The point of exit cannot be a branch out of the structured block.
6564 // longjmp() and throw() must not violate the entry/exit criteria.
6565 CS->getCapturedDecl()->setNothrow();
6566
6567 OMPLoopDirective::HelperExprs B;
6568 // In presence of clause 'collapse' with number of loops, it will
6569 // define the nested loops number.
6570 unsigned NestedLoopCount =
6571 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6572 nullptr /*ordered not a clause on distribute*/, AStmt,
6573 *this, *DSAStack, VarsWithImplicitDSA, B);
6574 if (NestedLoopCount == 0)
6575 return StmtError();
6576
6577 assert((CurContext->isDependentContext() || B.builtAll()) &&
6578 "omp teams distribute loop exprs were not built");
6579
6580 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006581 return OMPTeamsDistributeDirective::Create(
6582 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006583}
6584
Kelvin Li4e325f72016-10-25 12:50:55 +00006585StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6586 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6587 SourceLocation EndLoc,
6588 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6589 if (!AStmt)
6590 return StmtError();
6591
6592 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6593 // 1.2.2 OpenMP Language Terminology
6594 // Structured block - An executable statement with a single entry at the
6595 // top and a single exit at the bottom.
6596 // The point of exit cannot be a branch out of the structured block.
6597 // longjmp() and throw() must not violate the entry/exit criteria.
6598 CS->getCapturedDecl()->setNothrow();
6599
6600 OMPLoopDirective::HelperExprs B;
6601 // In presence of clause 'collapse' with number of loops, it will
6602 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006603 unsigned NestedLoopCount = CheckOpenMPLoop(
6604 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6605 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6606 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006607
6608 if (NestedLoopCount == 0)
6609 return StmtError();
6610
6611 assert((CurContext->isDependentContext() || B.builtAll()) &&
6612 "omp teams distribute simd loop exprs were not built");
6613
6614 if (!CurContext->isDependentContext()) {
6615 // Finalize the clauses that need pre-built expressions for CodeGen.
6616 for (auto C : Clauses) {
6617 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6618 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6619 B.NumIterations, *this, CurScope,
6620 DSAStack))
6621 return StmtError();
6622 }
6623 }
6624
6625 if (checkSimdlenSafelenSpecified(*this, Clauses))
6626 return StmtError();
6627
6628 getCurFunction()->setHasBranchProtectedScope();
6629 return OMPTeamsDistributeSimdDirective::Create(
6630 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6631}
6632
Kelvin Li579e41c2016-11-30 23:51:03 +00006633StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6634 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6635 SourceLocation EndLoc,
6636 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6637 if (!AStmt)
6638 return StmtError();
6639
6640 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6641 // 1.2.2 OpenMP Language Terminology
6642 // Structured block - An executable statement with a single entry at the
6643 // top and a single exit at the bottom.
6644 // The point of exit cannot be a branch out of the structured block.
6645 // longjmp() and throw() must not violate the entry/exit criteria.
6646 CS->getCapturedDecl()->setNothrow();
6647
6648 OMPLoopDirective::HelperExprs B;
6649 // In presence of clause 'collapse' with number of loops, it will
6650 // define the nested loops number.
6651 auto NestedLoopCount = CheckOpenMPLoop(
6652 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6653 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6654 VarsWithImplicitDSA, B);
6655
6656 if (NestedLoopCount == 0)
6657 return StmtError();
6658
6659 assert((CurContext->isDependentContext() || B.builtAll()) &&
6660 "omp for loop exprs were not built");
6661
6662 if (!CurContext->isDependentContext()) {
6663 // Finalize the clauses that need pre-built expressions for CodeGen.
6664 for (auto C : Clauses) {
6665 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6666 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6667 B.NumIterations, *this, CurScope,
6668 DSAStack))
6669 return StmtError();
6670 }
6671 }
6672
6673 if (checkSimdlenSafelenSpecified(*this, Clauses))
6674 return StmtError();
6675
6676 getCurFunction()->setHasBranchProtectedScope();
6677 return OMPTeamsDistributeParallelForSimdDirective::Create(
6678 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6679}
6680
Kelvin Li7ade93f2016-12-09 03:24:30 +00006681StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6682 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6683 SourceLocation EndLoc,
6684 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6685 if (!AStmt)
6686 return StmtError();
6687
6688 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6689 // 1.2.2 OpenMP Language Terminology
6690 // Structured block - An executable statement with a single entry at the
6691 // top and a single exit at the bottom.
6692 // The point of exit cannot be a branch out of the structured block.
6693 // longjmp() and throw() must not violate the entry/exit criteria.
6694 CS->getCapturedDecl()->setNothrow();
6695
6696 OMPLoopDirective::HelperExprs B;
6697 // In presence of clause 'collapse' with number of loops, it will
6698 // define the nested loops number.
6699 unsigned NestedLoopCount = CheckOpenMPLoop(
6700 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6701 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6702 VarsWithImplicitDSA, B);
6703
6704 if (NestedLoopCount == 0)
6705 return StmtError();
6706
6707 assert((CurContext->isDependentContext() || B.builtAll()) &&
6708 "omp for loop exprs were not built");
6709
6710 if (!CurContext->isDependentContext()) {
6711 // Finalize the clauses that need pre-built expressions for CodeGen.
6712 for (auto C : Clauses) {
6713 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6714 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6715 B.NumIterations, *this, CurScope,
6716 DSAStack))
6717 return StmtError();
6718 }
6719 }
6720
6721 getCurFunction()->setHasBranchProtectedScope();
6722 return OMPTeamsDistributeParallelForDirective::Create(
6723 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6724}
6725
Kelvin Libf594a52016-12-17 05:48:59 +00006726StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6727 Stmt *AStmt,
6728 SourceLocation StartLoc,
6729 SourceLocation EndLoc) {
6730 if (!AStmt)
6731 return StmtError();
6732
6733 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6734 // 1.2.2 OpenMP Language Terminology
6735 // Structured block - An executable statement with a single entry at the
6736 // top and a single exit at the bottom.
6737 // The point of exit cannot be a branch out of the structured block.
6738 // longjmp() and throw() must not violate the entry/exit criteria.
6739 CS->getCapturedDecl()->setNothrow();
6740
6741 getCurFunction()->setHasBranchProtectedScope();
6742
6743 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6744 AStmt);
6745}
6746
Kelvin Li83c451e2016-12-25 04:52:54 +00006747StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6749 SourceLocation EndLoc,
6750 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6751 if (!AStmt)
6752 return StmtError();
6753
6754 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6755 // 1.2.2 OpenMP Language Terminology
6756 // Structured block - An executable statement with a single entry at the
6757 // top and a single exit at the bottom.
6758 // The point of exit cannot be a branch out of the structured block.
6759 // longjmp() and throw() must not violate the entry/exit criteria.
6760 CS->getCapturedDecl()->setNothrow();
6761
6762 OMPLoopDirective::HelperExprs B;
6763 // In presence of clause 'collapse' with number of loops, it will
6764 // define the nested loops number.
6765 auto NestedLoopCount = CheckOpenMPLoop(
6766 OMPD_target_teams_distribute,
6767 getCollapseNumberExpr(Clauses),
6768 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6769 VarsWithImplicitDSA, B);
6770 if (NestedLoopCount == 0)
6771 return StmtError();
6772
6773 assert((CurContext->isDependentContext() || B.builtAll()) &&
6774 "omp target teams distribute loop exprs were not built");
6775
6776 getCurFunction()->setHasBranchProtectedScope();
6777 return OMPTargetTeamsDistributeDirective::Create(
6778 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6779}
6780
Kelvin Li80e8f562016-12-29 22:16:30 +00006781StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6782 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6783 SourceLocation EndLoc,
6784 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6785 if (!AStmt)
6786 return StmtError();
6787
6788 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6789 // 1.2.2 OpenMP Language Terminology
6790 // Structured block - An executable statement with a single entry at the
6791 // top and a single exit at the bottom.
6792 // The point of exit cannot be a branch out of the structured block.
6793 // longjmp() and throw() must not violate the entry/exit criteria.
6794 CS->getCapturedDecl()->setNothrow();
6795
6796 OMPLoopDirective::HelperExprs B;
6797 // In presence of clause 'collapse' with number of loops, it will
6798 // define the nested loops number.
6799 auto NestedLoopCount = CheckOpenMPLoop(
6800 OMPD_target_teams_distribute_parallel_for,
6801 getCollapseNumberExpr(Clauses),
6802 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6803 VarsWithImplicitDSA, B);
6804 if (NestedLoopCount == 0)
6805 return StmtError();
6806
6807 assert((CurContext->isDependentContext() || B.builtAll()) &&
6808 "omp target teams distribute parallel for loop exprs were not built");
6809
6810 if (!CurContext->isDependentContext()) {
6811 // Finalize the clauses that need pre-built expressions for CodeGen.
6812 for (auto C : Clauses) {
6813 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6814 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6815 B.NumIterations, *this, CurScope,
6816 DSAStack))
6817 return StmtError();
6818 }
6819 }
6820
6821 getCurFunction()->setHasBranchProtectedScope();
6822 return OMPTargetTeamsDistributeParallelForDirective::Create(
6823 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6824}
6825
Kelvin Li1851df52017-01-03 05:23:48 +00006826StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6827 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6828 SourceLocation EndLoc,
6829 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6830 if (!AStmt)
6831 return StmtError();
6832
6833 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6834 // 1.2.2 OpenMP Language Terminology
6835 // Structured block - An executable statement with a single entry at the
6836 // top and a single exit at the bottom.
6837 // The point of exit cannot be a branch out of the structured block.
6838 // longjmp() and throw() must not violate the entry/exit criteria.
6839 CS->getCapturedDecl()->setNothrow();
6840
6841 OMPLoopDirective::HelperExprs B;
6842 // In presence of clause 'collapse' with number of loops, it will
6843 // define the nested loops number.
6844 auto NestedLoopCount = CheckOpenMPLoop(
6845 OMPD_target_teams_distribute_parallel_for_simd,
6846 getCollapseNumberExpr(Clauses),
6847 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6848 VarsWithImplicitDSA, B);
6849 if (NestedLoopCount == 0)
6850 return StmtError();
6851
6852 assert((CurContext->isDependentContext() || B.builtAll()) &&
6853 "omp target teams distribute parallel for simd loop exprs were not "
6854 "built");
6855
6856 if (!CurContext->isDependentContext()) {
6857 // Finalize the clauses that need pre-built expressions for CodeGen.
6858 for (auto C : Clauses) {
6859 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6860 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6861 B.NumIterations, *this, CurScope,
6862 DSAStack))
6863 return StmtError();
6864 }
6865 }
6866
6867 getCurFunction()->setHasBranchProtectedScope();
6868 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6869 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6870}
6871
Kelvin Lida681182017-01-10 18:08:18 +00006872StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6873 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6874 SourceLocation EndLoc,
6875 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6876 if (!AStmt)
6877 return StmtError();
6878
6879 auto *CS = cast<CapturedStmt>(AStmt);
6880 // 1.2.2 OpenMP Language Terminology
6881 // Structured block - An executable statement with a single entry at the
6882 // top and a single exit at the bottom.
6883 // The point of exit cannot be a branch out of the structured block.
6884 // longjmp() and throw() must not violate the entry/exit criteria.
6885 CS->getCapturedDecl()->setNothrow();
6886
6887 OMPLoopDirective::HelperExprs B;
6888 // In presence of clause 'collapse' with number of loops, it will
6889 // define the nested loops number.
6890 auto NestedLoopCount = CheckOpenMPLoop(
6891 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6892 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6893 VarsWithImplicitDSA, B);
6894 if (NestedLoopCount == 0)
6895 return StmtError();
6896
6897 assert((CurContext->isDependentContext() || B.builtAll()) &&
6898 "omp target teams distribute simd loop exprs were not built");
6899
6900 getCurFunction()->setHasBranchProtectedScope();
6901 return OMPTargetTeamsDistributeSimdDirective::Create(
6902 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6903}
6904
Alexey Bataeved09d242014-05-28 05:53:51 +00006905OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006906 SourceLocation StartLoc,
6907 SourceLocation LParenLoc,
6908 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006909 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006910 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006911 case OMPC_final:
6912 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6913 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006914 case OMPC_num_threads:
6915 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6916 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006917 case OMPC_safelen:
6918 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6919 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006920 case OMPC_simdlen:
6921 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6922 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006923 case OMPC_collapse:
6924 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6925 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006926 case OMPC_ordered:
6927 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6928 break;
Michael Wonge710d542015-08-07 16:16:36 +00006929 case OMPC_device:
6930 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6931 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006932 case OMPC_num_teams:
6933 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6934 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006935 case OMPC_thread_limit:
6936 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6937 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006938 case OMPC_priority:
6939 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6940 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006941 case OMPC_grainsize:
6942 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6943 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006944 case OMPC_num_tasks:
6945 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6946 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006947 case OMPC_hint:
6948 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6949 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006950 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006951 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006952 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006953 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006954 case OMPC_private:
6955 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006956 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006957 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006958 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00006959 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00006960 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006961 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006962 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006963 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006964 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006965 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006966 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006967 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006968 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006969 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006970 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006971 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006972 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006973 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006974 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006975 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006976 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006977 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006978 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006979 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006980 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006981 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006982 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006983 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006984 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006985 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006986 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006987 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006988 llvm_unreachable("Clause is not allowed.");
6989 }
6990 return Res;
6991}
6992
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006993// An OpenMP directive such as 'target parallel' has two captured regions:
6994// for the 'target' and 'parallel' respectively. This function returns
6995// the region in which to capture expressions associated with a clause.
6996// A return value of OMPD_unknown signifies that the expression should not
6997// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006998static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6999 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7000 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007001 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7002
7003 switch (CKind) {
7004 case OMPC_if:
7005 switch (DKind) {
7006 case OMPD_target_parallel:
7007 // If this clause applies to the nested 'parallel' region, capture within
7008 // the 'target' region, otherwise do not capture.
7009 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7010 CaptureRegion = OMPD_target;
7011 break;
7012 case OMPD_cancel:
7013 case OMPD_parallel:
7014 case OMPD_parallel_sections:
7015 case OMPD_parallel_for:
7016 case OMPD_parallel_for_simd:
7017 case OMPD_target:
7018 case OMPD_target_simd:
7019 case OMPD_target_parallel_for:
7020 case OMPD_target_parallel_for_simd:
7021 case OMPD_target_teams:
7022 case OMPD_target_teams_distribute:
7023 case OMPD_target_teams_distribute_simd:
7024 case OMPD_target_teams_distribute_parallel_for:
7025 case OMPD_target_teams_distribute_parallel_for_simd:
7026 case OMPD_teams_distribute_parallel_for:
7027 case OMPD_teams_distribute_parallel_for_simd:
7028 case OMPD_distribute_parallel_for:
7029 case OMPD_distribute_parallel_for_simd:
7030 case OMPD_task:
7031 case OMPD_taskloop:
7032 case OMPD_taskloop_simd:
7033 case OMPD_target_data:
7034 case OMPD_target_enter_data:
7035 case OMPD_target_exit_data:
7036 case OMPD_target_update:
7037 // Do not capture if-clause expressions.
7038 break;
7039 case OMPD_threadprivate:
7040 case OMPD_taskyield:
7041 case OMPD_barrier:
7042 case OMPD_taskwait:
7043 case OMPD_cancellation_point:
7044 case OMPD_flush:
7045 case OMPD_declare_reduction:
7046 case OMPD_declare_simd:
7047 case OMPD_declare_target:
7048 case OMPD_end_declare_target:
7049 case OMPD_teams:
7050 case OMPD_simd:
7051 case OMPD_for:
7052 case OMPD_for_simd:
7053 case OMPD_sections:
7054 case OMPD_section:
7055 case OMPD_single:
7056 case OMPD_master:
7057 case OMPD_critical:
7058 case OMPD_taskgroup:
7059 case OMPD_distribute:
7060 case OMPD_ordered:
7061 case OMPD_atomic:
7062 case OMPD_distribute_simd:
7063 case OMPD_teams_distribute:
7064 case OMPD_teams_distribute_simd:
7065 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7066 case OMPD_unknown:
7067 llvm_unreachable("Unknown OpenMP directive");
7068 }
7069 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007070 case OMPC_num_threads:
7071 switch (DKind) {
7072 case OMPD_target_parallel:
7073 CaptureRegion = OMPD_target;
7074 break;
7075 case OMPD_cancel:
7076 case OMPD_parallel:
7077 case OMPD_parallel_sections:
7078 case OMPD_parallel_for:
7079 case OMPD_parallel_for_simd:
7080 case OMPD_target:
7081 case OMPD_target_simd:
7082 case OMPD_target_parallel_for:
7083 case OMPD_target_parallel_for_simd:
7084 case OMPD_target_teams:
7085 case OMPD_target_teams_distribute:
7086 case OMPD_target_teams_distribute_simd:
7087 case OMPD_target_teams_distribute_parallel_for:
7088 case OMPD_target_teams_distribute_parallel_for_simd:
7089 case OMPD_teams_distribute_parallel_for:
7090 case OMPD_teams_distribute_parallel_for_simd:
7091 case OMPD_distribute_parallel_for:
7092 case OMPD_distribute_parallel_for_simd:
7093 case OMPD_task:
7094 case OMPD_taskloop:
7095 case OMPD_taskloop_simd:
7096 case OMPD_target_data:
7097 case OMPD_target_enter_data:
7098 case OMPD_target_exit_data:
7099 case OMPD_target_update:
7100 // Do not capture num_threads-clause expressions.
7101 break;
7102 case OMPD_threadprivate:
7103 case OMPD_taskyield:
7104 case OMPD_barrier:
7105 case OMPD_taskwait:
7106 case OMPD_cancellation_point:
7107 case OMPD_flush:
7108 case OMPD_declare_reduction:
7109 case OMPD_declare_simd:
7110 case OMPD_declare_target:
7111 case OMPD_end_declare_target:
7112 case OMPD_teams:
7113 case OMPD_simd:
7114 case OMPD_for:
7115 case OMPD_for_simd:
7116 case OMPD_sections:
7117 case OMPD_section:
7118 case OMPD_single:
7119 case OMPD_master:
7120 case OMPD_critical:
7121 case OMPD_taskgroup:
7122 case OMPD_distribute:
7123 case OMPD_ordered:
7124 case OMPD_atomic:
7125 case OMPD_distribute_simd:
7126 case OMPD_teams_distribute:
7127 case OMPD_teams_distribute_simd:
7128 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7129 case OMPD_unknown:
7130 llvm_unreachable("Unknown OpenMP directive");
7131 }
7132 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007133 case OMPC_num_teams:
7134 switch (DKind) {
7135 case OMPD_target_teams:
7136 CaptureRegion = OMPD_target;
7137 break;
7138 case OMPD_cancel:
7139 case OMPD_parallel:
7140 case OMPD_parallel_sections:
7141 case OMPD_parallel_for:
7142 case OMPD_parallel_for_simd:
7143 case OMPD_target:
7144 case OMPD_target_simd:
7145 case OMPD_target_parallel:
7146 case OMPD_target_parallel_for:
7147 case OMPD_target_parallel_for_simd:
7148 case OMPD_target_teams_distribute:
7149 case OMPD_target_teams_distribute_simd:
7150 case OMPD_target_teams_distribute_parallel_for:
7151 case OMPD_target_teams_distribute_parallel_for_simd:
7152 case OMPD_teams_distribute_parallel_for:
7153 case OMPD_teams_distribute_parallel_for_simd:
7154 case OMPD_distribute_parallel_for:
7155 case OMPD_distribute_parallel_for_simd:
7156 case OMPD_task:
7157 case OMPD_taskloop:
7158 case OMPD_taskloop_simd:
7159 case OMPD_target_data:
7160 case OMPD_target_enter_data:
7161 case OMPD_target_exit_data:
7162 case OMPD_target_update:
7163 case OMPD_teams:
7164 case OMPD_teams_distribute:
7165 case OMPD_teams_distribute_simd:
7166 // Do not capture num_teams-clause expressions.
7167 break;
7168 case OMPD_threadprivate:
7169 case OMPD_taskyield:
7170 case OMPD_barrier:
7171 case OMPD_taskwait:
7172 case OMPD_cancellation_point:
7173 case OMPD_flush:
7174 case OMPD_declare_reduction:
7175 case OMPD_declare_simd:
7176 case OMPD_declare_target:
7177 case OMPD_end_declare_target:
7178 case OMPD_simd:
7179 case OMPD_for:
7180 case OMPD_for_simd:
7181 case OMPD_sections:
7182 case OMPD_section:
7183 case OMPD_single:
7184 case OMPD_master:
7185 case OMPD_critical:
7186 case OMPD_taskgroup:
7187 case OMPD_distribute:
7188 case OMPD_ordered:
7189 case OMPD_atomic:
7190 case OMPD_distribute_simd:
7191 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7192 case OMPD_unknown:
7193 llvm_unreachable("Unknown OpenMP directive");
7194 }
7195 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007196 case OMPC_thread_limit:
7197 switch (DKind) {
7198 case OMPD_target_teams:
7199 CaptureRegion = OMPD_target;
7200 break;
7201 case OMPD_cancel:
7202 case OMPD_parallel:
7203 case OMPD_parallel_sections:
7204 case OMPD_parallel_for:
7205 case OMPD_parallel_for_simd:
7206 case OMPD_target:
7207 case OMPD_target_simd:
7208 case OMPD_target_parallel:
7209 case OMPD_target_parallel_for:
7210 case OMPD_target_parallel_for_simd:
7211 case OMPD_target_teams_distribute:
7212 case OMPD_target_teams_distribute_simd:
7213 case OMPD_target_teams_distribute_parallel_for:
7214 case OMPD_target_teams_distribute_parallel_for_simd:
7215 case OMPD_teams_distribute_parallel_for:
7216 case OMPD_teams_distribute_parallel_for_simd:
7217 case OMPD_distribute_parallel_for:
7218 case OMPD_distribute_parallel_for_simd:
7219 case OMPD_task:
7220 case OMPD_taskloop:
7221 case OMPD_taskloop_simd:
7222 case OMPD_target_data:
7223 case OMPD_target_enter_data:
7224 case OMPD_target_exit_data:
7225 case OMPD_target_update:
7226 case OMPD_teams:
7227 case OMPD_teams_distribute:
7228 case OMPD_teams_distribute_simd:
7229 // Do not capture thread_limit-clause expressions.
7230 break;
7231 case OMPD_threadprivate:
7232 case OMPD_taskyield:
7233 case OMPD_barrier:
7234 case OMPD_taskwait:
7235 case OMPD_cancellation_point:
7236 case OMPD_flush:
7237 case OMPD_declare_reduction:
7238 case OMPD_declare_simd:
7239 case OMPD_declare_target:
7240 case OMPD_end_declare_target:
7241 case OMPD_simd:
7242 case OMPD_for:
7243 case OMPD_for_simd:
7244 case OMPD_sections:
7245 case OMPD_section:
7246 case OMPD_single:
7247 case OMPD_master:
7248 case OMPD_critical:
7249 case OMPD_taskgroup:
7250 case OMPD_distribute:
7251 case OMPD_ordered:
7252 case OMPD_atomic:
7253 case OMPD_distribute_simd:
7254 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7255 case OMPD_unknown:
7256 llvm_unreachable("Unknown OpenMP directive");
7257 }
7258 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007259 case OMPC_schedule:
7260 case OMPC_dist_schedule:
7261 case OMPC_firstprivate:
7262 case OMPC_lastprivate:
7263 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007264 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007265 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007266 case OMPC_linear:
7267 case OMPC_default:
7268 case OMPC_proc_bind:
7269 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007270 case OMPC_safelen:
7271 case OMPC_simdlen:
7272 case OMPC_collapse:
7273 case OMPC_private:
7274 case OMPC_shared:
7275 case OMPC_aligned:
7276 case OMPC_copyin:
7277 case OMPC_copyprivate:
7278 case OMPC_ordered:
7279 case OMPC_nowait:
7280 case OMPC_untied:
7281 case OMPC_mergeable:
7282 case OMPC_threadprivate:
7283 case OMPC_flush:
7284 case OMPC_read:
7285 case OMPC_write:
7286 case OMPC_update:
7287 case OMPC_capture:
7288 case OMPC_seq_cst:
7289 case OMPC_depend:
7290 case OMPC_device:
7291 case OMPC_threads:
7292 case OMPC_simd:
7293 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007294 case OMPC_priority:
7295 case OMPC_grainsize:
7296 case OMPC_nogroup:
7297 case OMPC_num_tasks:
7298 case OMPC_hint:
7299 case OMPC_defaultmap:
7300 case OMPC_unknown:
7301 case OMPC_uniform:
7302 case OMPC_to:
7303 case OMPC_from:
7304 case OMPC_use_device_ptr:
7305 case OMPC_is_device_ptr:
7306 llvm_unreachable("Unexpected OpenMP clause.");
7307 }
7308 return CaptureRegion;
7309}
7310
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007311OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7312 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007313 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007314 SourceLocation NameModifierLoc,
7315 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007316 SourceLocation EndLoc) {
7317 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007318 Stmt *HelperValStmt = nullptr;
7319 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007320 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7321 !Condition->isInstantiationDependent() &&
7322 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007323 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007324 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007325 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007326
Richard Smith03a4aa32016-06-23 19:02:52 +00007327 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007328
7329 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7330 CaptureRegion =
7331 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7332 if (CaptureRegion != OMPD_unknown) {
7333 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7334 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7335 HelperValStmt = buildPreInits(Context, Captures);
7336 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007337 }
7338
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007339 return new (Context)
7340 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7341 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007342}
7343
Alexey Bataev3778b602014-07-17 07:32:53 +00007344OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7345 SourceLocation StartLoc,
7346 SourceLocation LParenLoc,
7347 SourceLocation EndLoc) {
7348 Expr *ValExpr = Condition;
7349 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7350 !Condition->isInstantiationDependent() &&
7351 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007352 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007353 if (Val.isInvalid())
7354 return nullptr;
7355
Richard Smith03a4aa32016-06-23 19:02:52 +00007356 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007357 }
7358
7359 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7360}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007361ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7362 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007363 if (!Op)
7364 return ExprError();
7365
7366 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7367 public:
7368 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007369 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007370 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7371 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007372 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7373 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007374 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7375 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007376 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7377 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007378 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7379 QualType T,
7380 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007381 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7382 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007383 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7384 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007385 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007386 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007387 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007388 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7389 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007390 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7391 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007392 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7393 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007394 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007395 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007396 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007397 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7398 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007399 llvm_unreachable("conversion functions are permitted");
7400 }
7401 } ConvertDiagnoser;
7402 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7403}
7404
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007405static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007406 OpenMPClauseKind CKind,
7407 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007408 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7409 !ValExpr->isInstantiationDependent()) {
7410 SourceLocation Loc = ValExpr->getExprLoc();
7411 ExprResult Value =
7412 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7413 if (Value.isInvalid())
7414 return false;
7415
7416 ValExpr = Value.get();
7417 // The expression must evaluate to a non-negative integer value.
7418 llvm::APSInt Result;
7419 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007420 Result.isSigned() &&
7421 !((!StrictlyPositive && Result.isNonNegative()) ||
7422 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007423 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007424 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7425 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007426 return false;
7427 }
7428 }
7429 return true;
7430}
7431
Alexey Bataev568a8332014-03-06 06:15:19 +00007432OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7433 SourceLocation StartLoc,
7434 SourceLocation LParenLoc,
7435 SourceLocation EndLoc) {
7436 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007437 Stmt *HelperValStmt = nullptr;
7438 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007439
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007440 // OpenMP [2.5, Restrictions]
7441 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007442 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7443 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007444 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007445
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007446 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7447 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7448 if (CaptureRegion != OMPD_unknown) {
7449 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7450 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7451 HelperValStmt = buildPreInits(Context, Captures);
7452 }
7453
7454 return new (Context) OMPNumThreadsClause(
7455 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007456}
7457
Alexey Bataev62c87d22014-03-21 04:51:18 +00007458ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007459 OpenMPClauseKind CKind,
7460 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007461 if (!E)
7462 return ExprError();
7463 if (E->isValueDependent() || E->isTypeDependent() ||
7464 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007465 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007466 llvm::APSInt Result;
7467 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7468 if (ICE.isInvalid())
7469 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007470 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7471 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007472 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007473 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7474 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007475 return ExprError();
7476 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007477 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7478 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7479 << E->getSourceRange();
7480 return ExprError();
7481 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007482 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7483 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007484 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007485 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007486 return ICE;
7487}
7488
7489OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7490 SourceLocation LParenLoc,
7491 SourceLocation EndLoc) {
7492 // OpenMP [2.8.1, simd construct, Description]
7493 // The parameter of the safelen clause must be a constant
7494 // positive integer expression.
7495 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7496 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007497 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007498 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007499 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007500}
7501
Alexey Bataev66b15b52015-08-21 11:14:16 +00007502OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7503 SourceLocation LParenLoc,
7504 SourceLocation EndLoc) {
7505 // OpenMP [2.8.1, simd construct, Description]
7506 // The parameter of the simdlen clause must be a constant
7507 // positive integer expression.
7508 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7509 if (Simdlen.isInvalid())
7510 return nullptr;
7511 return new (Context)
7512 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7513}
7514
Alexander Musman64d33f12014-06-04 07:53:32 +00007515OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7516 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007517 SourceLocation LParenLoc,
7518 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007519 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007520 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007521 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007522 // The parameter of the collapse clause must be a constant
7523 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007524 ExprResult NumForLoopsResult =
7525 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7526 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007527 return nullptr;
7528 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007529 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007530}
7531
Alexey Bataev10e775f2015-07-30 11:36:16 +00007532OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7533 SourceLocation EndLoc,
7534 SourceLocation LParenLoc,
7535 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007536 // OpenMP [2.7.1, loop construct, Description]
7537 // OpenMP [2.8.1, simd construct, Description]
7538 // OpenMP [2.9.6, distribute construct, Description]
7539 // The parameter of the ordered clause must be a constant
7540 // positive integer expression if any.
7541 if (NumForLoops && LParenLoc.isValid()) {
7542 ExprResult NumForLoopsResult =
7543 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7544 if (NumForLoopsResult.isInvalid())
7545 return nullptr;
7546 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007547 } else
7548 NumForLoops = nullptr;
7549 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007550 return new (Context)
7551 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7552}
7553
Alexey Bataeved09d242014-05-28 05:53:51 +00007554OMPClause *Sema::ActOnOpenMPSimpleClause(
7555 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7556 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007557 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007558 switch (Kind) {
7559 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007560 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007561 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7562 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007563 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007564 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007565 Res = ActOnOpenMPProcBindClause(
7566 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7567 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007568 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007569 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007570 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007571 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007572 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007573 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007574 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007575 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007576 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007577 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007578 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007579 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007580 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007581 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007582 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007583 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007584 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007585 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007586 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007587 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007588 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007589 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007590 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007591 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007592 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007593 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007594 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007595 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007596 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007597 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007598 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007599 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007600 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007601 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007602 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007603 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007604 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007605 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007606 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007607 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007608 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007609 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007610 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007611 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007612 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007613 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007614 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007615 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007616 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007617 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007618 llvm_unreachable("Clause is not allowed.");
7619 }
7620 return Res;
7621}
7622
Alexey Bataev6402bca2015-12-28 07:25:51 +00007623static std::string
7624getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7625 ArrayRef<unsigned> Exclude = llvm::None) {
7626 std::string Values;
7627 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7628 unsigned Skipped = Exclude.size();
7629 auto S = Exclude.begin(), E = Exclude.end();
7630 for (unsigned i = First; i < Last; ++i) {
7631 if (std::find(S, E, i) != E) {
7632 --Skipped;
7633 continue;
7634 }
7635 Values += "'";
7636 Values += getOpenMPSimpleClauseTypeName(K, i);
7637 Values += "'";
7638 if (i == Bound - Skipped)
7639 Values += " or ";
7640 else if (i != Bound + 1 - Skipped)
7641 Values += ", ";
7642 }
7643 return Values;
7644}
7645
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007646OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7647 SourceLocation KindKwLoc,
7648 SourceLocation StartLoc,
7649 SourceLocation LParenLoc,
7650 SourceLocation EndLoc) {
7651 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007652 static_assert(OMPC_DEFAULT_unknown > 0,
7653 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007654 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007655 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7656 /*Last=*/OMPC_DEFAULT_unknown)
7657 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007658 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007659 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007660 switch (Kind) {
7661 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007662 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007663 break;
7664 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007665 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007666 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007667 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007668 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007669 break;
7670 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007671 return new (Context)
7672 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007673}
7674
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007675OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7676 SourceLocation KindKwLoc,
7677 SourceLocation StartLoc,
7678 SourceLocation LParenLoc,
7679 SourceLocation EndLoc) {
7680 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007681 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007682 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7683 /*Last=*/OMPC_PROC_BIND_unknown)
7684 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007685 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007686 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007687 return new (Context)
7688 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007689}
7690
Alexey Bataev56dafe82014-06-20 07:16:17 +00007691OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007692 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007693 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007694 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007695 SourceLocation EndLoc) {
7696 OMPClause *Res = nullptr;
7697 switch (Kind) {
7698 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007699 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7700 assert(Argument.size() == NumberOfElements &&
7701 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007702 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007703 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7704 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7705 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7706 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7707 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007708 break;
7709 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007710 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7711 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7712 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7713 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007714 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007715 case OMPC_dist_schedule:
7716 Res = ActOnOpenMPDistScheduleClause(
7717 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7718 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7719 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007720 case OMPC_defaultmap:
7721 enum { Modifier, DefaultmapKind };
7722 Res = ActOnOpenMPDefaultmapClause(
7723 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7724 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007725 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7726 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007727 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007728 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007729 case OMPC_num_threads:
7730 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007731 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007732 case OMPC_collapse:
7733 case OMPC_default:
7734 case OMPC_proc_bind:
7735 case OMPC_private:
7736 case OMPC_firstprivate:
7737 case OMPC_lastprivate:
7738 case OMPC_shared:
7739 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007740 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007741 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007742 case OMPC_linear:
7743 case OMPC_aligned:
7744 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007745 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007746 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007747 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007748 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007749 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007750 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007751 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007752 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007753 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007754 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007755 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007756 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007757 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007758 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007759 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007760 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007761 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007762 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007763 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007764 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007765 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007766 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007767 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007768 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007769 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007770 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007771 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007772 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007773 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007774 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007775 llvm_unreachable("Clause is not allowed.");
7776 }
7777 return Res;
7778}
7779
Alexey Bataev6402bca2015-12-28 07:25:51 +00007780static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7781 OpenMPScheduleClauseModifier M2,
7782 SourceLocation M1Loc, SourceLocation M2Loc) {
7783 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7784 SmallVector<unsigned, 2> Excluded;
7785 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7786 Excluded.push_back(M2);
7787 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7788 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7789 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7790 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7791 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7792 << getListOfPossibleValues(OMPC_schedule,
7793 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7794 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7795 Excluded)
7796 << getOpenMPClauseName(OMPC_schedule);
7797 return true;
7798 }
7799 return false;
7800}
7801
Alexey Bataev56dafe82014-06-20 07:16:17 +00007802OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007803 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007804 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007805 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7806 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7807 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7808 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7809 return nullptr;
7810 // OpenMP, 2.7.1, Loop Construct, Restrictions
7811 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7812 // but not both.
7813 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7814 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7815 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7816 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7817 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7818 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7819 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7820 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7821 return nullptr;
7822 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007823 if (Kind == OMPC_SCHEDULE_unknown) {
7824 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007825 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7826 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7827 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7828 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7829 Exclude);
7830 } else {
7831 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7832 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007833 }
7834 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7835 << Values << getOpenMPClauseName(OMPC_schedule);
7836 return nullptr;
7837 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007838 // OpenMP, 2.7.1, Loop Construct, Restrictions
7839 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7840 // schedule(guided).
7841 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7842 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7843 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7844 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7845 diag::err_omp_schedule_nonmonotonic_static);
7846 return nullptr;
7847 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007848 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007849 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007850 if (ChunkSize) {
7851 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7852 !ChunkSize->isInstantiationDependent() &&
7853 !ChunkSize->containsUnexpandedParameterPack()) {
7854 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7855 ExprResult Val =
7856 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7857 if (Val.isInvalid())
7858 return nullptr;
7859
7860 ValExpr = Val.get();
7861
7862 // OpenMP [2.7.1, Restrictions]
7863 // chunk_size must be a loop invariant integer expression with a positive
7864 // value.
7865 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007866 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7867 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7868 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007869 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007870 return nullptr;
7871 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007872 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7873 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007874 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7875 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7876 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007877 }
7878 }
7879 }
7880
Alexey Bataev6402bca2015-12-28 07:25:51 +00007881 return new (Context)
7882 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007883 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007884}
7885
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007886OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7887 SourceLocation StartLoc,
7888 SourceLocation EndLoc) {
7889 OMPClause *Res = nullptr;
7890 switch (Kind) {
7891 case OMPC_ordered:
7892 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7893 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007894 case OMPC_nowait:
7895 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7896 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007897 case OMPC_untied:
7898 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7899 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007900 case OMPC_mergeable:
7901 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7902 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007903 case OMPC_read:
7904 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7905 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007906 case OMPC_write:
7907 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7908 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007909 case OMPC_update:
7910 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7911 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007912 case OMPC_capture:
7913 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7914 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007915 case OMPC_seq_cst:
7916 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7917 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007918 case OMPC_threads:
7919 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7920 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007921 case OMPC_simd:
7922 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7923 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007924 case OMPC_nogroup:
7925 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7926 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007927 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007928 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007929 case OMPC_num_threads:
7930 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007931 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007932 case OMPC_collapse:
7933 case OMPC_schedule:
7934 case OMPC_private:
7935 case OMPC_firstprivate:
7936 case OMPC_lastprivate:
7937 case OMPC_shared:
7938 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007939 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007940 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007941 case OMPC_linear:
7942 case OMPC_aligned:
7943 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007944 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007945 case OMPC_default:
7946 case OMPC_proc_bind:
7947 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007948 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007949 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007950 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007951 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007952 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007953 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007954 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007955 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007956 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007957 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007958 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007959 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007960 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007961 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007962 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007963 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007964 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007965 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007966 llvm_unreachable("Clause is not allowed.");
7967 }
7968 return Res;
7969}
7970
Alexey Bataev236070f2014-06-20 11:19:47 +00007971OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7972 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007973 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007974 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7975}
7976
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007977OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7978 SourceLocation EndLoc) {
7979 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7980}
7981
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007982OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7983 SourceLocation EndLoc) {
7984 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7985}
7986
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007987OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7988 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007989 return new (Context) OMPReadClause(StartLoc, EndLoc);
7990}
7991
Alexey Bataevdea47612014-07-23 07:46:59 +00007992OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7993 SourceLocation EndLoc) {
7994 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7995}
7996
Alexey Bataev67a4f222014-07-23 10:25:33 +00007997OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7998 SourceLocation EndLoc) {
7999 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8000}
8001
Alexey Bataev459dec02014-07-24 06:46:57 +00008002OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8003 SourceLocation EndLoc) {
8004 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8005}
8006
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008007OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8008 SourceLocation EndLoc) {
8009 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8010}
8011
Alexey Bataev346265e2015-09-25 10:37:12 +00008012OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8013 SourceLocation EndLoc) {
8014 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8015}
8016
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008017OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8018 SourceLocation EndLoc) {
8019 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8020}
8021
Alexey Bataevb825de12015-12-07 10:51:44 +00008022OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8023 SourceLocation EndLoc) {
8024 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8025}
8026
Alexey Bataevc5e02582014-06-16 07:08:35 +00008027OMPClause *Sema::ActOnOpenMPVarListClause(
8028 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8029 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8030 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008031 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008032 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8033 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8034 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008035 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008036 switch (Kind) {
8037 case OMPC_private:
8038 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8039 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008040 case OMPC_firstprivate:
8041 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8042 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008043 case OMPC_lastprivate:
8044 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8045 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008046 case OMPC_shared:
8047 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8048 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008049 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008050 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8051 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008052 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008053 case OMPC_task_reduction:
8054 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8055 EndLoc, ReductionIdScopeSpec,
8056 ReductionId);
8057 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008058 case OMPC_in_reduction:
8059 Res =
8060 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8061 EndLoc, ReductionIdScopeSpec, ReductionId);
8062 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008063 case OMPC_linear:
8064 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008065 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008066 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008067 case OMPC_aligned:
8068 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8069 ColonLoc, EndLoc);
8070 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008071 case OMPC_copyin:
8072 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8073 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008074 case OMPC_copyprivate:
8075 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8076 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008077 case OMPC_flush:
8078 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8079 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008080 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008081 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008082 StartLoc, LParenLoc, EndLoc);
8083 break;
8084 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008085 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8086 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8087 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008088 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008089 case OMPC_to:
8090 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8091 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008092 case OMPC_from:
8093 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8094 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008095 case OMPC_use_device_ptr:
8096 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8097 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008098 case OMPC_is_device_ptr:
8099 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8100 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008101 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008102 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008103 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008104 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008105 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008106 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008107 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008108 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008109 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008110 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008111 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008112 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008113 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008114 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008115 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008116 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008117 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008118 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008119 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008120 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008121 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008122 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008123 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008124 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008125 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008126 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008127 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008128 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008129 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008130 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008131 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008132 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008133 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008134 llvm_unreachable("Clause is not allowed.");
8135 }
8136 return Res;
8137}
8138
Alexey Bataev90c228f2016-02-08 09:29:13 +00008139ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008140 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008141 ExprResult Res = BuildDeclRefExpr(
8142 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8143 if (!Res.isUsable())
8144 return ExprError();
8145 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8146 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8147 if (!Res.isUsable())
8148 return ExprError();
8149 }
8150 if (VK != VK_LValue && Res.get()->isGLValue()) {
8151 Res = DefaultLvalueConversion(Res.get());
8152 if (!Res.isUsable())
8153 return ExprError();
8154 }
8155 return Res;
8156}
8157
Alexey Bataev60da77e2016-02-29 05:54:20 +00008158static std::pair<ValueDecl *, bool>
8159getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8160 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008161 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8162 RefExpr->containsUnexpandedParameterPack())
8163 return std::make_pair(nullptr, true);
8164
Alexey Bataevd985eda2016-02-10 11:29:16 +00008165 // OpenMP [3.1, C/C++]
8166 // A list item is a variable name.
8167 // OpenMP [2.9.3.3, Restrictions, p.1]
8168 // A variable that is part of another variable (as an array or
8169 // structure element) cannot appear in a private clause.
8170 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008171 enum {
8172 NoArrayExpr = -1,
8173 ArraySubscript = 0,
8174 OMPArraySection = 1
8175 } IsArrayExpr = NoArrayExpr;
8176 if (AllowArraySection) {
8177 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8178 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8179 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8180 Base = TempASE->getBase()->IgnoreParenImpCasts();
8181 RefExpr = Base;
8182 IsArrayExpr = ArraySubscript;
8183 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8184 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8185 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8186 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8187 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8188 Base = TempASE->getBase()->IgnoreParenImpCasts();
8189 RefExpr = Base;
8190 IsArrayExpr = OMPArraySection;
8191 }
8192 }
8193 ELoc = RefExpr->getExprLoc();
8194 ERange = RefExpr->getSourceRange();
8195 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008196 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8197 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8198 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8199 (S.getCurrentThisType().isNull() || !ME ||
8200 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8201 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008202 if (IsArrayExpr != NoArrayExpr)
8203 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8204 << ERange;
8205 else {
8206 S.Diag(ELoc,
8207 AllowArraySection
8208 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8209 : diag::err_omp_expected_var_name_member_expr)
8210 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8211 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008212 return std::make_pair(nullptr, false);
8213 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008214 return std::make_pair(
8215 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008216}
8217
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008218OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8219 SourceLocation StartLoc,
8220 SourceLocation LParenLoc,
8221 SourceLocation EndLoc) {
8222 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008223 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008224 for (auto &RefExpr : VarList) {
8225 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008226 SourceLocation ELoc;
8227 SourceRange ERange;
8228 Expr *SimpleRefExpr = RefExpr;
8229 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008230 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008231 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008232 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008233 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008234 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008235 ValueDecl *D = Res.first;
8236 if (!D)
8237 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008238
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008239 QualType Type = D->getType();
8240 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008241
8242 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8243 // A variable that appears in a private clause must not have an incomplete
8244 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008245 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008246 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008247 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008248
Alexey Bataev758e55e2013-09-06 18:03:48 +00008249 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8250 // in a Construct]
8251 // Variables with the predetermined data-sharing attributes may not be
8252 // listed in data-sharing attributes clauses, except for the cases
8253 // listed below. For these exceptions only, listing a predetermined
8254 // variable in a data-sharing attribute clause is allowed and overrides
8255 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008256 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008257 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008258 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8259 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008260 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008261 continue;
8262 }
8263
Kelvin Libf594a52016-12-17 05:48:59 +00008264 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008265 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008266 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008267 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008268 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8269 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008270 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008271 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008272 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008273 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008274 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008275 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008276 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008277 continue;
8278 }
8279
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008280 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8281 // A list item cannot appear in both a map clause and a data-sharing
8282 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008283 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008284 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008285 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008286 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008287 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008288 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008289 CurrDir == OMPD_target_parallel_for_simd ||
8290 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008291 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008292 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008293 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008294 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8295 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8296 ConflictKind = WhereFoundClauseKind;
8297 return true;
8298 })) {
8299 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008300 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008301 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008302 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008303 ReportOriginalDSA(*this, DSAStack, D, DVar);
8304 continue;
8305 }
8306 }
8307
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008308 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8309 // A variable of class type (or array thereof) that appears in a private
8310 // clause requires an accessible, unambiguous default constructor for the
8311 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008312 // Generate helper private variable and initialize it with the default
8313 // value. The address of the original variable is replaced by the address of
8314 // the new private variable in CodeGen. This new variable is not added to
8315 // IdResolver, so the code in the OpenMP region uses original variable for
8316 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008317 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008318 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8319 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008320 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008321 if (VDPrivate->isInvalidDecl())
8322 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008323 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008324 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008325
Alexey Bataev90c228f2016-02-08 09:29:13 +00008326 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008327 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008328 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008329 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008330 Vars.push_back((VD || CurContext->isDependentContext())
8331 ? RefExpr->IgnoreParens()
8332 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008333 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008334 }
8335
Alexey Bataeved09d242014-05-28 05:53:51 +00008336 if (Vars.empty())
8337 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008338
Alexey Bataev03b340a2014-10-21 03:16:40 +00008339 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8340 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008341}
8342
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008343namespace {
8344class DiagsUninitializedSeveretyRAII {
8345private:
8346 DiagnosticsEngine &Diags;
8347 SourceLocation SavedLoc;
8348 bool IsIgnored;
8349
8350public:
8351 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8352 bool IsIgnored)
8353 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8354 if (!IsIgnored) {
8355 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8356 /*Map*/ diag::Severity::Ignored, Loc);
8357 }
8358 }
8359 ~DiagsUninitializedSeveretyRAII() {
8360 if (!IsIgnored)
8361 Diags.popMappings(SavedLoc);
8362 }
8363};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008364}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008365
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008366OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8367 SourceLocation StartLoc,
8368 SourceLocation LParenLoc,
8369 SourceLocation EndLoc) {
8370 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008371 SmallVector<Expr *, 8> PrivateCopies;
8372 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008373 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008374 bool IsImplicitClause =
8375 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8376 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8377
Alexey Bataeved09d242014-05-28 05:53:51 +00008378 for (auto &RefExpr : VarList) {
8379 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008380 SourceLocation ELoc;
8381 SourceRange ERange;
8382 Expr *SimpleRefExpr = RefExpr;
8383 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008384 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008385 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008386 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008387 PrivateCopies.push_back(nullptr);
8388 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008389 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008390 ValueDecl *D = Res.first;
8391 if (!D)
8392 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008393
Alexey Bataev60da77e2016-02-29 05:54:20 +00008394 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008395 QualType Type = D->getType();
8396 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008397
8398 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8399 // A variable that appears in a private clause must not have an incomplete
8400 // type or a reference type.
8401 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008402 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008403 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008404 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008405
8406 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8407 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008408 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008409 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008410 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008411
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008412 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008413 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008414 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008415 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008416 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008417 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008418 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008419 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8420 // A list item that specifies a given variable may not appear in more
8421 // than one clause on the same directive, except that a variable may be
8422 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008423 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8424 // A list item may appear in a firstprivate or lastprivate clause but not
8425 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008426 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008427 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8428 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008429 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008430 << getOpenMPClauseName(DVar.CKind)
8431 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008432 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008433 continue;
8434 }
8435
8436 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8437 // in a Construct]
8438 // Variables with the predetermined data-sharing attributes may not be
8439 // listed in data-sharing attributes clauses, except for the cases
8440 // listed below. For these exceptions only, listing a predetermined
8441 // variable in a data-sharing attribute clause is allowed and overrides
8442 // the variable's predetermined data-sharing attributes.
8443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8444 // in a Construct, C/C++, p.2]
8445 // Variables with const-qualified type having no mutable member may be
8446 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008447 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008448 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8449 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008450 << getOpenMPClauseName(DVar.CKind)
8451 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008452 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008453 continue;
8454 }
8455
8456 // OpenMP [2.9.3.4, Restrictions, p.2]
8457 // A list item that is private within a parallel region must not appear
8458 // in a firstprivate clause on a worksharing construct if any of the
8459 // worksharing regions arising from the worksharing construct ever bind
8460 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008461 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8462 // A list item that is private within a teams region must not appear in a
8463 // firstprivate clause on a distribute construct if any of the distribute
8464 // regions arising from the distribute construct ever bind to any of the
8465 // teams regions arising from the teams construct.
8466 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8467 // A list item that appears in a reduction clause of a teams construct
8468 // must not appear in a firstprivate clause on a distribute construct if
8469 // any of the distribute regions arising from the distribute construct
8470 // ever bind to any of the teams regions arising from the teams construct.
8471 if ((isOpenMPWorksharingDirective(CurrDir) ||
8472 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008473 !isOpenMPParallelDirective(CurrDir) &&
8474 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008475 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008476 if (DVar.CKind != OMPC_shared &&
8477 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008478 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008479 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008480 Diag(ELoc, diag::err_omp_required_access)
8481 << getOpenMPClauseName(OMPC_firstprivate)
8482 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008483 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008484 continue;
8485 }
8486 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008487 // OpenMP [2.9.3.4, Restrictions, p.3]
8488 // A list item that appears in a reduction clause of a parallel construct
8489 // must not appear in a firstprivate clause on a worksharing or task
8490 // construct if any of the worksharing or task regions arising from the
8491 // worksharing or task construct ever bind to any of the parallel regions
8492 // arising from the parallel construct.
8493 // OpenMP [2.9.3.4, Restrictions, p.4]
8494 // A list item that appears in a reduction clause in worksharing
8495 // construct must not appear in a firstprivate clause in a task construct
8496 // encountered during execution of any of the worksharing regions arising
8497 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008498 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008499 DVar = DSAStack->hasInnermostDSA(
8500 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8501 [](OpenMPDirectiveKind K) -> bool {
8502 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008503 isOpenMPWorksharingDirective(K) ||
8504 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008505 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008506 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008507 if (DVar.CKind == OMPC_reduction &&
8508 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008509 isOpenMPWorksharingDirective(DVar.DKind) ||
8510 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008511 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8512 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008513 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008514 continue;
8515 }
8516 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008517
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008518 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8519 // A list item cannot appear in both a map clause and a data-sharing
8520 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008521 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008522 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008523 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008524 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008525 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008526 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008527 CurrDir == OMPD_target_parallel_for_simd ||
8528 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008529 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008530 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008531 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008532 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8533 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8534 ConflictKind = WhereFoundClauseKind;
8535 return true;
8536 })) {
8537 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008538 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008539 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008540 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8541 ReportOriginalDSA(*this, DSAStack, D, DVar);
8542 continue;
8543 }
8544 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008545 }
8546
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008547 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008548 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008549 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008550 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8551 << getOpenMPClauseName(OMPC_firstprivate) << Type
8552 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8553 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008554 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008555 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008556 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008557 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008558 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008559 continue;
8560 }
8561
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008562 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008563 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8564 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008565 // Generate helper private variable and initialize it with the value of the
8566 // original variable. The address of the original variable is replaced by
8567 // the address of the new private variable in the CodeGen. This new variable
8568 // is not added to IdResolver, so the code in the OpenMP region uses
8569 // original variable for proper diagnostics and variable capturing.
8570 Expr *VDInitRefExpr = nullptr;
8571 // For arrays generate initializer for single element and replace it by the
8572 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008573 if (Type->isArrayType()) {
8574 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008575 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008576 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008577 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008578 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008579 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008580 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008581 InitializedEntity Entity =
8582 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008583 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8584
8585 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8586 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8587 if (Result.isInvalid())
8588 VDPrivate->setInvalidDecl();
8589 else
8590 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008591 // Remove temp variable declaration.
8592 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008593 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008594 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8595 ".firstprivate.temp");
8596 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8597 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008598 AddInitializerToDecl(VDPrivate,
8599 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008600 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008601 }
8602 if (VDPrivate->isInvalidDecl()) {
8603 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008604 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008605 diag::note_omp_task_predetermined_firstprivate_here);
8606 }
8607 continue;
8608 }
8609 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008610 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008611 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8612 RefExpr->getExprLoc());
8613 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008614 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008615 if (TopDVar.CKind == OMPC_lastprivate)
8616 Ref = TopDVar.PrivateCopy;
8617 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008618 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008619 if (!IsOpenMPCapturedDecl(D))
8620 ExprCaptures.push_back(Ref->getDecl());
8621 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008622 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008623 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008624 Vars.push_back((VD || CurContext->isDependentContext())
8625 ? RefExpr->IgnoreParens()
8626 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008627 PrivateCopies.push_back(VDPrivateRefExpr);
8628 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008629 }
8630
Alexey Bataeved09d242014-05-28 05:53:51 +00008631 if (Vars.empty())
8632 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008633
8634 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008635 Vars, PrivateCopies, Inits,
8636 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008637}
8638
Alexander Musman1bb328c2014-06-04 13:06:39 +00008639OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8640 SourceLocation StartLoc,
8641 SourceLocation LParenLoc,
8642 SourceLocation EndLoc) {
8643 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008644 SmallVector<Expr *, 8> SrcExprs;
8645 SmallVector<Expr *, 8> DstExprs;
8646 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008647 SmallVector<Decl *, 4> ExprCaptures;
8648 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008649 for (auto &RefExpr : VarList) {
8650 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008651 SourceLocation ELoc;
8652 SourceRange ERange;
8653 Expr *SimpleRefExpr = RefExpr;
8654 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008655 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008656 // It will be analyzed later.
8657 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008658 SrcExprs.push_back(nullptr);
8659 DstExprs.push_back(nullptr);
8660 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008661 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008662 ValueDecl *D = Res.first;
8663 if (!D)
8664 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008665
Alexey Bataev74caaf22016-02-20 04:09:36 +00008666 QualType Type = D->getType();
8667 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008668
8669 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8670 // A variable that appears in a lastprivate clause must not have an
8671 // incomplete type or a reference type.
8672 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008673 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008674 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008675 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008676
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008677 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008678 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8679 // in a Construct]
8680 // Variables with the predetermined data-sharing attributes may not be
8681 // listed in data-sharing attributes clauses, except for the cases
8682 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008683 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8684 // A list item may appear in a firstprivate or lastprivate clause but not
8685 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008686 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008687 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008688 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00008689 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8690 Diag(ELoc, diag::err_omp_wrong_dsa)
8691 << getOpenMPClauseName(DVar.CKind)
8692 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008693 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008694 continue;
8695 }
8696
Alexey Bataevf29276e2014-06-18 04:14:57 +00008697 // OpenMP [2.14.3.5, Restrictions, p.2]
8698 // A list item that is private within a parallel region, or that appears in
8699 // the reduction clause of a parallel construct, must not appear in a
8700 // lastprivate clause on a worksharing construct if any of the corresponding
8701 // worksharing regions ever binds to any of the corresponding parallel
8702 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008703 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008704 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008705 !isOpenMPParallelDirective(CurrDir) &&
8706 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008707 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008708 if (DVar.CKind != OMPC_shared) {
8709 Diag(ELoc, diag::err_omp_required_access)
8710 << getOpenMPClauseName(OMPC_lastprivate)
8711 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008712 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008713 continue;
8714 }
8715 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008716
Alexander Musman1bb328c2014-06-04 13:06:39 +00008717 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008718 // A variable of class type (or array thereof) that appears in a
8719 // lastprivate clause requires an accessible, unambiguous default
8720 // constructor for the class type, unless the list item is also specified
8721 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008722 // A variable of class type (or array thereof) that appears in a
8723 // lastprivate clause requires an accessible, unambiguous copy assignment
8724 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008725 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008726 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008727 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008728 D->hasAttrs() ? &D->getAttrs() : nullptr);
8729 auto *PseudoSrcExpr =
8730 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008731 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008732 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008733 D->hasAttrs() ? &D->getAttrs() : nullptr);
8734 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008735 // For arrays generate assignment operation for single element and replace
8736 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008737 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008738 PseudoDstExpr, PseudoSrcExpr);
8739 if (AssignmentOp.isInvalid())
8740 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008741 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008742 /*DiscardedValue=*/true);
8743 if (AssignmentOp.isInvalid())
8744 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008745
Alexey Bataev74caaf22016-02-20 04:09:36 +00008746 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008747 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008748 if (TopDVar.CKind == OMPC_firstprivate)
8749 Ref = TopDVar.PrivateCopy;
8750 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008751 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008752 if (!IsOpenMPCapturedDecl(D))
8753 ExprCaptures.push_back(Ref->getDecl());
8754 }
8755 if (TopDVar.CKind == OMPC_firstprivate ||
8756 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008757 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008758 ExprResult RefRes = DefaultLvalueConversion(Ref);
8759 if (!RefRes.isUsable())
8760 continue;
8761 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008762 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8763 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008764 if (!PostUpdateRes.isUsable())
8765 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008766 ExprPostUpdates.push_back(
8767 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008768 }
8769 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008770 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008771 Vars.push_back((VD || CurContext->isDependentContext())
8772 ? RefExpr->IgnoreParens()
8773 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008774 SrcExprs.push_back(PseudoSrcExpr);
8775 DstExprs.push_back(PseudoDstExpr);
8776 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008777 }
8778
8779 if (Vars.empty())
8780 return nullptr;
8781
8782 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008783 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008784 buildPreInits(Context, ExprCaptures),
8785 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008786}
8787
Alexey Bataev758e55e2013-09-06 18:03:48 +00008788OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8789 SourceLocation StartLoc,
8790 SourceLocation LParenLoc,
8791 SourceLocation EndLoc) {
8792 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008793 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008794 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008795 SourceLocation ELoc;
8796 SourceRange ERange;
8797 Expr *SimpleRefExpr = RefExpr;
8798 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008799 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008800 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008801 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008802 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008803 ValueDecl *D = Res.first;
8804 if (!D)
8805 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008806
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008807 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008808 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8809 // in a Construct]
8810 // Variables with the predetermined data-sharing attributes may not be
8811 // listed in data-sharing attributes clauses, except for the cases
8812 // listed below. For these exceptions only, listing a predetermined
8813 // variable in a data-sharing attribute clause is allowed and overrides
8814 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008815 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008816 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8817 DVar.RefExpr) {
8818 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8819 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008820 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008821 continue;
8822 }
8823
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008824 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008825 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008826 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008827 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008828 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8829 ? RefExpr->IgnoreParens()
8830 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008831 }
8832
Alexey Bataeved09d242014-05-28 05:53:51 +00008833 if (Vars.empty())
8834 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008835
8836 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8837}
8838
Alexey Bataevc5e02582014-06-16 07:08:35 +00008839namespace {
8840class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8841 DSAStackTy *Stack;
8842
8843public:
8844 bool VisitDeclRefExpr(DeclRefExpr *E) {
8845 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008846 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008847 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8848 return false;
8849 if (DVar.CKind != OMPC_unknown)
8850 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008851 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8852 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008853 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008854 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008855 return true;
8856 return false;
8857 }
8858 return false;
8859 }
8860 bool VisitStmt(Stmt *S) {
8861 for (auto Child : S->children()) {
8862 if (Child && Visit(Child))
8863 return true;
8864 }
8865 return false;
8866 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008867 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008868};
Alexey Bataev23b69422014-06-18 07:08:49 +00008869} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008870
Alexey Bataev60da77e2016-02-29 05:54:20 +00008871namespace {
8872// Transform MemberExpression for specified FieldDecl of current class to
8873// DeclRefExpr to specified OMPCapturedExprDecl.
8874class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8875 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8876 ValueDecl *Field;
8877 DeclRefExpr *CapturedExpr;
8878
8879public:
8880 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8881 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8882
8883 ExprResult TransformMemberExpr(MemberExpr *E) {
8884 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8885 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008886 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008887 return CapturedExpr;
8888 }
8889 return BaseTransform::TransformMemberExpr(E);
8890 }
8891 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8892};
8893} // namespace
8894
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008895template <typename T>
8896static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8897 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8898 for (auto &Set : Lookups) {
8899 for (auto *D : Set) {
8900 if (auto Res = Gen(cast<ValueDecl>(D)))
8901 return Res;
8902 }
8903 }
8904 return T();
8905}
8906
8907static ExprResult
8908buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8909 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8910 const DeclarationNameInfo &ReductionId, QualType Ty,
8911 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8912 if (ReductionIdScopeSpec.isInvalid())
8913 return ExprError();
8914 SmallVector<UnresolvedSet<8>, 4> Lookups;
8915 if (S) {
8916 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8917 Lookup.suppressDiagnostics();
8918 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8919 auto *D = Lookup.getRepresentativeDecl();
8920 do {
8921 S = S->getParent();
8922 } while (S && !S->isDeclScope(D));
8923 if (S)
8924 S = S->getParent();
8925 Lookups.push_back(UnresolvedSet<8>());
8926 Lookups.back().append(Lookup.begin(), Lookup.end());
8927 Lookup.clear();
8928 }
8929 } else if (auto *ULE =
8930 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8931 Lookups.push_back(UnresolvedSet<8>());
8932 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008933 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008934 if (D == PrevD)
8935 Lookups.push_back(UnresolvedSet<8>());
8936 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8937 Lookups.back().addDecl(DRD);
8938 PrevD = D;
8939 }
8940 }
8941 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8942 Ty->containsUnexpandedParameterPack() ||
8943 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8944 return !D->isInvalidDecl() &&
8945 (D->getType()->isDependentType() ||
8946 D->getType()->isInstantiationDependentType() ||
8947 D->getType()->containsUnexpandedParameterPack());
8948 })) {
8949 UnresolvedSet<8> ResSet;
8950 for (auto &Set : Lookups) {
8951 ResSet.append(Set.begin(), Set.end());
8952 // The last item marks the end of all declarations at the specified scope.
8953 ResSet.addDecl(Set[Set.size() - 1]);
8954 }
8955 return UnresolvedLookupExpr::Create(
8956 SemaRef.Context, /*NamingClass=*/nullptr,
8957 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8958 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8959 }
8960 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8961 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8962 if (!D->isInvalidDecl() &&
8963 SemaRef.Context.hasSameType(D->getType(), Ty))
8964 return D;
8965 return nullptr;
8966 }))
8967 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8968 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8969 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8970 if (!D->isInvalidDecl() &&
8971 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8972 !Ty.isMoreQualifiedThan(D->getType()))
8973 return D;
8974 return nullptr;
8975 })) {
8976 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8977 /*DetectVirtual=*/false);
8978 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8979 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8980 VD->getType().getUnqualifiedType()))) {
8981 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8982 /*DiagID=*/0) !=
8983 Sema::AR_inaccessible) {
8984 SemaRef.BuildBasePathArray(Paths, BasePath);
8985 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8986 }
8987 }
8988 }
8989 }
8990 if (ReductionIdScopeSpec.isSet()) {
8991 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8992 return ExprError();
8993 }
8994 return ExprEmpty();
8995}
8996
Alexey Bataevfad872fc2017-07-18 15:32:58 +00008997namespace {
8998/// Data for the reduction-based clauses.
8999struct ReductionData {
9000 /// List of original reduction items.
9001 SmallVector<Expr *, 8> Vars;
9002 /// List of private copies of the reduction items.
9003 SmallVector<Expr *, 8> Privates;
9004 /// LHS expressions for the reduction_op expressions.
9005 SmallVector<Expr *, 8> LHSs;
9006 /// RHS expressions for the reduction_op expressions.
9007 SmallVector<Expr *, 8> RHSs;
9008 /// Reduction operation expression.
9009 SmallVector<Expr *, 8> ReductionOps;
9010 /// List of captures for clause.
9011 SmallVector<Decl *, 4> ExprCaptures;
9012 /// List of postupdate expressions.
9013 SmallVector<Expr *, 4> ExprPostUpdates;
9014 ReductionData() = delete;
9015 /// Reserves required memory for the reduction data.
9016 ReductionData(unsigned Size) {
9017 Vars.reserve(Size);
9018 Privates.reserve(Size);
9019 LHSs.reserve(Size);
9020 RHSs.reserve(Size);
9021 ReductionOps.reserve(Size);
9022 ExprCaptures.reserve(Size);
9023 ExprPostUpdates.reserve(Size);
9024 }
9025 /// Stores reduction item and reduction operation only (required for dependent
9026 /// reduction item).
9027 void push(Expr *Item, Expr *ReductionOp) {
9028 Vars.emplace_back(Item);
9029 Privates.emplace_back(nullptr);
9030 LHSs.emplace_back(nullptr);
9031 RHSs.emplace_back(nullptr);
9032 ReductionOps.emplace_back(ReductionOp);
9033 }
9034 /// Stores reduction data.
9035 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS,
9036 Expr *ReductionOp) {
9037 Vars.emplace_back(Item);
9038 Privates.emplace_back(Private);
9039 LHSs.emplace_back(LHS);
9040 RHSs.emplace_back(RHS);
9041 ReductionOps.emplace_back(ReductionOp);
9042 }
9043};
9044} // namespace
9045
9046static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009047 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9048 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9049 SourceLocation ColonLoc, SourceLocation EndLoc,
9050 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009051 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009052 auto DN = ReductionId.getName();
9053 auto OOK = DN.getCXXOverloadedOperator();
9054 BinaryOperatorKind BOK = BO_Comma;
9055
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009056 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009057 // OpenMP [2.14.3.6, reduction clause]
9058 // C
9059 // reduction-identifier is either an identifier or one of the following
9060 // operators: +, -, *, &, |, ^, && and ||
9061 // C++
9062 // reduction-identifier is either an id-expression or one of the following
9063 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009064 switch (OOK) {
9065 case OO_Plus:
9066 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009067 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009068 break;
9069 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009070 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009071 break;
9072 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009073 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009074 break;
9075 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009076 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009077 break;
9078 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009079 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009080 break;
9081 case OO_AmpAmp:
9082 BOK = BO_LAnd;
9083 break;
9084 case OO_PipePipe:
9085 BOK = BO_LOr;
9086 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009087 case OO_New:
9088 case OO_Delete:
9089 case OO_Array_New:
9090 case OO_Array_Delete:
9091 case OO_Slash:
9092 case OO_Percent:
9093 case OO_Tilde:
9094 case OO_Exclaim:
9095 case OO_Equal:
9096 case OO_Less:
9097 case OO_Greater:
9098 case OO_LessEqual:
9099 case OO_GreaterEqual:
9100 case OO_PlusEqual:
9101 case OO_MinusEqual:
9102 case OO_StarEqual:
9103 case OO_SlashEqual:
9104 case OO_PercentEqual:
9105 case OO_CaretEqual:
9106 case OO_AmpEqual:
9107 case OO_PipeEqual:
9108 case OO_LessLess:
9109 case OO_GreaterGreater:
9110 case OO_LessLessEqual:
9111 case OO_GreaterGreaterEqual:
9112 case OO_EqualEqual:
9113 case OO_ExclaimEqual:
9114 case OO_PlusPlus:
9115 case OO_MinusMinus:
9116 case OO_Comma:
9117 case OO_ArrowStar:
9118 case OO_Arrow:
9119 case OO_Call:
9120 case OO_Subscript:
9121 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009122 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009123 case NUM_OVERLOADED_OPERATORS:
9124 llvm_unreachable("Unexpected reduction identifier");
9125 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009126 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009127 if (II->isStr("max"))
9128 BOK = BO_GT;
9129 else if (II->isStr("min"))
9130 BOK = BO_LT;
9131 }
9132 break;
9133 }
9134 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009135 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009136 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009137 else
9138 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009139 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009140
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009141 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9142 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009143 for (auto RefExpr : VarList) {
9144 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009145 // OpenMP [2.1, C/C++]
9146 // A list item is a variable or array section, subject to the restrictions
9147 // specified in Section 2.4 on page 42 and in each of the sections
9148 // describing clauses and directives for which a list appears.
9149 // OpenMP [2.14.3.3, Restrictions, p.1]
9150 // A variable that is part of another variable (as an array or
9151 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009152 if (!FirstIter && IR != ER)
9153 ++IR;
9154 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009155 SourceLocation ELoc;
9156 SourceRange ERange;
9157 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009158 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009159 /*AllowArraySection=*/true);
9160 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009161 // Try to find 'declare reduction' corresponding construct before using
9162 // builtin/overloaded operators.
9163 QualType Type = Context.DependentTy;
9164 CXXCastPath BasePath;
9165 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009166 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009167 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009168 Expr *ReductionOp = nullptr;
9169 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009170 (DeclareReductionRef.isUnset() ||
9171 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009172 ReductionOp = DeclareReductionRef.get();
9173 // It will be analyzed later.
9174 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009175 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009176 ValueDecl *D = Res.first;
9177 if (!D)
9178 continue;
9179
Alexey Bataeva1764212015-09-30 09:22:36 +00009180 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009181 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9182 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9183 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009184 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009185 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009186 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9187 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9188 Type = ATy->getElementType();
9189 else
9190 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009191 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009192 } else
9193 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9194 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009195
Alexey Bataevc5e02582014-06-16 07:08:35 +00009196 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9197 // A variable that appears in a private clause must not have an incomplete
9198 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009199 if (S.RequireCompleteType(ELoc, Type,
9200 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009201 continue;
9202 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009203 // A list item that appears in a reduction clause must not be
9204 // const-qualified.
9205 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009206 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009207 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009208 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9209 VarDecl::DeclarationOnly;
9210 S.Diag(D->getLocation(),
9211 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009212 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009213 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009214 continue;
9215 }
9216 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9217 // If a list-item is a reference type then it must bind to the same object
9218 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009219 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009220 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009221 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009222 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009223 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009224 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9225 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009226 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009227 continue;
9228 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009229 }
9230 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009231
Alexey Bataevc5e02582014-06-16 07:08:35 +00009232 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9233 // in a Construct]
9234 // Variables with the predetermined data-sharing attributes may not be
9235 // listed in data-sharing attributes clauses, except for the cases
9236 // listed below. For these exceptions only, listing a predetermined
9237 // variable in a data-sharing attribute clause is allowed and overrides
9238 // the variable's predetermined data-sharing attributes.
9239 // OpenMP [2.14.3.6, Restrictions, p.3]
9240 // Any number of reduction clauses can be specified on the directive,
9241 // but a list item can appear only once in the reduction clauses for that
9242 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009243 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009244 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009245 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009246 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009247 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009248 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009249 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009250 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009251 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009252 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009253 << getOpenMPClauseName(DVar.CKind)
9254 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009255 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009256 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009257 }
9258
9259 // OpenMP [2.14.3.6, Restrictions, p.1]
9260 // A list item that appears in a reduction clause of a worksharing
9261 // construct must be shared in the parallel regions to which any of the
9262 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009263 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009264 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009265 !isOpenMPParallelDirective(CurrDir) &&
9266 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009267 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009268 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009269 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009270 << getOpenMPClauseName(OMPC_reduction)
9271 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009272 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009273 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009274 }
9275 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009276
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009277 // Try to find 'declare reduction' corresponding construct before using
9278 // builtin/overloaded operators.
9279 CXXCastPath BasePath;
9280 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009281 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009282 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9283 if (DeclareReductionRef.isInvalid())
9284 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009285 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009286 (DeclareReductionRef.isUnset() ||
9287 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009288 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009289 continue;
9290 }
9291 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9292 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009293 S.Diag(ReductionId.getLocStart(),
9294 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009295 << Type << ReductionIdRange;
9296 continue;
9297 }
9298
9299 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9300 // The type of a list item that appears in a reduction clause must be valid
9301 // for the reduction-identifier. For a max or min reduction in C, the type
9302 // of the list item must be an allowed arithmetic data type: char, int,
9303 // float, double, or _Bool, possibly modified with long, short, signed, or
9304 // unsigned. For a max or min reduction in C++, the type of the list item
9305 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9306 // double, or bool, possibly modified with long, short, signed, or unsigned.
9307 if (DeclareReductionRef.isUnset()) {
9308 if ((BOK == BO_GT || BOK == BO_LT) &&
9309 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009310 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9311 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009312 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009313 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009314 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9315 VarDecl::DeclarationOnly;
9316 S.Diag(D->getLocation(),
9317 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009318 << D;
9319 }
9320 continue;
9321 }
9322 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009323 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009324 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9325 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009326 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009327 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9328 VarDecl::DeclarationOnly;
9329 S.Diag(D->getLocation(),
9330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009331 << D;
9332 }
9333 continue;
9334 }
9335 }
9336
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009337 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009338 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009339 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009340 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009341 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009342 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009343 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009344 (!ASE &&
9345 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009346 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009347 // Create pseudo array type for private copy. The size for this array will
9348 // be generated during codegen.
9349 // For array subscripts or single variables Private Ty is the same as Type
9350 // (type of the variable or single array element).
9351 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009352 Type,
9353 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9354 VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009355 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009356 } else if (!ASE && !OASE &&
9357 Context.getAsArrayType(D->getType().getNonReferenceType()))
9358 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009359 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009360 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009361 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009362 // Add initializer for private variable.
9363 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009364 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9365 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009366 if (DeclareReductionRef.isUsable()) {
9367 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9368 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9369 if (DRD->getInitializer()) {
9370 Init = DRDRef;
9371 RHSVD->setInit(DRDRef);
9372 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009373 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009374 } else {
9375 switch (BOK) {
9376 case BO_Add:
9377 case BO_Xor:
9378 case BO_Or:
9379 case BO_LOr:
9380 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9381 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009382 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009383 break;
9384 case BO_Mul:
9385 case BO_LAnd:
9386 if (Type->isScalarType() || Type->isAnyComplexType()) {
9387 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009388 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009389 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009390 break;
9391 case BO_And: {
9392 // '&' reduction op - initializer is '~0'.
9393 QualType OrigType = Type;
9394 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9395 Type = ComplexTy->getElementType();
9396 if (Type->isRealFloatingType()) {
9397 llvm::APFloat InitValue =
9398 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9399 /*isIEEE=*/true);
9400 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9401 Type, ELoc);
9402 } else if (Type->isScalarType()) {
9403 auto Size = Context.getTypeSize(Type);
9404 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9405 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9406 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9407 }
9408 if (Init && OrigType->isAnyComplexType()) {
9409 // Init = 0xFFFF + 0xFFFFi;
9410 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009411 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009412 }
9413 Type = OrigType;
9414 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009415 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009416 case BO_LT:
9417 case BO_GT: {
9418 // 'min' reduction op - initializer is 'Largest representable number in
9419 // the reduction list item type'.
9420 // 'max' reduction op - initializer is 'Least representable number in
9421 // the reduction list item type'.
9422 if (Type->isIntegerType() || Type->isPointerType()) {
9423 bool IsSigned = Type->hasSignedIntegerRepresentation();
9424 auto Size = Context.getTypeSize(Type);
9425 QualType IntTy =
9426 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9427 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009428 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9429 : llvm::APInt::getMinValue(Size)
9430 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9431 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009432 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9433 if (Type->isPointerType()) {
9434 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009435 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009436 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9437 SourceLocation(), Init);
9438 if (CastExpr.isInvalid())
9439 continue;
9440 Init = CastExpr.get();
9441 }
9442 } else if (Type->isRealFloatingType()) {
9443 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9444 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9445 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9446 Type, ELoc);
9447 }
9448 break;
9449 }
9450 case BO_PtrMemD:
9451 case BO_PtrMemI:
9452 case BO_MulAssign:
9453 case BO_Div:
9454 case BO_Rem:
9455 case BO_Sub:
9456 case BO_Shl:
9457 case BO_Shr:
9458 case BO_LE:
9459 case BO_GE:
9460 case BO_EQ:
9461 case BO_NE:
9462 case BO_AndAssign:
9463 case BO_XorAssign:
9464 case BO_OrAssign:
9465 case BO_Assign:
9466 case BO_AddAssign:
9467 case BO_SubAssign:
9468 case BO_DivAssign:
9469 case BO_RemAssign:
9470 case BO_ShlAssign:
9471 case BO_ShrAssign:
9472 case BO_Comma:
9473 llvm_unreachable("Unexpected reduction operation");
9474 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009475 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009476 if (Init && DeclareReductionRef.isUnset())
9477 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9478 else if (!Init)
9479 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009480 if (RHSVD->isInvalidDecl())
9481 continue;
9482 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009483 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9484 << Type << ReductionIdRange;
9485 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9486 VarDecl::DeclarationOnly;
9487 S.Diag(D->getLocation(),
9488 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009489 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009490 continue;
9491 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009492 // Store initializer for single element in private copy. Will be used during
9493 // codegen.
9494 PrivateVD->setInit(RHSVD->getInit());
9495 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009496 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009497 ExprResult ReductionOp;
9498 if (DeclareReductionRef.isUsable()) {
9499 QualType RedTy = DeclareReductionRef.get()->getType();
9500 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009501 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9502 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009503 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009504 LHS = S.DefaultLvalueConversion(LHS.get());
9505 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009506 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9507 CK_UncheckedDerivedToBase, LHS.get(),
9508 &BasePath, LHS.get()->getValueKind());
9509 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9510 CK_UncheckedDerivedToBase, RHS.get(),
9511 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009512 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009513 FunctionProtoType::ExtProtoInfo EPI;
9514 QualType Params[] = {PtrRedTy, PtrRedTy};
9515 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9516 auto *OVE = new (Context) OpaqueValueExpr(
9517 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009518 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009519 Expr *Args[] = {LHS.get(), RHS.get()};
9520 ReductionOp = new (Context)
9521 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9522 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009523 ReductionOp = S.BuildBinOp(
9524 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009525 if (ReductionOp.isUsable()) {
9526 if (BOK != BO_LT && BOK != BO_GT) {
9527 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009528 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9529 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009530 } else {
9531 auto *ConditionalOp = new (Context) ConditionalOperator(
9532 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9533 RHSDRE, Type, VK_LValue, OK_Ordinary);
9534 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009535 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9536 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009537 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009538 if (ReductionOp.isUsable())
9539 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009540 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009541 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009542 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009543 }
9544
Alexey Bataevfa312f32017-07-21 18:48:21 +00009545 // OpenMP [2.15.4.6, Restrictions, p.2]
9546 // A list item that appears in an in_reduction clause of a task construct
9547 // must appear in a task_reduction clause of a construct associated with a
9548 // taskgroup region that includes the participating task in its taskgroup
9549 // set. The construct associated with the innermost region that meets this
9550 // condition must specify the same reduction-identifier as the in_reduction
9551 // clause.
9552 if (ClauseKind == OMPC_in_reduction) {
9553 DVar = Stack->hasDSA(
9554 D, [](OpenMPClauseKind K) { return K != OMPC_unknown; },
9555 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
9556 /*FromParent=*/true);
9557 if (DVar.CKind != OMPC_reduction || DVar.DKind != OMPD_taskgroup) {
9558 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
9559 continue;
9560 }
9561 SourceRange ParentSR;
9562 BinaryOperatorKind ParentBOK;
9563 const Expr *ParentReductionOp;
9564 bool IsParentBOK = Stack->getTopMostReductionData(D, ParentSR, ParentBOK);
9565 bool IsParentReductionOp =
9566 Stack->getTopMostReductionData(D, ParentSR, ParentReductionOp);
9567 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
9568 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
9569 IsParentReductionOp) {
9570 bool EmitError = true;
9571 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
9572 llvm::FoldingSetNodeID RedId, ParentRedId;
9573 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
9574 DeclareReductionRef.get()->Profile(RedId, Context,
9575 /*Canonical=*/true);
9576 EmitError = RedId != ParentRedId;
9577 }
9578 if (EmitError) {
9579 S.Diag(ReductionId.getLocStart(),
9580 diag::err_omp_reduction_identifier_mismatch)
9581 << ReductionIdRange << RefExpr->getSourceRange();
9582 S.Diag(ParentSR.getBegin(),
9583 diag::note_omp_previous_reduction_identifier)
9584 << ParentSR << DVar.RefExpr->getSourceRange();
9585 continue;
9586 }
9587 }
9588 }
9589
Alexey Bataev60da77e2016-02-29 05:54:20 +00009590 DeclRefExpr *Ref = nullptr;
9591 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009592 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009593 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009594 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009595 VarsExpr =
9596 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9597 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009598 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009599 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009600 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009601 if (!S.IsOpenMPCapturedDecl(D)) {
9602 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009603 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009604 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009605 if (!RefRes.isUsable())
9606 continue;
9607 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009608 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9609 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009610 if (!PostUpdateRes.isUsable())
9611 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009612 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9613 Stack->getCurrentDirective() == OMPD_taskgroup) {
9614 S.Diag(RefExpr->getExprLoc(),
9615 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009616 << RefExpr->getSourceRange();
9617 continue;
9618 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009619 RD.ExprPostUpdates.emplace_back(
9620 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009621 }
9622 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009623 }
Alexey Bataev169d96a2017-07-18 20:17:46 +00009624 // All reduction items are still marked as reduction (to do not increase
9625 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009626 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevfa312f32017-07-21 18:48:21 +00009627 if (DeclareReductionRef.isUsable())
9628 Stack->addReductionData(D, ReductionIdRange, DeclareReductionRef.get());
9629 else
9630 Stack->addReductionData(D, ReductionIdRange, BOK);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009631 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009632 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009633 return RD.Vars.empty();
9634}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009635
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009636OMPClause *Sema::ActOnOpenMPReductionClause(
9637 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9638 SourceLocation ColonLoc, SourceLocation EndLoc,
9639 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9640 ArrayRef<Expr *> UnresolvedReductions) {
9641 ReductionData RD(VarList.size());
9642
Alexey Bataev169d96a2017-07-18 20:17:46 +00009643 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
9644 StartLoc, LParenLoc, ColonLoc, EndLoc,
9645 ReductionIdScopeSpec, ReductionId,
9646 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009647 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009648
Alexey Bataevc5e02582014-06-16 07:08:35 +00009649 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009650 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9651 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9652 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9653 buildPreInits(Context, RD.ExprCaptures),
9654 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009655}
9656
Alexey Bataev169d96a2017-07-18 20:17:46 +00009657OMPClause *Sema::ActOnOpenMPTaskReductionClause(
9658 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9659 SourceLocation ColonLoc, SourceLocation EndLoc,
9660 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9661 ArrayRef<Expr *> UnresolvedReductions) {
9662 ReductionData RD(VarList.size());
9663
9664 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
9665 VarList, StartLoc, LParenLoc, ColonLoc,
9666 EndLoc, ReductionIdScopeSpec, ReductionId,
9667 UnresolvedReductions, RD))
9668 return nullptr;
9669
9670 return OMPTaskReductionClause::Create(
9671 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9672 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9673 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9674 buildPreInits(Context, RD.ExprCaptures),
9675 buildPostUpdate(*this, RD.ExprPostUpdates));
9676}
9677
Alexey Bataevfa312f32017-07-21 18:48:21 +00009678OMPClause *Sema::ActOnOpenMPInReductionClause(
9679 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9680 SourceLocation ColonLoc, SourceLocation EndLoc,
9681 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9682 ArrayRef<Expr *> UnresolvedReductions) {
9683 ReductionData RD(VarList.size());
9684
9685 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
9686 StartLoc, LParenLoc, ColonLoc, EndLoc,
9687 ReductionIdScopeSpec, ReductionId,
9688 UnresolvedReductions, RD))
9689 return nullptr;
9690
9691 return OMPInReductionClause::Create(
9692 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9693 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9694 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9695 buildPreInits(Context, RD.ExprCaptures),
9696 buildPostUpdate(*this, RD.ExprPostUpdates));
9697}
9698
Alexey Bataevecba70f2016-04-12 11:02:11 +00009699bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9700 SourceLocation LinLoc) {
9701 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9702 LinKind == OMPC_LINEAR_unknown) {
9703 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9704 return true;
9705 }
9706 return false;
9707}
9708
9709bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9710 OpenMPLinearClauseKind LinKind,
9711 QualType Type) {
9712 auto *VD = dyn_cast_or_null<VarDecl>(D);
9713 // A variable must not have an incomplete type or a reference type.
9714 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9715 return true;
9716 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9717 !Type->isReferenceType()) {
9718 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9719 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9720 return true;
9721 }
9722 Type = Type.getNonReferenceType();
9723
9724 // A list item must not be const-qualified.
9725 if (Type.isConstant(Context)) {
9726 Diag(ELoc, diag::err_omp_const_variable)
9727 << getOpenMPClauseName(OMPC_linear);
9728 if (D) {
9729 bool IsDecl =
9730 !VD ||
9731 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9732 Diag(D->getLocation(),
9733 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9734 << D;
9735 }
9736 return true;
9737 }
9738
9739 // A list item must be of integral or pointer type.
9740 Type = Type.getUnqualifiedType().getCanonicalType();
9741 const auto *Ty = Type.getTypePtrOrNull();
9742 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9743 !Ty->isPointerType())) {
9744 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9745 if (D) {
9746 bool IsDecl =
9747 !VD ||
9748 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9749 Diag(D->getLocation(),
9750 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9751 << D;
9752 }
9753 return true;
9754 }
9755 return false;
9756}
9757
Alexey Bataev182227b2015-08-20 10:54:39 +00009758OMPClause *Sema::ActOnOpenMPLinearClause(
9759 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9760 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9761 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009762 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009763 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009764 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009765 SmallVector<Decl *, 4> ExprCaptures;
9766 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009767 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009768 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009769 for (auto &RefExpr : VarList) {
9770 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009771 SourceLocation ELoc;
9772 SourceRange ERange;
9773 Expr *SimpleRefExpr = RefExpr;
9774 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9775 /*AllowArraySection=*/false);
9776 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009777 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009778 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009779 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009780 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009781 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009782 ValueDecl *D = Res.first;
9783 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009784 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009785
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009786 QualType Type = D->getType();
9787 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009788
9789 // OpenMP [2.14.3.7, linear clause]
9790 // A list-item cannot appear in more than one linear clause.
9791 // A list-item that appears in a linear clause cannot appear in any
9792 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009793 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009794 if (DVar.RefExpr) {
9795 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9796 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009797 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009798 continue;
9799 }
9800
Alexey Bataevecba70f2016-04-12 11:02:11 +00009801 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009802 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009803 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009804
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009805 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009806 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9807 D->hasAttrs() ? &D->getAttrs() : nullptr);
9808 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009809 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009810 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009811 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009812 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009813 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009814 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9815 if (!IsOpenMPCapturedDecl(D)) {
9816 ExprCaptures.push_back(Ref->getDecl());
9817 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9818 ExprResult RefRes = DefaultLvalueConversion(Ref);
9819 if (!RefRes.isUsable())
9820 continue;
9821 ExprResult PostUpdateRes =
9822 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9823 SimpleRefExpr, RefRes.get());
9824 if (!PostUpdateRes.isUsable())
9825 continue;
9826 ExprPostUpdates.push_back(
9827 IgnoredValueConversions(PostUpdateRes.get()).get());
9828 }
9829 }
9830 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009831 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009832 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009833 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009834 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009835 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009836 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009837 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9838
9839 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009840 Vars.push_back((VD || CurContext->isDependentContext())
9841 ? RefExpr->IgnoreParens()
9842 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009843 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009844 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009845 }
9846
9847 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009848 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009849
9850 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009851 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009852 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9853 !Step->isInstantiationDependent() &&
9854 !Step->containsUnexpandedParameterPack()) {
9855 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009856 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009857 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009858 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009859 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009860
Alexander Musman3276a272015-03-21 10:12:56 +00009861 // Build var to save the step value.
9862 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009863 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009864 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009865 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009866 ExprResult CalcStep =
9867 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009868 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009869
Alexander Musman8dba6642014-04-22 13:09:42 +00009870 // Warn about zero linear step (it would be probably better specified as
9871 // making corresponding variables 'const').
9872 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009873 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9874 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009875 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9876 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009877 if (!IsConstant && CalcStep.isUsable()) {
9878 // Calculate the step beforehand instead of doing this on each iteration.
9879 // (This is not used if the number of iterations may be kfold-ed).
9880 CalcStepExpr = CalcStep.get();
9881 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009882 }
9883
Alexey Bataev182227b2015-08-20 10:54:39 +00009884 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9885 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009886 StepExpr, CalcStepExpr,
9887 buildPreInits(Context, ExprCaptures),
9888 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009889}
9890
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009891static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9892 Expr *NumIterations, Sema &SemaRef,
9893 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009894 // Walk the vars and build update/final expressions for the CodeGen.
9895 SmallVector<Expr *, 8> Updates;
9896 SmallVector<Expr *, 8> Finals;
9897 Expr *Step = Clause.getStep();
9898 Expr *CalcStep = Clause.getCalcStep();
9899 // OpenMP [2.14.3.7, linear clause]
9900 // If linear-step is not specified it is assumed to be 1.
9901 if (Step == nullptr)
9902 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009903 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009904 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009905 }
Alexander Musman3276a272015-03-21 10:12:56 +00009906 bool HasErrors = false;
9907 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009908 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009909 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009910 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009911 SourceLocation ELoc;
9912 SourceRange ERange;
9913 Expr *SimpleRefExpr = RefExpr;
9914 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9915 /*AllowArraySection=*/false);
9916 ValueDecl *D = Res.first;
9917 if (Res.second || !D) {
9918 Updates.push_back(nullptr);
9919 Finals.push_back(nullptr);
9920 HasErrors = true;
9921 continue;
9922 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009923 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009924 Expr *InitExpr = *CurInit;
9925
9926 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009927 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009928 Expr *CapturedRef;
9929 if (LinKind == OMPC_LINEAR_uval)
9930 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9931 else
9932 CapturedRef =
9933 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9934 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9935 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009936
9937 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009938 ExprResult Update;
9939 if (!Info.first) {
9940 Update =
9941 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9942 InitExpr, IV, Step, /* Subtract */ false);
9943 } else
9944 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009945 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9946 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009947
9948 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009949 ExprResult Final;
9950 if (!Info.first) {
9951 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9952 InitExpr, NumIterations, Step,
9953 /* Subtract */ false);
9954 } else
9955 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009956 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9957 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009958
Alexander Musman3276a272015-03-21 10:12:56 +00009959 if (!Update.isUsable() || !Final.isUsable()) {
9960 Updates.push_back(nullptr);
9961 Finals.push_back(nullptr);
9962 HasErrors = true;
9963 } else {
9964 Updates.push_back(Update.get());
9965 Finals.push_back(Final.get());
9966 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009967 ++CurInit;
9968 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009969 }
9970 Clause.setUpdates(Updates);
9971 Clause.setFinals(Finals);
9972 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009973}
9974
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009975OMPClause *Sema::ActOnOpenMPAlignedClause(
9976 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9977 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9978
9979 SmallVector<Expr *, 8> Vars;
9980 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009981 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9982 SourceLocation ELoc;
9983 SourceRange ERange;
9984 Expr *SimpleRefExpr = RefExpr;
9985 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9986 /*AllowArraySection=*/false);
9987 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009988 // It will be analyzed later.
9989 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009990 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009991 ValueDecl *D = Res.first;
9992 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009993 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009994
Alexey Bataev1efd1662016-03-29 10:59:56 +00009995 QualType QType = D->getType();
9996 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009997
9998 // OpenMP [2.8.1, simd construct, Restrictions]
9999 // The type of list items appearing in the aligned clause must be
10000 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010001 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010002 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010003 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010004 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010005 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010006 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010007 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010008 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010009 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010010 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010011 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010012 continue;
10013 }
10014
10015 // OpenMP [2.8.1, simd construct, Restrictions]
10016 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010017 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010018 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010019 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10020 << getOpenMPClauseName(OMPC_aligned);
10021 continue;
10022 }
10023
Alexey Bataev1efd1662016-03-29 10:59:56 +000010024 DeclRefExpr *Ref = nullptr;
10025 if (!VD && IsOpenMPCapturedDecl(D))
10026 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10027 Vars.push_back(DefaultFunctionArrayConversion(
10028 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10029 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010030 }
10031
10032 // OpenMP [2.8.1, simd construct, Description]
10033 // The parameter of the aligned clause, alignment, must be a constant
10034 // positive integer expression.
10035 // If no optional parameter is specified, implementation-defined default
10036 // alignments for SIMD instructions on the target platforms are assumed.
10037 if (Alignment != nullptr) {
10038 ExprResult AlignResult =
10039 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10040 if (AlignResult.isInvalid())
10041 return nullptr;
10042 Alignment = AlignResult.get();
10043 }
10044 if (Vars.empty())
10045 return nullptr;
10046
10047 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10048 EndLoc, Vars, Alignment);
10049}
10050
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010051OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10052 SourceLocation StartLoc,
10053 SourceLocation LParenLoc,
10054 SourceLocation EndLoc) {
10055 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010056 SmallVector<Expr *, 8> SrcExprs;
10057 SmallVector<Expr *, 8> DstExprs;
10058 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010059 for (auto &RefExpr : VarList) {
10060 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10061 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010062 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010063 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010064 SrcExprs.push_back(nullptr);
10065 DstExprs.push_back(nullptr);
10066 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010067 continue;
10068 }
10069
Alexey Bataeved09d242014-05-28 05:53:51 +000010070 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010071 // OpenMP [2.1, C/C++]
10072 // A list item is a variable name.
10073 // OpenMP [2.14.4.1, Restrictions, p.1]
10074 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010075 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010076 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010077 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10078 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010079 continue;
10080 }
10081
10082 Decl *D = DE->getDecl();
10083 VarDecl *VD = cast<VarDecl>(D);
10084
10085 QualType Type = VD->getType();
10086 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10087 // It will be analyzed later.
10088 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010089 SrcExprs.push_back(nullptr);
10090 DstExprs.push_back(nullptr);
10091 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010092 continue;
10093 }
10094
10095 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10096 // A list item that appears in a copyin clause must be threadprivate.
10097 if (!DSAStack->isThreadPrivate(VD)) {
10098 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010099 << getOpenMPClauseName(OMPC_copyin)
10100 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010101 continue;
10102 }
10103
10104 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10105 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010106 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010107 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010108 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010109 auto *SrcVD =
10110 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10111 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010112 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010113 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10114 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010115 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10116 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010117 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010118 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010119 // For arrays generate assignment operation for single element and replace
10120 // it by the original array element in CodeGen.
10121 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10122 PseudoDstExpr, PseudoSrcExpr);
10123 if (AssignmentOp.isInvalid())
10124 continue;
10125 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10126 /*DiscardedValue=*/true);
10127 if (AssignmentOp.isInvalid())
10128 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010129
10130 DSAStack->addDSA(VD, DE, OMPC_copyin);
10131 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010132 SrcExprs.push_back(PseudoSrcExpr);
10133 DstExprs.push_back(PseudoDstExpr);
10134 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010135 }
10136
Alexey Bataeved09d242014-05-28 05:53:51 +000010137 if (Vars.empty())
10138 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010139
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010140 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10141 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010142}
10143
Alexey Bataevbae9a792014-06-27 10:37:06 +000010144OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10145 SourceLocation StartLoc,
10146 SourceLocation LParenLoc,
10147 SourceLocation EndLoc) {
10148 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010149 SmallVector<Expr *, 8> SrcExprs;
10150 SmallVector<Expr *, 8> DstExprs;
10151 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010152 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010153 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10154 SourceLocation ELoc;
10155 SourceRange ERange;
10156 Expr *SimpleRefExpr = RefExpr;
10157 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10158 /*AllowArraySection=*/false);
10159 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010160 // It will be analyzed later.
10161 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010162 SrcExprs.push_back(nullptr);
10163 DstExprs.push_back(nullptr);
10164 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010165 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010166 ValueDecl *D = Res.first;
10167 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010168 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010169
Alexey Bataeve122da12016-03-17 10:50:17 +000010170 QualType Type = D->getType();
10171 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010172
10173 // OpenMP [2.14.4.2, Restrictions, p.2]
10174 // A list item that appears in a copyprivate clause may not appear in a
10175 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010176 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10177 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010178 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10179 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010180 Diag(ELoc, diag::err_omp_wrong_dsa)
10181 << getOpenMPClauseName(DVar.CKind)
10182 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010183 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010184 continue;
10185 }
10186
10187 // OpenMP [2.11.4.2, Restrictions, p.1]
10188 // All list items that appear in a copyprivate clause must be either
10189 // threadprivate or private in the enclosing context.
10190 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010191 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010192 if (DVar.CKind == OMPC_shared) {
10193 Diag(ELoc, diag::err_omp_required_access)
10194 << getOpenMPClauseName(OMPC_copyprivate)
10195 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010196 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010197 continue;
10198 }
10199 }
10200 }
10201
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010202 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010203 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010204 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010205 << getOpenMPClauseName(OMPC_copyprivate) << Type
10206 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010207 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010208 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010209 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010210 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010211 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010212 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010213 continue;
10214 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010215
Alexey Bataevbae9a792014-06-27 10:37:06 +000010216 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10217 // A variable of class type (or array thereof) that appears in a
10218 // copyin clause requires an accessible, unambiguous copy assignment
10219 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010220 Type = Context.getBaseElementType(Type.getNonReferenceType())
10221 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010222 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010223 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10224 D->hasAttrs() ? &D->getAttrs() : nullptr);
10225 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010226 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010227 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10228 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010229 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010230 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010231 PseudoDstExpr, PseudoSrcExpr);
10232 if (AssignmentOp.isInvalid())
10233 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010234 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010235 /*DiscardedValue=*/true);
10236 if (AssignmentOp.isInvalid())
10237 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010238
10239 // No need to mark vars as copyprivate, they are already threadprivate or
10240 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010241 assert(VD || IsOpenMPCapturedDecl(D));
10242 Vars.push_back(
10243 VD ? RefExpr->IgnoreParens()
10244 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010245 SrcExprs.push_back(PseudoSrcExpr);
10246 DstExprs.push_back(PseudoDstExpr);
10247 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010248 }
10249
10250 if (Vars.empty())
10251 return nullptr;
10252
Alexey Bataeva63048e2015-03-23 06:18:07 +000010253 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10254 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010255}
10256
Alexey Bataev6125da92014-07-21 11:26:11 +000010257OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10258 SourceLocation StartLoc,
10259 SourceLocation LParenLoc,
10260 SourceLocation EndLoc) {
10261 if (VarList.empty())
10262 return nullptr;
10263
10264 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10265}
Alexey Bataevdea47612014-07-23 07:46:59 +000010266
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010267OMPClause *
10268Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10269 SourceLocation DepLoc, SourceLocation ColonLoc,
10270 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10271 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010272 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010273 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010274 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010275 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010276 return nullptr;
10277 }
10278 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010279 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10280 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010281 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010282 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010283 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10284 /*Last=*/OMPC_DEPEND_unknown, Except)
10285 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010286 return nullptr;
10287 }
10288 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010289 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010290 llvm::APSInt DepCounter(/*BitWidth=*/32);
10291 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10292 if (DepKind == OMPC_DEPEND_sink) {
10293 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10294 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10295 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010296 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010297 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010298 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10299 DSAStack->getParentOrderedRegionParam()) {
10300 for (auto &RefExpr : VarList) {
10301 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010302 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010303 // It will be analyzed later.
10304 Vars.push_back(RefExpr);
10305 continue;
10306 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010307
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010308 SourceLocation ELoc = RefExpr->getExprLoc();
10309 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10310 if (DepKind == OMPC_DEPEND_sink) {
10311 if (DepCounter >= TotalDepCount) {
10312 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10313 continue;
10314 }
10315 ++DepCounter;
10316 // OpenMP [2.13.9, Summary]
10317 // depend(dependence-type : vec), where dependence-type is:
10318 // 'sink' and where vec is the iteration vector, which has the form:
10319 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10320 // where n is the value specified by the ordered clause in the loop
10321 // directive, xi denotes the loop iteration variable of the i-th nested
10322 // loop associated with the loop directive, and di is a constant
10323 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010324 if (CurContext->isDependentContext()) {
10325 // It will be analyzed later.
10326 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010327 continue;
10328 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010329 SimpleExpr = SimpleExpr->IgnoreImplicit();
10330 OverloadedOperatorKind OOK = OO_None;
10331 SourceLocation OOLoc;
10332 Expr *LHS = SimpleExpr;
10333 Expr *RHS = nullptr;
10334 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10335 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10336 OOLoc = BO->getOperatorLoc();
10337 LHS = BO->getLHS()->IgnoreParenImpCasts();
10338 RHS = BO->getRHS()->IgnoreParenImpCasts();
10339 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10340 OOK = OCE->getOperator();
10341 OOLoc = OCE->getOperatorLoc();
10342 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10343 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10344 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10345 OOK = MCE->getMethodDecl()
10346 ->getNameInfo()
10347 .getName()
10348 .getCXXOverloadedOperator();
10349 OOLoc = MCE->getCallee()->getExprLoc();
10350 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10351 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10352 }
10353 SourceLocation ELoc;
10354 SourceRange ERange;
10355 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10356 /*AllowArraySection=*/false);
10357 if (Res.second) {
10358 // It will be analyzed later.
10359 Vars.push_back(RefExpr);
10360 }
10361 ValueDecl *D = Res.first;
10362 if (!D)
10363 continue;
10364
10365 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10366 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10367 continue;
10368 }
10369 if (RHS) {
10370 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10371 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10372 if (RHSRes.isInvalid())
10373 continue;
10374 }
10375 if (!CurContext->isDependentContext() &&
10376 DSAStack->getParentOrderedRegionParam() &&
10377 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10378 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10379 << DSAStack->getParentLoopControlVariable(
10380 DepCounter.getZExtValue());
10381 continue;
10382 }
10383 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010384 } else {
10385 // OpenMP [2.11.1.1, Restrictions, p.3]
10386 // A variable that is part of another variable (such as a field of a
10387 // structure) but is not an array element or an array section cannot
10388 // appear in a depend clause.
10389 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10390 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10391 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10392 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10393 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010394 (ASE &&
10395 !ASE->getBase()
10396 ->getType()
10397 .getNonReferenceType()
10398 ->isPointerType() &&
10399 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010400 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10401 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010402 continue;
10403 }
10404 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010405 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10406 }
10407
10408 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10409 TotalDepCount > VarList.size() &&
10410 DSAStack->getParentOrderedRegionParam()) {
10411 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10412 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10413 }
10414 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10415 Vars.empty())
10416 return nullptr;
10417 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010418 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10419 DepKind, DepLoc, ColonLoc, Vars);
10420 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10421 DSAStack->addDoacrossDependClause(C, OpsOffs);
10422 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010423}
Michael Wonge710d542015-08-07 16:16:36 +000010424
10425OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10426 SourceLocation LParenLoc,
10427 SourceLocation EndLoc) {
10428 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010429
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010430 // OpenMP [2.9.1, Restrictions]
10431 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010432 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10433 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010434 return nullptr;
10435
Michael Wonge710d542015-08-07 16:16:36 +000010436 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10437}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010438
10439static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10440 DSAStackTy *Stack, CXXRecordDecl *RD) {
10441 if (!RD || RD->isInvalidDecl())
10442 return true;
10443
10444 auto QTy = SemaRef.Context.getRecordType(RD);
10445 if (RD->isDynamicClass()) {
10446 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10447 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10448 return false;
10449 }
10450 auto *DC = RD;
10451 bool IsCorrect = true;
10452 for (auto *I : DC->decls()) {
10453 if (I) {
10454 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10455 if (MD->isStatic()) {
10456 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10457 SemaRef.Diag(MD->getLocation(),
10458 diag::note_omp_static_member_in_target);
10459 IsCorrect = false;
10460 }
10461 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10462 if (VD->isStaticDataMember()) {
10463 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10464 SemaRef.Diag(VD->getLocation(),
10465 diag::note_omp_static_member_in_target);
10466 IsCorrect = false;
10467 }
10468 }
10469 }
10470 }
10471
10472 for (auto &I : RD->bases()) {
10473 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10474 I.getType()->getAsCXXRecordDecl()))
10475 IsCorrect = false;
10476 }
10477 return IsCorrect;
10478}
10479
10480static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10481 DSAStackTy *Stack, QualType QTy) {
10482 NamedDecl *ND;
10483 if (QTy->isIncompleteType(&ND)) {
10484 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10485 return false;
10486 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010487 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010488 return false;
10489 }
10490 return true;
10491}
10492
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010493/// \brief Return true if it can be proven that the provided array expression
10494/// (array section or array subscript) does NOT specify the whole size of the
10495/// array whose base type is \a BaseQTy.
10496static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10497 const Expr *E,
10498 QualType BaseQTy) {
10499 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10500
10501 // If this is an array subscript, it refers to the whole size if the size of
10502 // the dimension is constant and equals 1. Also, an array section assumes the
10503 // format of an array subscript if no colon is used.
10504 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10505 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10506 return ATy->getSize().getSExtValue() != 1;
10507 // Size can't be evaluated statically.
10508 return false;
10509 }
10510
10511 assert(OASE && "Expecting array section if not an array subscript.");
10512 auto *LowerBound = OASE->getLowerBound();
10513 auto *Length = OASE->getLength();
10514
10515 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010516 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010517 if (LowerBound) {
10518 llvm::APSInt ConstLowerBound;
10519 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10520 return false; // Can't get the integer value as a constant.
10521 if (ConstLowerBound.getSExtValue())
10522 return true;
10523 }
10524
10525 // If we don't have a length we covering the whole dimension.
10526 if (!Length)
10527 return false;
10528
10529 // If the base is a pointer, we don't have a way to get the size of the
10530 // pointee.
10531 if (BaseQTy->isPointerType())
10532 return false;
10533
10534 // We can only check if the length is the same as the size of the dimension
10535 // if we have a constant array.
10536 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10537 if (!CATy)
10538 return false;
10539
10540 llvm::APSInt ConstLength;
10541 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10542 return false; // Can't get the integer value as a constant.
10543
10544 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10545}
10546
10547// Return true if it can be proven that the provided array expression (array
10548// section or array subscript) does NOT specify a single element of the array
10549// whose base type is \a BaseQTy.
10550static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010551 const Expr *E,
10552 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010553 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10554
10555 // An array subscript always refer to a single element. Also, an array section
10556 // assumes the format of an array subscript if no colon is used.
10557 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10558 return false;
10559
10560 assert(OASE && "Expecting array section if not an array subscript.");
10561 auto *Length = OASE->getLength();
10562
10563 // If we don't have a length we have to check if the array has unitary size
10564 // for this dimension. Also, we should always expect a length if the base type
10565 // is pointer.
10566 if (!Length) {
10567 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10568 return ATy->getSize().getSExtValue() != 1;
10569 // We cannot assume anything.
10570 return false;
10571 }
10572
10573 // Check if the length evaluates to 1.
10574 llvm::APSInt ConstLength;
10575 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10576 return false; // Can't get the integer value as a constant.
10577
10578 return ConstLength.getSExtValue() != 1;
10579}
10580
Samuel Antao661c0902016-05-26 17:39:58 +000010581// Return the expression of the base of the mappable expression or null if it
10582// cannot be determined and do all the necessary checks to see if the expression
10583// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010584// components of the expression.
10585static Expr *CheckMapClauseExpressionBase(
10586 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010587 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10588 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010589 SourceLocation ELoc = E->getExprLoc();
10590 SourceRange ERange = E->getSourceRange();
10591
10592 // The base of elements of list in a map clause have to be either:
10593 // - a reference to variable or field.
10594 // - a member expression.
10595 // - an array expression.
10596 //
10597 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10598 // reference to 'r'.
10599 //
10600 // If we have:
10601 //
10602 // struct SS {
10603 // Bla S;
10604 // foo() {
10605 // #pragma omp target map (S.Arr[:12]);
10606 // }
10607 // }
10608 //
10609 // We want to retrieve the member expression 'this->S';
10610
10611 Expr *RelevantExpr = nullptr;
10612
Samuel Antao5de996e2016-01-22 20:21:36 +000010613 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10614 // If a list item is an array section, it must specify contiguous storage.
10615 //
10616 // For this restriction it is sufficient that we make sure only references
10617 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010618 // exist except in the rightmost expression (unless they cover the whole
10619 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010620 //
10621 // r.ArrS[3:5].Arr[6:7]
10622 //
10623 // r.ArrS[3:5].x
10624 //
10625 // but these would be valid:
10626 // r.ArrS[3].Arr[6:7]
10627 //
10628 // r.ArrS[3].x
10629
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010630 bool AllowUnitySizeArraySection = true;
10631 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010632
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010633 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010634 E = E->IgnoreParenImpCasts();
10635
10636 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10637 if (!isa<VarDecl>(CurE->getDecl()))
10638 break;
10639
10640 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010641
10642 // If we got a reference to a declaration, we should not expect any array
10643 // section before that.
10644 AllowUnitySizeArraySection = false;
10645 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010646
10647 // Record the component.
10648 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10649 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010650 continue;
10651 }
10652
10653 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10654 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10655
10656 if (isa<CXXThisExpr>(BaseE))
10657 // We found a base expression: this->Val.
10658 RelevantExpr = CurE;
10659 else
10660 E = BaseE;
10661
10662 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10663 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10664 << CurE->getSourceRange();
10665 break;
10666 }
10667
10668 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10669
10670 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10671 // A bit-field cannot appear in a map clause.
10672 //
10673 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010674 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10675 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010676 break;
10677 }
10678
10679 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10680 // If the type of a list item is a reference to a type T then the type
10681 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010682 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010683
10684 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10685 // A list item cannot be a variable that is a member of a structure with
10686 // a union type.
10687 //
10688 if (auto *RT = CurType->getAs<RecordType>())
10689 if (RT->isUnionType()) {
10690 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10691 << CurE->getSourceRange();
10692 break;
10693 }
10694
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010695 // If we got a member expression, we should not expect any array section
10696 // before that:
10697 //
10698 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10699 // If a list item is an element of a structure, only the rightmost symbol
10700 // of the variable reference can be an array section.
10701 //
10702 AllowUnitySizeArraySection = false;
10703 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010704
10705 // Record the component.
10706 CurComponents.push_back(
10707 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010708 continue;
10709 }
10710
10711 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10712 E = CurE->getBase()->IgnoreParenImpCasts();
10713
10714 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10715 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10716 << 0 << CurE->getSourceRange();
10717 break;
10718 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010719
10720 // If we got an array subscript that express the whole dimension we
10721 // can have any array expressions before. If it only expressing part of
10722 // the dimension, we can only have unitary-size array expressions.
10723 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10724 E->getType()))
10725 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010726
10727 // Record the component - we don't have any declaration associated.
10728 CurComponents.push_back(
10729 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010730 continue;
10731 }
10732
10733 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010734 E = CurE->getBase()->IgnoreParenImpCasts();
10735
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010736 auto CurType =
10737 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10738
Samuel Antao5de996e2016-01-22 20:21:36 +000010739 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10740 // If the type of a list item is a reference to a type T then the type
10741 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010742 if (CurType->isReferenceType())
10743 CurType = CurType->getPointeeType();
10744
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010745 bool IsPointer = CurType->isAnyPointerType();
10746
10747 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010748 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10749 << 0 << CurE->getSourceRange();
10750 break;
10751 }
10752
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010753 bool NotWhole =
10754 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10755 bool NotUnity =
10756 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10757
Samuel Antaodab51bb2016-07-18 23:22:11 +000010758 if (AllowWholeSizeArraySection) {
10759 // Any array section is currently allowed. Allowing a whole size array
10760 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010761 //
10762 // If this array section refers to the whole dimension we can still
10763 // accept other array sections before this one, except if the base is a
10764 // pointer. Otherwise, only unitary sections are accepted.
10765 if (NotWhole || IsPointer)
10766 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010767 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010768 // A unity or whole array section is not allowed and that is not
10769 // compatible with the properties of the current array section.
10770 SemaRef.Diag(
10771 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10772 << CurE->getSourceRange();
10773 break;
10774 }
Samuel Antao90927002016-04-26 14:54:23 +000010775
10776 // Record the component - we don't have any declaration associated.
10777 CurComponents.push_back(
10778 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010779 continue;
10780 }
10781
10782 // If nothing else worked, this is not a valid map clause expression.
10783 SemaRef.Diag(ELoc,
10784 diag::err_omp_expected_named_var_member_or_array_expression)
10785 << ERange;
10786 break;
10787 }
10788
10789 return RelevantExpr;
10790}
10791
10792// Return true if expression E associated with value VD has conflicts with other
10793// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010794static bool CheckMapConflicts(
10795 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10796 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010797 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10798 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010799 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010800 SourceLocation ELoc = E->getExprLoc();
10801 SourceRange ERange = E->getSourceRange();
10802
10803 // In order to easily check the conflicts we need to match each component of
10804 // the expression under test with the components of the expressions that are
10805 // already in the stack.
10806
Samuel Antao5de996e2016-01-22 20:21:36 +000010807 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010808 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010809 "Map clause expression with unexpected base!");
10810
10811 // Variables to help detecting enclosing problems in data environment nests.
10812 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010813 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010814
Samuel Antao90927002016-04-26 14:54:23 +000010815 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10816 VD, CurrentRegionOnly,
10817 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010818 StackComponents,
10819 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010820
Samuel Antao5de996e2016-01-22 20:21:36 +000010821 assert(!StackComponents.empty() &&
10822 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010823 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010824 "Map clause expression with unexpected base!");
10825
Samuel Antao90927002016-04-26 14:54:23 +000010826 // The whole expression in the stack.
10827 auto *RE = StackComponents.front().getAssociatedExpression();
10828
Samuel Antao5de996e2016-01-22 20:21:36 +000010829 // Expressions must start from the same base. Here we detect at which
10830 // point both expressions diverge from each other and see if we can
10831 // detect if the memory referred to both expressions is contiguous and
10832 // do not overlap.
10833 auto CI = CurComponents.rbegin();
10834 auto CE = CurComponents.rend();
10835 auto SI = StackComponents.rbegin();
10836 auto SE = StackComponents.rend();
10837 for (; CI != CE && SI != SE; ++CI, ++SI) {
10838
10839 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10840 // At most one list item can be an array item derived from a given
10841 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010842 if (CurrentRegionOnly &&
10843 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10844 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10845 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10846 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10847 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010848 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010849 << CI->getAssociatedExpression()->getSourceRange();
10850 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10851 diag::note_used_here)
10852 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010853 return true;
10854 }
10855
10856 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010857 if (CI->getAssociatedExpression()->getStmtClass() !=
10858 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010859 break;
10860
10861 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010862 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010863 break;
10864 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010865 // Check if the extra components of the expressions in the enclosing
10866 // data environment are redundant for the current base declaration.
10867 // If they are, the maps completely overlap, which is legal.
10868 for (; SI != SE; ++SI) {
10869 QualType Type;
10870 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010871 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010872 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010873 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10874 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010875 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10876 Type =
10877 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10878 }
10879 if (Type.isNull() || Type->isAnyPointerType() ||
10880 CheckArrayExpressionDoesNotReferToWholeSize(
10881 SemaRef, SI->getAssociatedExpression(), Type))
10882 break;
10883 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010884
10885 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10886 // List items of map clauses in the same construct must not share
10887 // original storage.
10888 //
10889 // If the expressions are exactly the same or one is a subset of the
10890 // other, it means they are sharing storage.
10891 if (CI == CE && SI == SE) {
10892 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010893 if (CKind == OMPC_map)
10894 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10895 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010896 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010897 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10898 << ERange;
10899 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010900 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10901 << RE->getSourceRange();
10902 return true;
10903 } else {
10904 // If we find the same expression in the enclosing data environment,
10905 // that is legal.
10906 IsEnclosedByDataEnvironmentExpr = true;
10907 return false;
10908 }
10909 }
10910
Samuel Antao90927002016-04-26 14:54:23 +000010911 QualType DerivedType =
10912 std::prev(CI)->getAssociatedDeclaration()->getType();
10913 SourceLocation DerivedLoc =
10914 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010915
10916 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10917 // If the type of a list item is a reference to a type T then the type
10918 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010919 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010920
10921 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10922 // A variable for which the type is pointer and an array section
10923 // derived from that variable must not appear as list items of map
10924 // clauses of the same construct.
10925 //
10926 // Also, cover one of the cases in:
10927 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10928 // If any part of the original storage of a list item has corresponding
10929 // storage in the device data environment, all of the original storage
10930 // must have corresponding storage in the device data environment.
10931 //
10932 if (DerivedType->isAnyPointerType()) {
10933 if (CI == CE || SI == SE) {
10934 SemaRef.Diag(
10935 DerivedLoc,
10936 diag::err_omp_pointer_mapped_along_with_derived_section)
10937 << DerivedLoc;
10938 } else {
10939 assert(CI != CE && SI != SE);
10940 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10941 << DerivedLoc;
10942 }
10943 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10944 << RE->getSourceRange();
10945 return true;
10946 }
10947
10948 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10949 // List items of map clauses in the same construct must not share
10950 // original storage.
10951 //
10952 // An expression is a subset of the other.
10953 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010954 if (CKind == OMPC_map)
10955 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10956 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010957 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010958 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10959 << ERange;
10960 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010961 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10962 << RE->getSourceRange();
10963 return true;
10964 }
10965
10966 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010967 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010968 if (!CurrentRegionOnly && SI != SE)
10969 EnclosingExpr = RE;
10970
10971 // The current expression is a subset of the expression in the data
10972 // environment.
10973 IsEnclosedByDataEnvironmentExpr |=
10974 (!CurrentRegionOnly && CI != CE && SI == SE);
10975
10976 return false;
10977 });
10978
10979 if (CurrentRegionOnly)
10980 return FoundError;
10981
10982 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10983 // If any part of the original storage of a list item has corresponding
10984 // storage in the device data environment, all of the original storage must
10985 // have corresponding storage in the device data environment.
10986 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10987 // If a list item is an element of a structure, and a different element of
10988 // the structure has a corresponding list item in the device data environment
10989 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010990 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010991 // data environment prior to the task encountering the construct.
10992 //
10993 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10994 SemaRef.Diag(ELoc,
10995 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10996 << ERange;
10997 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10998 << EnclosingExpr->getSourceRange();
10999 return true;
11000 }
11001
11002 return FoundError;
11003}
11004
Samuel Antao661c0902016-05-26 17:39:58 +000011005namespace {
11006// Utility struct that gathers all the related lists associated with a mappable
11007// expression.
11008struct MappableVarListInfo final {
11009 // The list of expressions.
11010 ArrayRef<Expr *> VarList;
11011 // The list of processed expressions.
11012 SmallVector<Expr *, 16> ProcessedVarList;
11013 // The mappble components for each expression.
11014 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11015 // The base declaration of the variable.
11016 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11017
11018 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11019 // We have a list of components and base declarations for each entry in the
11020 // variable list.
11021 VarComponents.reserve(VarList.size());
11022 VarBaseDeclarations.reserve(VarList.size());
11023 }
11024};
11025}
11026
11027// Check the validity of the provided variable list for the provided clause kind
11028// \a CKind. In the check process the valid expressions, and mappable expression
11029// components and variables are extracted and used to fill \a Vars,
11030// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11031// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11032static void
11033checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11034 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11035 SourceLocation StartLoc,
11036 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11037 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011038 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11039 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011040 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011041
Samuel Antao90927002016-04-26 14:54:23 +000011042 // Keep track of the mappable components and base declarations in this clause.
11043 // Each entry in the list is going to have a list of components associated. We
11044 // record each set of the components so that we can build the clause later on.
11045 // In the end we should have the same amount of declarations and component
11046 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011047
Samuel Antao661c0902016-05-26 17:39:58 +000011048 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011049 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011050 SourceLocation ELoc = RE->getExprLoc();
11051
Kelvin Li0bff7af2015-11-23 05:32:03 +000011052 auto *VE = RE->IgnoreParenLValueCasts();
11053
11054 if (VE->isValueDependent() || VE->isTypeDependent() ||
11055 VE->isInstantiationDependent() ||
11056 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011057 // We can only analyze this information once the missing information is
11058 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011059 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011060 continue;
11061 }
11062
11063 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011064
Samuel Antao5de996e2016-01-22 20:21:36 +000011065 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011066 SemaRef.Diag(ELoc,
11067 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011068 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011069 continue;
11070 }
11071
Samuel Antao90927002016-04-26 14:54:23 +000011072 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11073 ValueDecl *CurDeclaration = nullptr;
11074
11075 // Obtain the array or member expression bases if required. Also, fill the
11076 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011077 auto *BE =
11078 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011079 if (!BE)
11080 continue;
11081
Samuel Antao90927002016-04-26 14:54:23 +000011082 assert(!CurComponents.empty() &&
11083 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011084
Samuel Antao90927002016-04-26 14:54:23 +000011085 // For the following checks, we rely on the base declaration which is
11086 // expected to be associated with the last component. The declaration is
11087 // expected to be a variable or a field (if 'this' is being mapped).
11088 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11089 assert(CurDeclaration && "Null decl on map clause.");
11090 assert(
11091 CurDeclaration->isCanonicalDecl() &&
11092 "Expecting components to have associated only canonical declarations.");
11093
11094 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11095 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011096
11097 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011098 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011099
11100 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011101 // threadprivate variables cannot appear in a map clause.
11102 // OpenMP 4.5 [2.10.5, target update Construct]
11103 // threadprivate variables cannot appear in a from clause.
11104 if (VD && DSAS->isThreadPrivate(VD)) {
11105 auto DVar = DSAS->getTopDSA(VD, false);
11106 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11107 << getOpenMPClauseName(CKind);
11108 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011109 continue;
11110 }
11111
Samuel Antao5de996e2016-01-22 20:21:36 +000011112 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11113 // A list item cannot appear in both a map clause and a data-sharing
11114 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011115
Samuel Antao5de996e2016-01-22 20:21:36 +000011116 // Check conflicts with other map clause expressions. We check the conflicts
11117 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011118 // environment, because the restrictions are different. We only have to
11119 // check conflicts across regions for the map clauses.
11120 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11121 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011122 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011123 if (CKind == OMPC_map &&
11124 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11125 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011126 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011127
Samuel Antao661c0902016-05-26 17:39:58 +000011128 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011129 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11130 // If the type of a list item is a reference to a type T then the type will
11131 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011132 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011133
Samuel Antao661c0902016-05-26 17:39:58 +000011134 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11135 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011136 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011137 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011138 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11139 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011140 continue;
11141
Samuel Antao661c0902016-05-26 17:39:58 +000011142 if (CKind == OMPC_map) {
11143 // target enter data
11144 // OpenMP [2.10.2, Restrictions, p. 99]
11145 // A map-type must be specified in all map clauses and must be either
11146 // to or alloc.
11147 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11148 if (DKind == OMPD_target_enter_data &&
11149 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11150 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11151 << (IsMapTypeImplicit ? 1 : 0)
11152 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11153 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011154 continue;
11155 }
Samuel Antao661c0902016-05-26 17:39:58 +000011156
11157 // target exit_data
11158 // OpenMP [2.10.3, Restrictions, p. 102]
11159 // A map-type must be specified in all map clauses and must be either
11160 // from, release, or delete.
11161 if (DKind == OMPD_target_exit_data &&
11162 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11163 MapType == OMPC_MAP_delete)) {
11164 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11165 << (IsMapTypeImplicit ? 1 : 0)
11166 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11167 << getOpenMPDirectiveName(DKind);
11168 continue;
11169 }
11170
11171 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11172 // A list item cannot appear in both a map clause and a data-sharing
11173 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011174 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011175 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011176 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011177 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11178 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011179 auto DVar = DSAS->getTopDSA(VD, false);
11180 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011181 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011182 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011183 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011184 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11185 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11186 continue;
11187 }
11188 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011189 }
11190
Samuel Antao90927002016-04-26 14:54:23 +000011191 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011192 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011193
11194 // Store the components in the stack so that they can be used to check
11195 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011196 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11197 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011198
11199 // Save the components and declaration to create the clause. For purposes of
11200 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011201 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011202 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11203 MVLI.VarComponents.back().append(CurComponents.begin(),
11204 CurComponents.end());
11205 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11206 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011207 }
Samuel Antao661c0902016-05-26 17:39:58 +000011208}
11209
11210OMPClause *
11211Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11212 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11213 SourceLocation MapLoc, SourceLocation ColonLoc,
11214 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11215 SourceLocation LParenLoc, SourceLocation EndLoc) {
11216 MappableVarListInfo MVLI(VarList);
11217 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11218 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011219
Samuel Antao5de996e2016-01-22 20:21:36 +000011220 // We need to produce a map clause even if we don't have variables so that
11221 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011222 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11223 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11224 MVLI.VarComponents, MapTypeModifier, MapType,
11225 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011226}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011227
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011228QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11229 TypeResult ParsedType) {
11230 assert(ParsedType.isUsable());
11231
11232 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11233 if (ReductionType.isNull())
11234 return QualType();
11235
11236 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11237 // A type name in a declare reduction directive cannot be a function type, an
11238 // array type, a reference type, or a type qualified with const, volatile or
11239 // restrict.
11240 if (ReductionType.hasQualifiers()) {
11241 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11242 return QualType();
11243 }
11244
11245 if (ReductionType->isFunctionType()) {
11246 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11247 return QualType();
11248 }
11249 if (ReductionType->isReferenceType()) {
11250 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11251 return QualType();
11252 }
11253 if (ReductionType->isArrayType()) {
11254 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11255 return QualType();
11256 }
11257 return ReductionType;
11258}
11259
11260Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11261 Scope *S, DeclContext *DC, DeclarationName Name,
11262 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11263 AccessSpecifier AS, Decl *PrevDeclInScope) {
11264 SmallVector<Decl *, 8> Decls;
11265 Decls.reserve(ReductionTypes.size());
11266
11267 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11268 ForRedeclaration);
11269 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11270 // A reduction-identifier may not be re-declared in the current scope for the
11271 // same type or for a type that is compatible according to the base language
11272 // rules.
11273 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11274 OMPDeclareReductionDecl *PrevDRD = nullptr;
11275 bool InCompoundScope = true;
11276 if (S != nullptr) {
11277 // Find previous declaration with the same name not referenced in other
11278 // declarations.
11279 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11280 InCompoundScope =
11281 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11282 LookupName(Lookup, S);
11283 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11284 /*AllowInlineNamespace=*/false);
11285 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11286 auto Filter = Lookup.makeFilter();
11287 while (Filter.hasNext()) {
11288 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11289 if (InCompoundScope) {
11290 auto I = UsedAsPrevious.find(PrevDecl);
11291 if (I == UsedAsPrevious.end())
11292 UsedAsPrevious[PrevDecl] = false;
11293 if (auto *D = PrevDecl->getPrevDeclInScope())
11294 UsedAsPrevious[D] = true;
11295 }
11296 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11297 PrevDecl->getLocation();
11298 }
11299 Filter.done();
11300 if (InCompoundScope) {
11301 for (auto &PrevData : UsedAsPrevious) {
11302 if (!PrevData.second) {
11303 PrevDRD = PrevData.first;
11304 break;
11305 }
11306 }
11307 }
11308 } else if (PrevDeclInScope != nullptr) {
11309 auto *PrevDRDInScope = PrevDRD =
11310 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11311 do {
11312 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11313 PrevDRDInScope->getLocation();
11314 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11315 } while (PrevDRDInScope != nullptr);
11316 }
11317 for (auto &TyData : ReductionTypes) {
11318 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11319 bool Invalid = false;
11320 if (I != PreviousRedeclTypes.end()) {
11321 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11322 << TyData.first;
11323 Diag(I->second, diag::note_previous_definition);
11324 Invalid = true;
11325 }
11326 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11327 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11328 Name, TyData.first, PrevDRD);
11329 DC->addDecl(DRD);
11330 DRD->setAccess(AS);
11331 Decls.push_back(DRD);
11332 if (Invalid)
11333 DRD->setInvalidDecl();
11334 else
11335 PrevDRD = DRD;
11336 }
11337
11338 return DeclGroupPtrTy::make(
11339 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11340}
11341
11342void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11343 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11344
11345 // Enter new function scope.
11346 PushFunctionScope();
11347 getCurFunction()->setHasBranchProtectedScope();
11348 getCurFunction()->setHasOMPDeclareReductionCombiner();
11349
11350 if (S != nullptr)
11351 PushDeclContext(S, DRD);
11352 else
11353 CurContext = DRD;
11354
Faisal Valid143a0c2017-04-01 21:30:49 +000011355 PushExpressionEvaluationContext(
11356 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011357
11358 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011359 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11360 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11361 // uses semantics of argument handles by value, but it should be passed by
11362 // reference. C lang does not support references, so pass all parameters as
11363 // pointers.
11364 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011365 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011366 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011367 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11368 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11369 // uses semantics of argument handles by value, but it should be passed by
11370 // reference. C lang does not support references, so pass all parameters as
11371 // pointers.
11372 // Create 'T omp_out;' variable.
11373 auto *OmpOutParm =
11374 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11375 if (S != nullptr) {
11376 PushOnScopeChains(OmpInParm, S);
11377 PushOnScopeChains(OmpOutParm, S);
11378 } else {
11379 DRD->addDecl(OmpInParm);
11380 DRD->addDecl(OmpOutParm);
11381 }
11382}
11383
11384void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11385 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11386 DiscardCleanupsInEvaluationContext();
11387 PopExpressionEvaluationContext();
11388
11389 PopDeclContext();
11390 PopFunctionScopeInfo();
11391
11392 if (Combiner != nullptr)
11393 DRD->setCombiner(Combiner);
11394 else
11395 DRD->setInvalidDecl();
11396}
11397
11398void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11399 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11400
11401 // Enter new function scope.
11402 PushFunctionScope();
11403 getCurFunction()->setHasBranchProtectedScope();
11404
11405 if (S != nullptr)
11406 PushDeclContext(S, DRD);
11407 else
11408 CurContext = DRD;
11409
Faisal Valid143a0c2017-04-01 21:30:49 +000011410 PushExpressionEvaluationContext(
11411 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011412
11413 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011414 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11415 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11416 // uses semantics of argument handles by value, but it should be passed by
11417 // reference. C lang does not support references, so pass all parameters as
11418 // pointers.
11419 // Create 'T omp_priv;' variable.
11420 auto *OmpPrivParm =
11421 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011422 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11423 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11424 // uses semantics of argument handles by value, but it should be passed by
11425 // reference. C lang does not support references, so pass all parameters as
11426 // pointers.
11427 // Create 'T omp_orig;' variable.
11428 auto *OmpOrigParm =
11429 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011430 if (S != nullptr) {
11431 PushOnScopeChains(OmpPrivParm, S);
11432 PushOnScopeChains(OmpOrigParm, S);
11433 } else {
11434 DRD->addDecl(OmpPrivParm);
11435 DRD->addDecl(OmpOrigParm);
11436 }
11437}
11438
11439void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11440 Expr *Initializer) {
11441 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11442 DiscardCleanupsInEvaluationContext();
11443 PopExpressionEvaluationContext();
11444
11445 PopDeclContext();
11446 PopFunctionScopeInfo();
11447
11448 if (Initializer != nullptr)
11449 DRD->setInitializer(Initializer);
11450 else
11451 DRD->setInvalidDecl();
11452}
11453
11454Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11455 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11456 for (auto *D : DeclReductions.get()) {
11457 if (IsValid) {
11458 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11459 if (S != nullptr)
11460 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11461 } else
11462 D->setInvalidDecl();
11463 }
11464 return DeclReductions;
11465}
11466
David Majnemer9d168222016-08-05 17:44:54 +000011467OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011468 SourceLocation StartLoc,
11469 SourceLocation LParenLoc,
11470 SourceLocation EndLoc) {
11471 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011472 Stmt *HelperValStmt = nullptr;
11473 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011474
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011475 // OpenMP [teams Constrcut, Restrictions]
11476 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011477 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11478 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011479 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011480
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011481 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11482 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11483 if (CaptureRegion != OMPD_unknown) {
11484 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11485 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11486 HelperValStmt = buildPreInits(Context, Captures);
11487 }
11488
11489 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11490 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011491}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011492
11493OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11494 SourceLocation StartLoc,
11495 SourceLocation LParenLoc,
11496 SourceLocation EndLoc) {
11497 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011498 Stmt *HelperValStmt = nullptr;
11499 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011500
11501 // OpenMP [teams Constrcut, Restrictions]
11502 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011503 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11504 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011505 return nullptr;
11506
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011507 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11508 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11509 if (CaptureRegion != OMPD_unknown) {
11510 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11511 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11512 HelperValStmt = buildPreInits(Context, Captures);
11513 }
11514
11515 return new (Context) OMPThreadLimitClause(
11516 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011517}
Alexey Bataeva0569352015-12-01 10:17:31 +000011518
11519OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11520 SourceLocation StartLoc,
11521 SourceLocation LParenLoc,
11522 SourceLocation EndLoc) {
11523 Expr *ValExpr = Priority;
11524
11525 // OpenMP [2.9.1, task Constrcut]
11526 // The priority-value is a non-negative numerical scalar expression.
11527 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11528 /*StrictlyPositive=*/false))
11529 return nullptr;
11530
11531 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11532}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011533
11534OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11535 SourceLocation StartLoc,
11536 SourceLocation LParenLoc,
11537 SourceLocation EndLoc) {
11538 Expr *ValExpr = Grainsize;
11539
11540 // OpenMP [2.9.2, taskloop Constrcut]
11541 // The parameter of the grainsize clause must be a positive integer
11542 // expression.
11543 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11544 /*StrictlyPositive=*/true))
11545 return nullptr;
11546
11547 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11548}
Alexey Bataev382967a2015-12-08 12:06:20 +000011549
11550OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11551 SourceLocation StartLoc,
11552 SourceLocation LParenLoc,
11553 SourceLocation EndLoc) {
11554 Expr *ValExpr = NumTasks;
11555
11556 // OpenMP [2.9.2, taskloop Constrcut]
11557 // The parameter of the num_tasks clause must be a positive integer
11558 // expression.
11559 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11560 /*StrictlyPositive=*/true))
11561 return nullptr;
11562
11563 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11564}
11565
Alexey Bataev28c75412015-12-15 08:19:24 +000011566OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11567 SourceLocation LParenLoc,
11568 SourceLocation EndLoc) {
11569 // OpenMP [2.13.2, critical construct, Description]
11570 // ... where hint-expression is an integer constant expression that evaluates
11571 // to a valid lock hint.
11572 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11573 if (HintExpr.isInvalid())
11574 return nullptr;
11575 return new (Context)
11576 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11577}
11578
Carlo Bertollib4adf552016-01-15 18:50:31 +000011579OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11580 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11581 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11582 SourceLocation EndLoc) {
11583 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11584 std::string Values;
11585 Values += "'";
11586 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11587 Values += "'";
11588 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11589 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11590 return nullptr;
11591 }
11592 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011593 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011594 if (ChunkSize) {
11595 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11596 !ChunkSize->isInstantiationDependent() &&
11597 !ChunkSize->containsUnexpandedParameterPack()) {
11598 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11599 ExprResult Val =
11600 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11601 if (Val.isInvalid())
11602 return nullptr;
11603
11604 ValExpr = Val.get();
11605
11606 // OpenMP [2.7.1, Restrictions]
11607 // chunk_size must be a loop invariant integer expression with a positive
11608 // value.
11609 llvm::APSInt Result;
11610 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11611 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11612 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11613 << "dist_schedule" << ChunkSize->getSourceRange();
11614 return nullptr;
11615 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011616 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11617 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011618 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11619 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11620 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011621 }
11622 }
11623 }
11624
11625 return new (Context)
11626 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011627 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011628}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011629
11630OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11631 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11632 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11633 SourceLocation KindLoc, SourceLocation EndLoc) {
11634 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011635 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011636 std::string Value;
11637 SourceLocation Loc;
11638 Value += "'";
11639 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11640 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011641 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011642 Loc = MLoc;
11643 } else {
11644 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011645 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011646 Loc = KindLoc;
11647 }
11648 Value += "'";
11649 Diag(Loc, diag::err_omp_unexpected_clause_value)
11650 << Value << getOpenMPClauseName(OMPC_defaultmap);
11651 return nullptr;
11652 }
11653
11654 return new (Context)
11655 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11656}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011657
11658bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11659 DeclContext *CurLexicalContext = getCurLexicalContext();
11660 if (!CurLexicalContext->isFileContext() &&
11661 !CurLexicalContext->isExternCContext() &&
11662 !CurLexicalContext->isExternCXXContext()) {
11663 Diag(Loc, diag::err_omp_region_not_file_context);
11664 return false;
11665 }
11666 if (IsInOpenMPDeclareTargetContext) {
11667 Diag(Loc, diag::err_omp_enclosed_declare_target);
11668 return false;
11669 }
11670
11671 IsInOpenMPDeclareTargetContext = true;
11672 return true;
11673}
11674
11675void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11676 assert(IsInOpenMPDeclareTargetContext &&
11677 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11678
11679 IsInOpenMPDeclareTargetContext = false;
11680}
11681
David Majnemer9d168222016-08-05 17:44:54 +000011682void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11683 CXXScopeSpec &ScopeSpec,
11684 const DeclarationNameInfo &Id,
11685 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11686 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011687 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11688 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11689
11690 if (Lookup.isAmbiguous())
11691 return;
11692 Lookup.suppressDiagnostics();
11693
11694 if (!Lookup.isSingleResult()) {
11695 if (TypoCorrection Corrected =
11696 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11697 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11698 CTK_ErrorRecovery)) {
11699 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11700 << Id.getName());
11701 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11702 return;
11703 }
11704
11705 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11706 return;
11707 }
11708
11709 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11710 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11711 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11712 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11713
11714 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11715 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11716 ND->addAttr(A);
11717 if (ASTMutationListener *ML = Context.getASTMutationListener())
11718 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11719 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11720 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11721 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11722 << Id.getName();
11723 }
11724 } else
11725 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11726}
11727
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011728static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11729 Sema &SemaRef, Decl *D) {
11730 if (!D)
11731 return;
11732 Decl *LD = nullptr;
11733 if (isa<TagDecl>(D)) {
11734 LD = cast<TagDecl>(D)->getDefinition();
11735 } else if (isa<VarDecl>(D)) {
11736 LD = cast<VarDecl>(D)->getDefinition();
11737
11738 // If this is an implicit variable that is legal and we do not need to do
11739 // anything.
11740 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011741 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11742 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11743 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011744 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011745 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011746 return;
11747 }
11748
11749 } else if (isa<FunctionDecl>(D)) {
11750 const FunctionDecl *FD = nullptr;
11751 if (cast<FunctionDecl>(D)->hasBody(FD))
11752 LD = const_cast<FunctionDecl *>(FD);
11753
11754 // If the definition is associated with the current declaration in the
11755 // target region (it can be e.g. a lambda) that is legal and we do not need
11756 // to do anything else.
11757 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011758 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11759 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11760 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011761 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011762 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011763 return;
11764 }
11765 }
11766 if (!LD)
11767 LD = D;
11768 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11769 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11770 // Outlined declaration is not declared target.
11771 if (LD->isOutOfLine()) {
11772 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11773 SemaRef.Diag(SL, diag::note_used_here) << SR;
11774 } else {
11775 DeclContext *DC = LD->getDeclContext();
11776 while (DC) {
11777 if (isa<FunctionDecl>(DC) &&
11778 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11779 break;
11780 DC = DC->getParent();
11781 }
11782 if (DC)
11783 return;
11784
11785 // Is not declared in target context.
11786 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11787 SemaRef.Diag(SL, diag::note_used_here) << SR;
11788 }
11789 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011790 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11791 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11792 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011793 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011794 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011795 }
11796}
11797
11798static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11799 Sema &SemaRef, DSAStackTy *Stack,
11800 ValueDecl *VD) {
11801 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11802 return true;
11803 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11804 return false;
11805 return true;
11806}
11807
11808void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11809 if (!D || D->isInvalidDecl())
11810 return;
11811 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11812 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11813 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11814 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11815 if (DSAStack->isThreadPrivate(VD)) {
11816 Diag(SL, diag::err_omp_threadprivate_in_target);
11817 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11818 return;
11819 }
11820 }
11821 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11822 // Problem if any with var declared with incomplete type will be reported
11823 // as normal, so no need to check it here.
11824 if ((E || !VD->getType()->isIncompleteType()) &&
11825 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11826 // Mark decl as declared target to prevent further diagnostic.
11827 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011828 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11829 Context, OMPDeclareTargetDeclAttr::MT_To);
11830 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011831 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011832 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011833 }
11834 return;
11835 }
11836 }
11837 if (!E) {
11838 // Checking declaration inside declare target region.
11839 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11840 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011841 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11842 Context, OMPDeclareTargetDeclAttr::MT_To);
11843 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011844 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011845 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011846 }
11847 return;
11848 }
11849 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11850}
Samuel Antao661c0902016-05-26 17:39:58 +000011851
11852OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11853 SourceLocation StartLoc,
11854 SourceLocation LParenLoc,
11855 SourceLocation EndLoc) {
11856 MappableVarListInfo MVLI(VarList);
11857 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11858 if (MVLI.ProcessedVarList.empty())
11859 return nullptr;
11860
11861 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11862 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11863 MVLI.VarComponents);
11864}
Samuel Antaoec172c62016-05-26 17:49:04 +000011865
11866OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11867 SourceLocation StartLoc,
11868 SourceLocation LParenLoc,
11869 SourceLocation EndLoc) {
11870 MappableVarListInfo MVLI(VarList);
11871 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11872 if (MVLI.ProcessedVarList.empty())
11873 return nullptr;
11874
11875 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11876 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11877 MVLI.VarComponents);
11878}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011879
11880OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11881 SourceLocation StartLoc,
11882 SourceLocation LParenLoc,
11883 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011884 MappableVarListInfo MVLI(VarList);
11885 SmallVector<Expr *, 8> PrivateCopies;
11886 SmallVector<Expr *, 8> Inits;
11887
Carlo Bertolli2404b172016-07-13 15:37:16 +000011888 for (auto &RefExpr : VarList) {
11889 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11890 SourceLocation ELoc;
11891 SourceRange ERange;
11892 Expr *SimpleRefExpr = RefExpr;
11893 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11894 if (Res.second) {
11895 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011896 MVLI.ProcessedVarList.push_back(RefExpr);
11897 PrivateCopies.push_back(nullptr);
11898 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011899 }
11900 ValueDecl *D = Res.first;
11901 if (!D)
11902 continue;
11903
11904 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011905 Type = Type.getNonReferenceType().getUnqualifiedType();
11906
11907 auto *VD = dyn_cast<VarDecl>(D);
11908
11909 // Item should be a pointer or reference to pointer.
11910 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011911 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11912 << 0 << RefExpr->getSourceRange();
11913 continue;
11914 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011915
11916 // Build the private variable and the expression that refers to it.
11917 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11918 D->hasAttrs() ? &D->getAttrs() : nullptr);
11919 if (VDPrivate->isInvalidDecl())
11920 continue;
11921
11922 CurContext->addDecl(VDPrivate);
11923 auto VDPrivateRefExpr = buildDeclRefExpr(
11924 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11925
11926 // Add temporary variable to initialize the private copy of the pointer.
11927 auto *VDInit =
11928 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11929 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11930 RefExpr->getExprLoc());
11931 AddInitializerToDecl(VDPrivate,
11932 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011933 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011934
11935 // If required, build a capture to implement the privatization initialized
11936 // with the current list item value.
11937 DeclRefExpr *Ref = nullptr;
11938 if (!VD)
11939 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11940 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11941 PrivateCopies.push_back(VDPrivateRefExpr);
11942 Inits.push_back(VDInitRefExpr);
11943
11944 // We need to add a data sharing attribute for this variable to make sure it
11945 // is correctly captured. A variable that shows up in a use_device_ptr has
11946 // similar properties of a first private variable.
11947 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11948
11949 // Create a mappable component for the list item. List items in this clause
11950 // only need a component.
11951 MVLI.VarBaseDeclarations.push_back(D);
11952 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11953 MVLI.VarComponents.back().push_back(
11954 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011955 }
11956
Samuel Antaocc10b852016-07-28 14:23:26 +000011957 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011958 return nullptr;
11959
Samuel Antaocc10b852016-07-28 14:23:26 +000011960 return OMPUseDevicePtrClause::Create(
11961 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11962 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011963}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011964
11965OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11966 SourceLocation StartLoc,
11967 SourceLocation LParenLoc,
11968 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011969 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011970 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011971 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011972 SourceLocation ELoc;
11973 SourceRange ERange;
11974 Expr *SimpleRefExpr = RefExpr;
11975 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11976 if (Res.second) {
11977 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011978 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011979 }
11980 ValueDecl *D = Res.first;
11981 if (!D)
11982 continue;
11983
11984 QualType Type = D->getType();
11985 // item should be a pointer or array or reference to pointer or array
11986 if (!Type.getNonReferenceType()->isPointerType() &&
11987 !Type.getNonReferenceType()->isArrayType()) {
11988 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11989 << 0 << RefExpr->getSourceRange();
11990 continue;
11991 }
Samuel Antao6890b092016-07-28 14:25:09 +000011992
11993 // Check if the declaration in the clause does not show up in any data
11994 // sharing attribute.
11995 auto DVar = DSAStack->getTopDSA(D, false);
11996 if (isOpenMPPrivate(DVar.CKind)) {
11997 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11998 << getOpenMPClauseName(DVar.CKind)
11999 << getOpenMPClauseName(OMPC_is_device_ptr)
12000 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12001 ReportOriginalDSA(*this, DSAStack, D, DVar);
12002 continue;
12003 }
12004
12005 Expr *ConflictExpr;
12006 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012007 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012008 [&ConflictExpr](
12009 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12010 OpenMPClauseKind) -> bool {
12011 ConflictExpr = R.front().getAssociatedExpression();
12012 return true;
12013 })) {
12014 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12015 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12016 << ConflictExpr->getSourceRange();
12017 continue;
12018 }
12019
12020 // Store the components in the stack so that they can be used to check
12021 // against other clauses later on.
12022 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12023 DSAStack->addMappableExpressionComponents(
12024 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12025
12026 // Record the expression we've just processed.
12027 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12028
12029 // Create a mappable component for the list item. List items in this clause
12030 // only need a component. We use a null declaration to signal fields in
12031 // 'this'.
12032 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12033 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12034 "Unexpected device pointer expression!");
12035 MVLI.VarBaseDeclarations.push_back(
12036 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12037 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12038 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012039 }
12040
Samuel Antao6890b092016-07-28 14:25:09 +000012041 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012042 return nullptr;
12043
Samuel Antao6890b092016-07-28 14:25:09 +000012044 return OMPIsDevicePtrClause::Create(
12045 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12046 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012047}