blob: 1eb2ec45dbe591e6516f04c9ff493d7cad472b8e [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 {
89 SourceRange ReductionRange;
90 llvm::PointerUnion<const Expr *,
91 llvm::PointerEmbeddedInt<BinaryOperatorKind>>
92 ReductionOp;
93 ReductionData() = default;
94 void set(BinaryOperatorKind BO, SourceRange RR) {
95 ReductionRange = RR;
96 ReductionOp = BO;
97 }
98 void set(const Expr *RefExpr, SourceRange RR) {
99 ReductionRange = RR;
100 ReductionOp = RefExpr;
101 }
102 };
103 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000104
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000105 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000107 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000108 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000109 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000110 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000111 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000114 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000115 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000116 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000117 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
118 /// get the data (loop counters etc.) about enclosing loop-based construct.
119 /// This data is required during codegen.
120 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000121 /// \brief first argument (Expr *) contains optional argument of the
122 /// 'ordered' clause, the second one is true if the regions has 'ordered'
123 /// clause, false otherwise.
124 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 bool NowaitRegion = false;
126 bool CancelRegion = false;
127 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000128 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000129 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000130 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
132 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000133 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000134 };
135
Axel Naumann323862e2016-02-03 10:45:22 +0000136 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000137
138 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000139 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000140 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
141 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000142 /// \brief true, if check for DSA must be from parent directive, false, if
143 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000144 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000145 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000146 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000147 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000148
149 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
150
David Majnemer9d168222016-08-05 17:44:54 +0000151 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000152
153 /// \brief Checks if the variable is a local for OpenMP region.
154 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000155
Alexey Bataev4b465392017-04-26 15:06:24 +0000156 bool isStackEmpty() const {
157 return Stack.empty() ||
158 Stack.back().second != CurrentNonCapturingFunctionScope ||
159 Stack.back().first.empty();
160 }
161
Alexey Bataev758e55e2013-09-06 18:03:48 +0000162public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000163 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000164
Alexey Bataevaac108a2015-06-23 04:51:00 +0000165 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
166 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000167
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000168 bool isForceVarCapturing() const { return ForceCapturing; }
169 void setForceVarCapturing(bool V) { ForceCapturing = V; }
170
Alexey Bataev758e55e2013-09-06 18:03:48 +0000171 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000172 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000173 if (Stack.empty() ||
174 Stack.back().second != CurrentNonCapturingFunctionScope)
175 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
176 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
177 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000178 }
179
180 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000181 assert(!Stack.back().first.empty() &&
182 "Data-sharing attributes stack is empty!");
183 Stack.back().first.pop_back();
184 }
185
186 /// Start new OpenMP region stack in new non-capturing function.
187 void pushFunction() {
188 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
189 assert(!isa<CapturingScopeInfo>(CurFnScope));
190 CurrentNonCapturingFunctionScope = CurFnScope;
191 }
192 /// Pop region stack for non-capturing function.
193 void popFunction(const FunctionScopeInfo *OldFSI) {
194 if (!Stack.empty() && Stack.back().second == OldFSI) {
195 assert(Stack.back().first.empty());
196 Stack.pop_back();
197 }
198 CurrentNonCapturingFunctionScope = nullptr;
199 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
200 if (!isa<CapturingScopeInfo>(FSI)) {
201 CurrentNonCapturingFunctionScope = FSI;
202 break;
203 }
204 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000205 }
206
Alexey Bataev28c75412015-12-15 08:19:24 +0000207 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
208 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
209 }
210 const std::pair<OMPCriticalDirective *, llvm::APSInt>
211 getCriticalWithHint(const DeclarationNameInfo &Name) const {
212 auto I = Criticals.find(Name.getAsString());
213 if (I != Criticals.end())
214 return I->second;
215 return std::make_pair(nullptr, llvm::APSInt());
216 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000217 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000218 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000219 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000220 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000221
Alexey Bataev9c821032015-04-30 04:23:23 +0000222 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000223 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000224 /// \brief Check if the specified variable is a loop control variable for
225 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000226 /// \return The index of the loop control variable in the list of associated
227 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000228 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000229 /// \brief Check if the specified variable is a loop control variable for
230 /// parent region.
231 /// \return The index of the loop control variable in the list of associated
232 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000233 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000234 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
235 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000236 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000237
Alexey Bataev758e55e2013-09-06 18:03:48 +0000238 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000239 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
240 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000241
Alexey Bataevfa312f32017-07-21 18:48:21 +0000242 /// Adds additional information for the reduction items with the reduction id
243 /// represented as an operator.
244 void addReductionData(ValueDecl *D, SourceRange SR, BinaryOperatorKind BOK);
245 /// Adds additional information for the reduction items with the reduction id
246 /// represented as reduction identifier.
247 void addReductionData(ValueDecl *D, SourceRange SR, const Expr *ReductionRef);
248 /// Returns the location and reduction operation from the innermost parent
249 /// region for the given \p D.
250 bool getTopMostReductionData(ValueDecl *D, SourceRange &SR,
251 BinaryOperatorKind &BOK);
252 /// Returns the location and reduction operation from the innermost parent
253 /// region for the given \p D.
254 bool getTopMostReductionData(ValueDecl *D, SourceRange &SR,
255 const Expr *&ReductionRef);
256
Alexey Bataev758e55e2013-09-06 18:03:48 +0000257 /// \brief Returns data sharing attributes from top of the stack for the
258 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000259 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000260 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000261 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 /// \brief Checks if the specified variables has data-sharing attributes which
263 /// match specified \a CPred predicate in any directive which matches \a DPred
264 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000265 DSAVarData hasDSA(ValueDecl *D,
266 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
267 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
268 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000269 /// \brief Checks if the specified variables has data-sharing attributes which
270 /// match specified \a CPred predicate in any innermost directive which
271 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000272 DSAVarData
273 hasInnermostDSA(ValueDecl *D,
274 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
275 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
276 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000277 /// \brief Checks if the specified variables has explicit data-sharing
278 /// attributes which match specified \a CPred predicate at the specified
279 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000280 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000281 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000282 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000283
284 /// \brief Returns true if the directive at level \Level matches in the
285 /// specified \a DPred predicate.
286 bool hasExplicitDirective(
287 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
288 unsigned Level);
289
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000290 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000291 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
292 const DeclarationNameInfo &,
293 SourceLocation)> &DPred,
294 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000295
Alexey Bataev758e55e2013-09-06 18:03:48 +0000296 /// \brief Returns currently analyzed directive.
297 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000298 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000299 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000300 /// \brief Returns parent directive.
301 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000302 if (isStackEmpty() || Stack.back().first.size() == 1)
303 return OMPD_unknown;
304 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000305 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000306
307 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000308 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000309 assert(!isStackEmpty());
310 Stack.back().first.back().DefaultAttr = DSA_none;
311 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000312 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000313 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000314 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000315 assert(!isStackEmpty());
316 Stack.back().first.back().DefaultAttr = DSA_shared;
317 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000318 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000319
320 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000321 return isStackEmpty() ? DSA_unspecified
322 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000323 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000324 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000325 return isStackEmpty() ? SourceLocation()
326 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000328
Alexey Bataevf29276e2014-06-18 04:14:57 +0000329 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000330 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000331 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000332 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000333 }
334
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000335 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000336 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000337 assert(!isStackEmpty());
338 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
339 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000340 }
341 /// \brief Returns true, if parent region is ordered (has associated
342 /// 'ordered' clause), false - otherwise.
343 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000344 if (isStackEmpty() || Stack.back().first.size() == 1)
345 return false;
346 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000347 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000348 /// \brief Returns optional parameter for the ordered region.
349 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000350 if (isStackEmpty() || Stack.back().first.size() == 1)
351 return nullptr;
352 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000353 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000354 /// \brief Marks current region as nowait (it has a 'nowait' clause).
355 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000356 assert(!isStackEmpty());
357 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000358 }
359 /// \brief Returns true, if parent region is nowait (has associated
360 /// 'nowait' clause), false - otherwise.
361 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000362 if (isStackEmpty() || Stack.back().first.size() == 1)
363 return false;
364 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000365 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000366 /// \brief Marks parent region as cancel region.
367 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000368 if (!isStackEmpty() && Stack.back().first.size() > 1) {
369 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
370 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
371 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000372 }
373 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000374 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000375 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000376 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000377
Alexey Bataev9c821032015-04-30 04:23:23 +0000378 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000379 void setAssociatedLoops(unsigned Val) {
380 assert(!isStackEmpty());
381 Stack.back().first.back().AssociatedLoops = Val;
382 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000383 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000384 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000385 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000386 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000387
Alexey Bataev13314bf2014-10-09 04:18:56 +0000388 /// \brief Marks current target region as one with closely nested teams
389 /// region.
390 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000391 if (!isStackEmpty() && Stack.back().first.size() > 1) {
392 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
393 TeamsRegionLoc;
394 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000395 }
396 /// \brief Returns true, if current region has closely nested teams region.
397 bool hasInnerTeamsRegion() const {
398 return getInnerTeamsRegionLoc().isValid();
399 }
400 /// \brief Returns location of the nested teams region (if any).
401 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000402 return isStackEmpty() ? SourceLocation()
403 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000404 }
405
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000406 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000407 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000408 }
409 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000410 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000411 }
412 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000413 return isStackEmpty() ? SourceLocation()
414 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000415 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000416
Samuel Antao4c8035b2016-12-12 18:00:20 +0000417 /// Do the check specified in \a Check to all component lists and return true
418 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000419 bool checkMappableExprComponentListsForDecl(
420 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000421 const llvm::function_ref<
422 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
423 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000424 if (isStackEmpty())
425 return false;
426 auto SI = Stack.back().first.rbegin();
427 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000428
429 if (SI == SE)
430 return false;
431
432 if (CurrentRegionOnly) {
433 SE = std::next(SI);
434 } else {
435 ++SI;
436 }
437
438 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000439 auto MI = SI->MappedExprComponents.find(VD);
440 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000441 for (auto &L : MI->second.Components)
442 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000443 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000444 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000445 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000446 }
447
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000448 /// Do the check specified in \a Check to all component lists at a given level
449 /// and return true if any issue is found.
450 bool checkMappableExprComponentListsForDeclAtLevel(
451 ValueDecl *VD, unsigned Level,
452 const llvm::function_ref<
453 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
454 OpenMPClauseKind)> &Check) {
455 if (isStackEmpty())
456 return false;
457
458 auto StartI = Stack.back().first.begin();
459 auto EndI = Stack.back().first.end();
460 if (std::distance(StartI, EndI) <= (int)Level)
461 return false;
462 std::advance(StartI, Level);
463
464 auto MI = StartI->MappedExprComponents.find(VD);
465 if (MI != StartI->MappedExprComponents.end())
466 for (auto &L : MI->second.Components)
467 if (Check(L, MI->second.Kind))
468 return true;
469 return false;
470 }
471
Samuel Antao4c8035b2016-12-12 18:00:20 +0000472 /// Create a new mappable expression component list associated with a given
473 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000474 void addMappableExpressionComponents(
475 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000476 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
477 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000478 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000479 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000480 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000481 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000482 MEC.Components.resize(MEC.Components.size() + 1);
483 MEC.Components.back().append(Components.begin(), Components.end());
484 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000485 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000486
487 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000488 assert(!isStackEmpty());
489 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000490 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000491 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000492 assert(!isStackEmpty() && Stack.back().first.size() > 1);
493 auto &StackElem = *std::next(Stack.back().first.rbegin());
494 assert(isOpenMPWorksharingDirective(StackElem.Directive));
495 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000496 }
497 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
498 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000499 assert(!isStackEmpty());
500 auto &StackElem = Stack.back().first.back();
501 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
502 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000503 return llvm::make_range(Ref.begin(), Ref.end());
504 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000505 return llvm::make_range(StackElem.DoacrossDepends.end(),
506 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000507 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000509bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000510 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
511 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000512}
Alexey Bataeved09d242014-05-28 05:53:51 +0000513} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000514
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000515static Expr *getExprAsWritten(Expr *E) {
516 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
517 E = ExprTemp->getSubExpr();
518
519 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
520 E = MTE->GetTemporaryExpr();
521
522 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
523 E = Binder->getSubExpr();
524
525 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
526 E = ICE->getSubExprAsWritten();
527 return E->IgnoreParens();
528}
529
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000530static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000531 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
532 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
533 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000534 auto *VD = dyn_cast<VarDecl>(D);
535 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000536 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000537 VD = VD->getCanonicalDecl();
538 D = VD;
539 } else {
540 assert(FD);
541 FD = FD->getCanonicalDecl();
542 D = FD;
543 }
544 return D;
545}
546
David Majnemer9d168222016-08-05 17:44:54 +0000547DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000548 ValueDecl *D) {
549 D = getCanonicalDecl(D);
550 auto *VD = dyn_cast<VarDecl>(D);
551 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000552 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000553 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000554 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
555 // in a region but not in construct]
556 // File-scope or namespace-scope variables referenced in called routines
557 // in the region are shared unless they appear in a threadprivate
558 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000560 DVar.CKind = OMPC_shared;
561
562 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
563 // in a region but not in construct]
564 // Variables with static storage duration that are declared in called
565 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000566 if (VD && VD->hasGlobalStorage())
567 DVar.CKind = OMPC_shared;
568
569 // Non-static data members are shared by default.
570 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000571 DVar.CKind = OMPC_shared;
572
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 return DVar;
574 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000575
Alexey Bataevec3da872014-01-31 05:15:34 +0000576 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
577 // in a Construct, C/C++, predetermined, p.1]
578 // Variables with automatic storage duration that are declared in a scope
579 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
581 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000582 DVar.CKind = OMPC_private;
583 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000584 }
585
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000586 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000587 // Explicitly specified attributes and local variables with predetermined
588 // attributes.
589 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000590 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000591 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000592 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000593 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000594 return DVar;
595 }
596
597 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
598 // in a Construct, C/C++, implicitly determined, p.1]
599 // In a parallel or task construct, the data-sharing attributes of these
600 // variables are determined by the default clause, if present.
601 switch (Iter->DefaultAttr) {
602 case DSA_shared:
603 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000604 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000605 return DVar;
606 case DSA_none:
607 return DVar;
608 case DSA_unspecified:
609 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
610 // in a Construct, implicitly determined, p.2]
611 // In a parallel construct, if no default clause is present, these
612 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000613 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000614 if (isOpenMPParallelDirective(DVar.DKind) ||
615 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 DVar.CKind = OMPC_shared;
617 return DVar;
618 }
619
620 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
621 // in a Construct, implicitly determined, p.4]
622 // In a task construct, if no default clause is present, a variable that in
623 // the enclosing context is determined to be shared by all implicit tasks
624 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000625 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000626 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000627 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000628 do {
629 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000630 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000631 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000632 // In a task construct, if no default clause is present, a variable
633 // whose data-sharing attribute is not determined by the rules above is
634 // firstprivate.
635 DVarTemp = getDSA(I, D);
636 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000637 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000638 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000639 return DVar;
640 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000641 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000642 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000643 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000644 return DVar;
645 }
646 }
647 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
648 // in a Construct, implicitly determined, p.3]
649 // For constructs other than task, if no default clause is present, these
650 // variables inherit their data-sharing attributes from the enclosing
651 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000652 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000653}
654
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000655Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000656 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000658 auto &StackElem = Stack.back().first.back();
659 auto It = StackElem.AlignedMap.find(D);
660 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000661 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000662 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000663 return nullptr;
664 } else {
665 assert(It->second && "Unexpected nullptr expr in the aligned map");
666 return It->second;
667 }
668 return nullptr;
669}
670
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000671void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000672 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000673 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000674 auto &StackElem = Stack.back().first.back();
675 StackElem.LCVMap.insert(
676 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000677}
678
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000679DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000680 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000681 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000682 auto &StackElem = Stack.back().first.back();
683 auto It = StackElem.LCVMap.find(D);
684 if (It != StackElem.LCVMap.end())
685 return It->second;
686 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000687}
688
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000689DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000690 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
691 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000692 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000693 auto &StackElem = *std::next(Stack.back().first.rbegin());
694 auto It = StackElem.LCVMap.find(D);
695 if (It != StackElem.LCVMap.end())
696 return It->second;
697 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000698}
699
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000700ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000701 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
702 "Data-sharing attributes stack is empty");
703 auto &StackElem = *std::next(Stack.back().first.rbegin());
704 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000705 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000706 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000707 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000708 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000709 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000710}
711
Alexey Bataev90c228f2016-02-08 09:29:13 +0000712void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
713 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000714 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000715 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000716 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000717 Data.Attributes = A;
718 Data.RefExpr.setPointer(E);
719 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000720 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000721 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
722 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000723 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
724 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
725 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
726 (isLoopControlVariable(D).first && A == OMPC_private));
727 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
728 Data.RefExpr.setInt(/*IntVal=*/true);
729 return;
730 }
731 const bool IsLastprivate =
732 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
733 Data.Attributes = A;
734 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
735 Data.PrivateCopy = PrivateCopy;
736 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000737 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000738 Data.Attributes = A;
739 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
740 Data.PrivateCopy = nullptr;
741 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000742 }
743}
744
Alexey Bataevfa312f32017-07-21 18:48:21 +0000745void DSAStackTy::addReductionData(ValueDecl *D, SourceRange SR,
746 BinaryOperatorKind BOK) {
747 D = getCanonicalDecl(D);
748 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
749 auto &Data = Stack.back().first.back().SharingMap[D];
750 assert(
751 Data.Attributes == OMPC_reduction &&
752 "Additional reduction info may be specified only for reduction items.");
753 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
754 assert(ReductionData.ReductionRange.isInvalid() &&
755 "Additional reduction info may be specified only once for reduction "
756 "items.");
757 ReductionData.set(BOK, SR);
758}
759
760void DSAStackTy::addReductionData(ValueDecl *D, SourceRange SR,
761 const Expr *ReductionRef) {
762 D = getCanonicalDecl(D);
763 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
764 auto &Data = Stack.back().first.back().SharingMap[D];
765 assert(
766 Data.Attributes == OMPC_reduction &&
767 "Additional reduction info may be specified only for reduction items.");
768 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
769 assert(ReductionData.ReductionRange.isInvalid() &&
770 "Additional reduction info may be specified only once for reduction "
771 "items.");
772 ReductionData.set(ReductionRef, SR);
773}
774
775bool DSAStackTy::getTopMostReductionData(ValueDecl *D, SourceRange &SR,
776 BinaryOperatorKind &BOK) {
777 D = getCanonicalDecl(D);
778 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
779 "Data-sharing attributes stack is empty or has only 1 region.");
780 for (auto I = std::next(Stack.back().first.rbegin(), 0),
781 E = Stack.back().first.rend();
782 I != E; std::advance(I, 1)) {
783 auto &Data = I->SharingMap[D];
784 if (Data.Attributes != OMPC_reduction)
785 continue;
786 auto &ReductionData = I->ReductionMap[D];
787 if (!ReductionData.ReductionOp ||
788 ReductionData.ReductionOp.is<const Expr *>())
789 return false;
790 SR = ReductionData.ReductionRange;
791 BOK = ReductionData.ReductionOp
792 .get<llvm::PointerEmbeddedInt<BinaryOperatorKind>>();
793 return true;
794 }
795 return false;
796}
797
798bool DSAStackTy::getTopMostReductionData(ValueDecl *D, SourceRange &SR,
799 const Expr *&ReductionRef) {
800 D = getCanonicalDecl(D);
801 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
802 "Data-sharing attributes stack is empty or has only 1 region.");
803 for (auto I = std::next(Stack.back().first.rbegin(), 0),
804 E = Stack.back().first.rend();
805 I != E; std::advance(I, 1)) {
806 auto &Data = I->SharingMap[D];
807 if (Data.Attributes != OMPC_reduction)
808 continue;
809 auto &ReductionData = I->ReductionMap[D];
810 if (!ReductionData.ReductionOp ||
811 !ReductionData.ReductionOp.is<const Expr *>())
812 return false;
813 SR = ReductionData.ReductionRange;
814 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
815 return true;
816 }
817 return false;
818}
819
Alexey Bataeved09d242014-05-28 05:53:51 +0000820bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000821 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000822 if (!isStackEmpty() && Stack.back().first.size() > 1) {
823 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000824 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000825 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000826 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000827 if (I == E)
828 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000829 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000830 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000831 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000832 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000833 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000834 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000835 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836}
837
Alexey Bataev39f915b82015-05-08 10:41:21 +0000838/// \brief Build a variable declaration for OpenMP loop iteration variable.
839static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000840 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000841 DeclContext *DC = SemaRef.CurContext;
842 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
843 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
844 VarDecl *Decl =
845 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000846 if (Attrs) {
847 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
848 I != E; ++I)
849 Decl->addAttr(*I);
850 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000851 Decl->setImplicit();
852 return Decl;
853}
854
855static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
856 SourceLocation Loc,
857 bool RefersToCapture = false) {
858 D->setReferenced();
859 D->markUsed(S.Context);
860 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
861 SourceLocation(), D, RefersToCapture, Loc, Ty,
862 VK_LValue);
863}
864
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000865DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
866 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000867 DSAVarData DVar;
868
869 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
870 // in a Construct, C/C++, predetermined, p.1]
871 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000872 auto *VD = dyn_cast<VarDecl>(D);
873 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
874 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000875 SemaRef.getLangOpts().OpenMPUseTLS &&
876 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000877 (VD && VD->getStorageClass() == SC_Register &&
878 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
879 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000880 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000881 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000882 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000883 auto TI = Threadprivates.find(D);
884 if (TI != Threadprivates.end()) {
885 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000886 DVar.CKind = OMPC_threadprivate;
887 return DVar;
888 }
889
Alexey Bataev4b465392017-04-26 15:06:24 +0000890 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000891 // Not in OpenMP execution region and top scope was already checked.
892 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000893
Alexey Bataev758e55e2013-09-06 18:03:48 +0000894 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000895 // in a Construct, C/C++, predetermined, p.4]
896 // Static data members are shared.
897 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
898 // in a Construct, C/C++, predetermined, p.7]
899 // Variables with static storage duration that are declared in a scope
900 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000901 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000902 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000903 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000904 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000905 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000906
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000907 DVar.CKind = OMPC_shared;
908 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000909 }
910
911 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000912 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
913 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000914 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
915 // in a Construct, C/C++, predetermined, p.6]
916 // Variables with const qualified type having no mutable member are
917 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000918 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000919 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000920 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
921 if (auto *CTD = CTSD->getSpecializedTemplate())
922 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000923 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000924 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
925 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000926 // Variables with const-qualified type having no mutable member may be
927 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000928 DSAVarData DVarTemp = hasDSA(
929 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
930 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000931 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
932 return DVar;
933
Alexey Bataev758e55e2013-09-06 18:03:48 +0000934 DVar.CKind = OMPC_shared;
935 return DVar;
936 }
937
Alexey Bataev758e55e2013-09-06 18:03:48 +0000938 // Explicitly specified attributes and local variables with predetermined
939 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000940 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000941 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000942 if (FromParent && I != EndI)
943 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000944 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000945 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000946 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000947 DVar.CKind = I->SharingMap[D].Attributes;
948 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000949 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000950 }
951
952 return DVar;
953}
954
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000955DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
956 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000957 if (isStackEmpty()) {
958 StackTy::reverse_iterator I;
959 return getDSA(I, D);
960 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000961 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000962 auto StartI = Stack.back().first.rbegin();
963 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000964 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000965 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000966 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000967}
968
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000969DSAStackTy::DSAVarData
970DSAStackTy::hasDSA(ValueDecl *D,
971 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
972 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
973 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000974 if (isStackEmpty())
975 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000976 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000977 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000978 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000979 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +0000980 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000981 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000982 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000983 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000984 auto NewI = I;
985 DSAVarData DVar = getDSA(NewI, D);
986 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000987 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +0000988 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000989 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000990}
991
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000992DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
993 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
994 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
995 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000996 if (isStackEmpty())
997 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000998 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000999 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001000 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001001 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001002 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001003 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001004 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001005 auto NewI = StartI;
1006 DSAVarData DVar = getDSA(NewI, D);
1007 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001008}
1009
Alexey Bataevaac108a2015-06-23 04:51:00 +00001010bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001011 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001012 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001013 if (CPred(ClauseKindMode))
1014 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001015 if (isStackEmpty())
1016 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001018 auto StartI = Stack.back().first.begin();
1019 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001020 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001021 return false;
1022 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001023 return (StartI->SharingMap.count(D) > 0) &&
1024 StartI->SharingMap[D].RefExpr.getPointer() &&
1025 CPred(StartI->SharingMap[D].Attributes) &&
1026 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001027}
1028
Samuel Antao4be30e92015-10-02 17:14:03 +00001029bool DSAStackTy::hasExplicitDirective(
1030 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1031 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001032 if (isStackEmpty())
1033 return false;
1034 auto StartI = Stack.back().first.begin();
1035 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001036 if (std::distance(StartI, EndI) <= (int)Level)
1037 return false;
1038 std::advance(StartI, Level);
1039 return DPred(StartI->Directive);
1040}
1041
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001042bool DSAStackTy::hasDirective(
1043 const llvm::function_ref<bool(OpenMPDirectiveKind,
1044 const DeclarationNameInfo &, SourceLocation)>
1045 &DPred,
1046 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001047 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001048 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001049 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001050 auto StartI = std::next(Stack.back().first.rbegin());
1051 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001052 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001053 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001054 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1055 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1056 return true;
1057 }
1058 return false;
1059}
1060
Alexey Bataev758e55e2013-09-06 18:03:48 +00001061void Sema::InitDataSharingAttributesStack() {
1062 VarDataSharingAttributesStack = new DSAStackTy(*this);
1063}
1064
1065#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1066
Alexey Bataev4b465392017-04-26 15:06:24 +00001067void Sema::pushOpenMPFunctionRegion() {
1068 DSAStack->pushFunction();
1069}
1070
1071void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1072 DSAStack->popFunction(OldFSI);
1073}
1074
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001075bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001076 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1077
1078 auto &Ctx = getASTContext();
1079 bool IsByRef = true;
1080
1081 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001082 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001083
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001084 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001085 // This table summarizes how a given variable should be passed to the device
1086 // given its type and the clauses where it appears. This table is based on
1087 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1088 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1089 //
1090 // =========================================================================
1091 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1092 // | |(tofrom:scalar)| | pvt | | | |
1093 // =========================================================================
1094 // | scl | | | | - | | bycopy|
1095 // | scl | | - | x | - | - | bycopy|
1096 // | scl | | x | - | - | - | null |
1097 // | scl | x | | | - | | byref |
1098 // | scl | x | - | x | - | - | bycopy|
1099 // | scl | x | x | - | - | - | null |
1100 // | scl | | - | - | - | x | byref |
1101 // | scl | x | - | - | - | x | byref |
1102 //
1103 // | agg | n.a. | | | - | | byref |
1104 // | agg | n.a. | - | x | - | - | byref |
1105 // | agg | n.a. | x | - | - | - | null |
1106 // | agg | n.a. | - | - | - | x | byref |
1107 // | agg | n.a. | - | - | - | x[] | byref |
1108 //
1109 // | ptr | n.a. | | | - | | bycopy|
1110 // | ptr | n.a. | - | x | - | - | bycopy|
1111 // | ptr | n.a. | x | - | - | - | null |
1112 // | ptr | n.a. | - | - | - | x | byref |
1113 // | ptr | n.a. | - | - | - | x[] | bycopy|
1114 // | ptr | n.a. | - | - | x | | bycopy|
1115 // | ptr | n.a. | - | - | x | x | bycopy|
1116 // | ptr | n.a. | - | - | x | x[] | bycopy|
1117 // =========================================================================
1118 // Legend:
1119 // scl - scalar
1120 // ptr - pointer
1121 // agg - aggregate
1122 // x - applies
1123 // - - invalid in this combination
1124 // [] - mapped with an array section
1125 // byref - should be mapped by reference
1126 // byval - should be mapped by value
1127 // null - initialize a local variable to null on the device
1128 //
1129 // Observations:
1130 // - All scalar declarations that show up in a map clause have to be passed
1131 // by reference, because they may have been mapped in the enclosing data
1132 // environment.
1133 // - If the scalar value does not fit the size of uintptr, it has to be
1134 // passed by reference, regardless the result in the table above.
1135 // - For pointers mapped by value that have either an implicit map or an
1136 // array section, the runtime library may pass the NULL value to the
1137 // device instead of the value passed to it by the compiler.
1138
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001139 if (Ty->isReferenceType())
1140 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001141
1142 // Locate map clauses and see if the variable being captured is referred to
1143 // in any of those clauses. Here we only care about variables, not fields,
1144 // because fields are part of aggregates.
1145 bool IsVariableUsedInMapClause = false;
1146 bool IsVariableAssociatedWithSection = false;
1147
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001148 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1149 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001150 MapExprComponents,
1151 OpenMPClauseKind WhereFoundClauseKind) {
1152 // Only the map clause information influences how a variable is
1153 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001154 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001155 if (WhereFoundClauseKind != OMPC_map)
1156 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001157
1158 auto EI = MapExprComponents.rbegin();
1159 auto EE = MapExprComponents.rend();
1160
1161 assert(EI != EE && "Invalid map expression!");
1162
1163 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1164 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1165
1166 ++EI;
1167 if (EI == EE)
1168 return false;
1169
1170 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1171 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1172 isa<MemberExpr>(EI->getAssociatedExpression())) {
1173 IsVariableAssociatedWithSection = true;
1174 // There is nothing more we need to know about this variable.
1175 return true;
1176 }
1177
1178 // Keep looking for more map info.
1179 return false;
1180 });
1181
1182 if (IsVariableUsedInMapClause) {
1183 // If variable is identified in a map clause it is always captured by
1184 // reference except if it is a pointer that is dereferenced somehow.
1185 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1186 } else {
1187 // By default, all the data that has a scalar type is mapped by copy.
1188 IsByRef = !Ty->isScalarType();
1189 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001190 }
1191
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001192 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1193 IsByRef = !DSAStack->hasExplicitDSA(
1194 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1195 Level, /*NotLastprivate=*/true);
1196 }
1197
Samuel Antao86ace552016-04-27 22:40:57 +00001198 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001199 // and alignment, because the runtime library only deals with uintptr types.
1200 // If it does not fit the uintptr size, we need to pass the data by reference
1201 // instead.
1202 if (!IsByRef &&
1203 (Ctx.getTypeSizeInChars(Ty) >
1204 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001205 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001206 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001207 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001208
1209 return IsByRef;
1210}
1211
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001212unsigned Sema::getOpenMPNestingLevel() const {
1213 assert(getLangOpts().OpenMP);
1214 return DSAStack->getNestingLevel();
1215}
1216
Alexey Bataev90c228f2016-02-08 09:29:13 +00001217VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001218 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001219 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001220
1221 // If we are attempting to capture a global variable in a directive with
1222 // 'target' we return true so that this global is also mapped to the device.
1223 //
1224 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1225 // then it should not be captured. Therefore, an extra check has to be
1226 // inserted here once support for 'declare target' is added.
1227 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001228 auto *VD = dyn_cast<VarDecl>(D);
1229 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001230 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001231 !DSAStack->isClauseParsingMode())
1232 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001233 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001234 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1235 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001236 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001237 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001238 false))
1239 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001240 }
1241
Alexey Bataev48977c32015-08-04 08:10:48 +00001242 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1243 (!DSAStack->isClauseParsingMode() ||
1244 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001245 auto &&Info = DSAStack->isLoopControlVariable(D);
1246 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001247 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001248 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001249 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001250 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001251 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001252 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001253 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001254 DVarPrivate = DSAStack->hasDSA(
1255 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1256 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001257 if (DVarPrivate.CKind != OMPC_unknown)
1258 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001259 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001260 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001261}
1262
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001263bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001264 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1265 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001266 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001267}
1268
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001269bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001270 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1271 // Return true if the current level is no longer enclosed in a target region.
1272
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001273 auto *VD = dyn_cast<VarDecl>(D);
1274 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001275 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1276 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001277}
1278
Alexey Bataeved09d242014-05-28 05:53:51 +00001279void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001280
1281void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1282 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001283 Scope *CurScope, SourceLocation Loc) {
1284 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001285 PushExpressionEvaluationContext(
1286 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001287}
1288
Alexey Bataevaac108a2015-06-23 04:51:00 +00001289void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1290 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001291}
1292
Alexey Bataevaac108a2015-06-23 04:51:00 +00001293void Sema::EndOpenMPClause() {
1294 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001295}
1296
Alexey Bataev758e55e2013-09-06 18:03:48 +00001297void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001298 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1299 // A variable of class type (or array thereof) that appears in a lastprivate
1300 // clause requires an accessible, unambiguous default constructor for the
1301 // class type, unless the list item is also specified in a firstprivate
1302 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001303 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001304 for (auto *C : D->clauses()) {
1305 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1306 SmallVector<Expr *, 8> PrivateCopies;
1307 for (auto *DE : Clause->varlists()) {
1308 if (DE->isValueDependent() || DE->isTypeDependent()) {
1309 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001310 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001311 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001312 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001313 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1314 QualType Type = VD->getType().getNonReferenceType();
1315 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001316 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001317 // Generate helper private variable and initialize it with the
1318 // default value. The address of the original variable is replaced
1319 // by the address of the new private variable in CodeGen. This new
1320 // variable is not added to IdResolver, so the code in the OpenMP
1321 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001322 auto *VDPrivate = buildVarDecl(
1323 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001324 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001325 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001326 if (VDPrivate->isInvalidDecl())
1327 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001328 PrivateCopies.push_back(buildDeclRefExpr(
1329 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001330 } else {
1331 // The variable is also a firstprivate, so initialization sequence
1332 // for private copy is generated already.
1333 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001334 }
1335 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001336 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001337 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001338 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001339 }
1340 }
1341 }
1342
Alexey Bataev758e55e2013-09-06 18:03:48 +00001343 DSAStack->pop();
1344 DiscardCleanupsInEvaluationContext();
1345 PopExpressionEvaluationContext();
1346}
1347
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001348static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1349 Expr *NumIterations, Sema &SemaRef,
1350 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001351
Alexey Bataeva769e072013-03-22 06:34:35 +00001352namespace {
1353
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001354class VarDeclFilterCCC : public CorrectionCandidateCallback {
1355private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001356 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001357
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001358public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001359 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001360 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001361 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001362 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001363 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001364 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1365 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001366 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001367 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001368 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001369};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001370
1371class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1372private:
1373 Sema &SemaRef;
1374
1375public:
1376 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1377 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1378 NamedDecl *ND = Candidate.getCorrectionDecl();
1379 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1380 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1381 SemaRef.getCurScope());
1382 }
1383 return false;
1384 }
1385};
1386
Alexey Bataeved09d242014-05-28 05:53:51 +00001387} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001388
1389ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1390 CXXScopeSpec &ScopeSpec,
1391 const DeclarationNameInfo &Id) {
1392 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1393 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1394
1395 if (Lookup.isAmbiguous())
1396 return ExprError();
1397
1398 VarDecl *VD;
1399 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001400 if (TypoCorrection Corrected = CorrectTypo(
1401 Id, LookupOrdinaryName, CurScope, nullptr,
1402 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001403 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001404 PDiag(Lookup.empty()
1405 ? diag::err_undeclared_var_use_suggest
1406 : diag::err_omp_expected_var_arg_suggest)
1407 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001408 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001409 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001410 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1411 : diag::err_omp_expected_var_arg)
1412 << Id.getName();
1413 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001414 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001415 } else {
1416 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001417 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001418 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1419 return ExprError();
1420 }
1421 }
1422 Lookup.suppressDiagnostics();
1423
1424 // OpenMP [2.9.2, Syntax, C/C++]
1425 // Variables must be file-scope, namespace-scope, or static block-scope.
1426 if (!VD->hasGlobalStorage()) {
1427 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001428 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1429 bool IsDecl =
1430 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001431 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001432 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1433 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001434 return ExprError();
1435 }
1436
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001437 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1438 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001439 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1440 // A threadprivate directive for file-scope variables must appear outside
1441 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001442 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1443 !getCurLexicalContext()->isTranslationUnit()) {
1444 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001445 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1446 bool IsDecl =
1447 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1448 Diag(VD->getLocation(),
1449 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1450 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001451 return ExprError();
1452 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001453 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1454 // A threadprivate directive for static class member variables must appear
1455 // in the class definition, in the same scope in which the member
1456 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001457 if (CanonicalVD->isStaticDataMember() &&
1458 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1459 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001460 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1461 bool IsDecl =
1462 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1463 Diag(VD->getLocation(),
1464 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1465 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001466 return ExprError();
1467 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001468 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1469 // A threadprivate directive for namespace-scope variables must appear
1470 // outside any definition or declaration other than the namespace
1471 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001472 if (CanonicalVD->getDeclContext()->isNamespace() &&
1473 (!getCurLexicalContext()->isFileContext() ||
1474 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1475 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001476 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1477 bool IsDecl =
1478 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1479 Diag(VD->getLocation(),
1480 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1481 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001482 return ExprError();
1483 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001484 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1485 // A threadprivate directive for static block-scope variables must appear
1486 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001487 if (CanonicalVD->isStaticLocal() && CurScope &&
1488 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001489 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001490 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1491 bool IsDecl =
1492 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1493 Diag(VD->getLocation(),
1494 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1495 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001496 return ExprError();
1497 }
1498
1499 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1500 // A threadprivate directive must lexically precede all references to any
1501 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001502 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001503 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001504 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001505 return ExprError();
1506 }
1507
1508 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001509 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1510 SourceLocation(), VD,
1511 /*RefersToEnclosingVariableOrCapture=*/false,
1512 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001513}
1514
Alexey Bataeved09d242014-05-28 05:53:51 +00001515Sema::DeclGroupPtrTy
1516Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1517 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001518 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001519 CurContext->addDecl(D);
1520 return DeclGroupPtrTy::make(DeclGroupRef(D));
1521 }
David Blaikie0403cb12016-01-15 23:43:25 +00001522 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001523}
1524
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001525namespace {
1526class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1527 Sema &SemaRef;
1528
1529public:
1530 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001531 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001532 if (VD->hasLocalStorage()) {
1533 SemaRef.Diag(E->getLocStart(),
1534 diag::err_omp_local_var_in_threadprivate_init)
1535 << E->getSourceRange();
1536 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1537 << VD << VD->getSourceRange();
1538 return true;
1539 }
1540 }
1541 return false;
1542 }
1543 bool VisitStmt(const Stmt *S) {
1544 for (auto Child : S->children()) {
1545 if (Child && Visit(Child))
1546 return true;
1547 }
1548 return false;
1549 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001550 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001551};
1552} // namespace
1553
Alexey Bataeved09d242014-05-28 05:53:51 +00001554OMPThreadPrivateDecl *
1555Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001556 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001557 for (auto &RefExpr : VarList) {
1558 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001559 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1560 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001561
Alexey Bataev376b4a42016-02-09 09:41:09 +00001562 // Mark variable as used.
1563 VD->setReferenced();
1564 VD->markUsed(Context);
1565
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001566 QualType QType = VD->getType();
1567 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1568 // It will be analyzed later.
1569 Vars.push_back(DE);
1570 continue;
1571 }
1572
Alexey Bataeva769e072013-03-22 06:34:35 +00001573 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1574 // A threadprivate variable must not have an incomplete type.
1575 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001576 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001577 continue;
1578 }
1579
1580 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1581 // A threadprivate variable must not have a reference type.
1582 if (VD->getType()->isReferenceType()) {
1583 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001584 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1585 bool IsDecl =
1586 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1587 Diag(VD->getLocation(),
1588 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1589 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001590 continue;
1591 }
1592
Samuel Antaof8b50122015-07-13 22:54:53 +00001593 // Check if this is a TLS variable. If TLS is not being supported, produce
1594 // the corresponding diagnostic.
1595 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1596 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1597 getLangOpts().OpenMPUseTLS &&
1598 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001599 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1600 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001601 Diag(ILoc, diag::err_omp_var_thread_local)
1602 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001603 bool IsDecl =
1604 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1605 Diag(VD->getLocation(),
1606 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1607 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001608 continue;
1609 }
1610
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001611 // Check if initial value of threadprivate variable reference variable with
1612 // local storage (it is not supported by runtime).
1613 if (auto Init = VD->getAnyInitializer()) {
1614 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001615 if (Checker.Visit(Init))
1616 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001617 }
1618
Alexey Bataeved09d242014-05-28 05:53:51 +00001619 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001620 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001621 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1622 Context, SourceRange(Loc, Loc)));
1623 if (auto *ML = Context.getASTMutationListener())
1624 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001625 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001626 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001627 if (!Vars.empty()) {
1628 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1629 Vars);
1630 D->setAccess(AS_public);
1631 }
1632 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001633}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001634
Alexey Bataev7ff55242014-06-19 09:13:45 +00001635static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001636 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001637 bool IsLoopIterVar = false) {
1638 if (DVar.RefExpr) {
1639 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1640 << getOpenMPClauseName(DVar.CKind);
1641 return;
1642 }
1643 enum {
1644 PDSA_StaticMemberShared,
1645 PDSA_StaticLocalVarShared,
1646 PDSA_LoopIterVarPrivate,
1647 PDSA_LoopIterVarLinear,
1648 PDSA_LoopIterVarLastprivate,
1649 PDSA_ConstVarShared,
1650 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001651 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001652 PDSA_LocalVarPrivate,
1653 PDSA_Implicit
1654 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001655 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001656 auto ReportLoc = D->getLocation();
1657 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001658 if (IsLoopIterVar) {
1659 if (DVar.CKind == OMPC_private)
1660 Reason = PDSA_LoopIterVarPrivate;
1661 else if (DVar.CKind == OMPC_lastprivate)
1662 Reason = PDSA_LoopIterVarLastprivate;
1663 else
1664 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001665 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1666 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001667 Reason = PDSA_TaskVarFirstprivate;
1668 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001669 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001670 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001671 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001672 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001673 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001674 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001675 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001676 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001677 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001678 ReportHint = true;
1679 Reason = PDSA_LocalVarPrivate;
1680 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001681 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001682 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001683 << Reason << ReportHint
1684 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1685 } else if (DVar.ImplicitDSALoc.isValid()) {
1686 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1687 << getOpenMPClauseName(DVar.CKind);
1688 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001689}
1690
Alexey Bataev758e55e2013-09-06 18:03:48 +00001691namespace {
1692class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1693 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001694 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001695 bool ErrorFound;
1696 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001697 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001698 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001699
Alexey Bataev758e55e2013-09-06 18:03:48 +00001700public:
1701 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001702 if (E->isTypeDependent() || E->isValueDependent() ||
1703 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1704 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001705 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001706 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001707 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1708 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001709
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001710 auto DVar = Stack->getTopDSA(VD, false);
1711 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001712 if (DVar.RefExpr)
1713 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001714
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001715 auto ELoc = E->getExprLoc();
1716 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001717 // The default(none) clause requires that each variable that is referenced
1718 // in the construct, and does not have a predetermined data-sharing
1719 // attribute, must have its data-sharing attribute explicitly determined
1720 // by being listed in a data-sharing attribute clause.
1721 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001722 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001723 VarsWithInheritedDSA.count(VD) == 0) {
1724 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001725 return;
1726 }
1727
1728 // OpenMP [2.9.3.6, Restrictions, p.2]
1729 // A list item that appears in a reduction clause of the innermost
1730 // enclosing worksharing or parallel construct may not be accessed in an
1731 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001732 DVar = Stack->hasInnermostDSA(
1733 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1734 [](OpenMPDirectiveKind K) -> bool {
1735 return isOpenMPParallelDirective(K) ||
1736 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1737 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001738 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001739 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001740 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001741 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1742 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001743 return;
1744 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001745
1746 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001747 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001748 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1749 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001750 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001751 }
1752 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001753 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001754 if (E->isTypeDependent() || E->isValueDependent() ||
1755 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1756 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001757 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1758 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1759 auto DVar = Stack->getTopDSA(FD, false);
1760 // Check if the variable has explicit DSA set and stop analysis if it
1761 // so.
1762 if (DVar.RefExpr)
1763 return;
1764
1765 auto ELoc = E->getExprLoc();
1766 auto DKind = Stack->getCurrentDirective();
1767 // OpenMP [2.9.3.6, Restrictions, p.2]
1768 // A list item that appears in a reduction clause of the innermost
1769 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001770 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001771 DVar = Stack->hasInnermostDSA(
1772 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1773 [](OpenMPDirectiveKind K) -> bool {
1774 return isOpenMPParallelDirective(K) ||
1775 isOpenMPWorksharingDirective(K) ||
1776 isOpenMPTeamsDirective(K);
1777 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001778 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001779 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001780 ErrorFound = true;
1781 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1782 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1783 return;
1784 }
1785
1786 // Define implicit data-sharing attributes for task.
1787 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001788 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1789 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001790 ImplicitFirstprivate.push_back(E);
1791 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001792 } else
1793 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001794 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001795 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001796 for (auto *C : S->clauses()) {
1797 // Skip analysis of arguments of implicitly defined firstprivate clause
1798 // for task directives.
1799 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1800 for (auto *CC : C->children()) {
1801 if (CC)
1802 Visit(CC);
1803 }
1804 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001805 }
1806 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001807 for (auto *C : S->children()) {
1808 if (C && !isa<OMPExecutableDirective>(C))
1809 Visit(C);
1810 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001811 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001812
1813 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001814 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001815 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001816 return VarsWithInheritedDSA;
1817 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001818
Alexey Bataev7ff55242014-06-19 09:13:45 +00001819 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1820 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001821};
Alexey Bataeved09d242014-05-28 05:53:51 +00001822} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001823
Alexey Bataevbae9a792014-06-27 10:37:06 +00001824void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001825 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001826 case OMPD_parallel:
1827 case OMPD_parallel_for:
1828 case OMPD_parallel_for_simd:
1829 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001830 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001831 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001832 QualType KmpInt32PtrTy =
1833 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001834 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001835 std::make_pair(".global_tid.", KmpInt32PtrTy),
1836 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1837 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001838 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001839 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1840 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001841 break;
1842 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001843 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001844 case OMPD_target_parallel: {
1845 Sema::CapturedParamNameType ParamsTarget[] = {
1846 std::make_pair(StringRef(), QualType()) // __context with shared vars
1847 };
1848 // Start a captured region for 'target' with no implicit parameters.
1849 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1850 ParamsTarget);
1851 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1852 QualType KmpInt32PtrTy =
1853 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001854 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001855 std::make_pair(".global_tid.", KmpInt32PtrTy),
1856 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1857 std::make_pair(StringRef(), QualType()) // __context with shared vars
1858 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001859 // Start a captured region for 'teams' or 'parallel'. Both regions have
1860 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001861 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001862 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001863 break;
1864 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001865 case OMPD_simd:
1866 case OMPD_for:
1867 case OMPD_for_simd:
1868 case OMPD_sections:
1869 case OMPD_section:
1870 case OMPD_single:
1871 case OMPD_master:
1872 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001873 case OMPD_taskgroup:
1874 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001875 case OMPD_ordered:
1876 case OMPD_atomic:
1877 case OMPD_target_data:
1878 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001879 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001880 case OMPD_target_parallel_for_simd:
1881 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001882 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001883 std::make_pair(StringRef(), QualType()) // __context with shared vars
1884 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001885 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1886 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001887 break;
1888 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001889 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001890 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001891 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1892 FunctionProtoType::ExtProtoInfo EPI;
1893 EPI.Variadic = true;
1894 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001895 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001896 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001897 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1898 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1899 std::make_pair(".copy_fn.",
1900 Context.getPointerType(CopyFnType).withConst()),
1901 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001902 std::make_pair(StringRef(), QualType()) // __context with shared vars
1903 };
1904 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1905 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001906 // Mark this captured region as inlined, because we don't use outlined
1907 // function directly.
1908 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1909 AlwaysInlineAttr::CreateImplicit(
1910 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001911 break;
1912 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001913 case OMPD_taskloop:
1914 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001915 QualType KmpInt32Ty =
1916 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1917 QualType KmpUInt64Ty =
1918 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1919 QualType KmpInt64Ty =
1920 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1921 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1922 FunctionProtoType::ExtProtoInfo EPI;
1923 EPI.Variadic = true;
1924 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001925 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001926 std::make_pair(".global_tid.", KmpInt32Ty),
1927 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1928 std::make_pair(".privates.",
1929 Context.VoidPtrTy.withConst().withRestrict()),
1930 std::make_pair(
1931 ".copy_fn.",
1932 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1933 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1934 std::make_pair(".lb.", KmpUInt64Ty),
1935 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1936 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001937 std::make_pair(".reductions.",
1938 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001939 std::make_pair(StringRef(), QualType()) // __context with shared vars
1940 };
1941 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1942 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001943 // Mark this captured region as inlined, because we don't use outlined
1944 // function directly.
1945 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1946 AlwaysInlineAttr::CreateImplicit(
1947 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001948 break;
1949 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001950 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001951 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001952 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001953 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001954 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001955 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001956 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001957 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001958 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001959 case OMPD_target_teams_distribute_parallel_for_simd:
1960 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001961 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1962 QualType KmpInt32PtrTy =
1963 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1964 Sema::CapturedParamNameType Params[] = {
1965 std::make_pair(".global_tid.", KmpInt32PtrTy),
1966 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1967 std::make_pair(".previous.lb.", Context.getSizeType()),
1968 std::make_pair(".previous.ub.", Context.getSizeType()),
1969 std::make_pair(StringRef(), QualType()) // __context with shared vars
1970 };
1971 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1972 Params);
1973 break;
1974 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001975 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001976 case OMPD_taskyield:
1977 case OMPD_barrier:
1978 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001979 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001980 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001981 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001982 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001983 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001984 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001985 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001986 case OMPD_declare_target:
1987 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001988 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001989 llvm_unreachable("OpenMP Directive is not allowed");
1990 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001991 llvm_unreachable("Unknown OpenMP directive");
1992 }
1993}
1994
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001995int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1996 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1997 getOpenMPCaptureRegions(CaptureRegions, DKind);
1998 return CaptureRegions.size();
1999}
2000
Alexey Bataev3392d762016-02-16 11:18:12 +00002001static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002002 Expr *CaptureExpr, bool WithInit,
2003 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002004 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002005 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002006 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002007 QualType Ty = Init->getType();
2008 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2009 if (S.getLangOpts().CPlusPlus)
2010 Ty = C.getLValueReferenceType(Ty);
2011 else {
2012 Ty = C.getPointerType(Ty);
2013 ExprResult Res =
2014 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2015 if (!Res.isUsable())
2016 return nullptr;
2017 Init = Res.get();
2018 }
Alexey Bataev61205072016-03-02 04:57:40 +00002019 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002020 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002021 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2022 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002023 if (!WithInit)
2024 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002025 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002026 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002027 return CED;
2028}
2029
Alexey Bataev61205072016-03-02 04:57:40 +00002030static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2031 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002032 OMPCapturedExprDecl *CD;
2033 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2034 CD = cast<OMPCapturedExprDecl>(VD);
2035 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002036 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2037 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002038 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002039 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002040}
2041
Alexey Bataev5a3af132016-03-29 08:58:54 +00002042static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2043 if (!Ref) {
2044 auto *CD =
2045 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2046 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2047 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2048 CaptureExpr->getExprLoc());
2049 }
2050 ExprResult Res = Ref;
2051 if (!S.getLangOpts().CPlusPlus &&
2052 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2053 Ref->getType()->isPointerType())
2054 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2055 if (!Res.isUsable())
2056 return ExprError();
2057 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002058}
2059
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002060namespace {
2061// OpenMP directives parsed in this section are represented as a
2062// CapturedStatement with an associated statement. If a syntax error
2063// is detected during the parsing of the associated statement, the
2064// compiler must abort processing and close the CapturedStatement.
2065//
2066// Combined directives such as 'target parallel' have more than one
2067// nested CapturedStatements. This RAII ensures that we unwind out
2068// of all the nested CapturedStatements when an error is found.
2069class CaptureRegionUnwinderRAII {
2070private:
2071 Sema &S;
2072 bool &ErrorFound;
2073 OpenMPDirectiveKind DKind;
2074
2075public:
2076 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2077 OpenMPDirectiveKind DKind)
2078 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2079 ~CaptureRegionUnwinderRAII() {
2080 if (ErrorFound) {
2081 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2082 while (--ThisCaptureLevel >= 0)
2083 S.ActOnCapturedRegionError();
2084 }
2085 }
2086};
2087} // namespace
2088
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002089StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2090 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002091 bool ErrorFound = false;
2092 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2093 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002094 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002095 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002096 return StmtError();
2097 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002098
2099 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002100 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002101 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002102 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002103 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002104 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002105 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002106 Clause->getClauseKind() == OMPC_copyprivate ||
2107 (getLangOpts().OpenMPUseTLS &&
2108 getASTContext().getTargetInfo().isTLSSupported() &&
2109 Clause->getClauseKind() == OMPC_copyin)) {
2110 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002111 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002112 for (auto *VarRef : Clause->children()) {
2113 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002114 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002115 }
2116 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002117 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002118 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002119 if (auto *C = OMPClauseWithPreInit::get(Clause))
2120 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002121 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2122 if (auto *E = C->getPostUpdateExpr())
2123 MarkDeclarationsReferencedInExpr(E);
2124 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002125 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002126 if (Clause->getClauseKind() == OMPC_schedule)
2127 SC = cast<OMPScheduleClause>(Clause);
2128 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002129 OC = cast<OMPOrderedClause>(Clause);
2130 else if (Clause->getClauseKind() == OMPC_linear)
2131 LCs.push_back(cast<OMPLinearClause>(Clause));
2132 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002133 // OpenMP, 2.7.1 Loop Construct, Restrictions
2134 // The nonmonotonic modifier cannot be specified if an ordered clause is
2135 // specified.
2136 if (SC &&
2137 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2138 SC->getSecondScheduleModifier() ==
2139 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2140 OC) {
2141 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2142 ? SC->getFirstScheduleModifierLoc()
2143 : SC->getSecondScheduleModifierLoc(),
2144 diag::err_omp_schedule_nonmonotonic_ordered)
2145 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2146 ErrorFound = true;
2147 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002148 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2149 for (auto *C : LCs) {
2150 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2151 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2152 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002153 ErrorFound = true;
2154 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002155 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2156 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2157 OC->getNumForLoops()) {
2158 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2159 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2160 ErrorFound = true;
2161 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002162 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002163 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002164 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002165 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002166 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2167 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2168 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2169 // Mark all variables in private list clauses as used in inner region.
2170 // Required for proper codegen of combined directives.
2171 // TODO: add processing for other clauses.
2172 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2173 for (auto *C : PICs) {
2174 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2175 // Find the particular capture region for the clause if the
2176 // directive is a combined one with multiple capture regions.
2177 // If the directive is not a combined one, the capture region
2178 // associated with the clause is OMPD_unknown and is generated
2179 // only once.
2180 if (CaptureRegion == ThisCaptureRegion ||
2181 CaptureRegion == OMPD_unknown) {
2182 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2183 for (auto *D : DS->decls())
2184 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2185 }
2186 }
2187 }
2188 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002189 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002190 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002191 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002192}
2193
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002194static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2195 OpenMPDirectiveKind CancelRegion,
2196 SourceLocation StartLoc) {
2197 // CancelRegion is only needed for cancel and cancellation_point.
2198 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2199 return false;
2200
2201 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2202 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2203 return false;
2204
2205 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2206 << getOpenMPDirectiveName(CancelRegion);
2207 return true;
2208}
2209
2210static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002211 OpenMPDirectiveKind CurrentRegion,
2212 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002213 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002214 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002215 if (Stack->getCurScope()) {
2216 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002217 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002218 bool NestingProhibited = false;
2219 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002220 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002221 enum {
2222 NoRecommend,
2223 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002224 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002225 ShouldBeInTargetRegion,
2226 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002227 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002228 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002229 // OpenMP [2.16, Nesting of Regions]
2230 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002231 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002232 // An ordered construct with the simd clause is the only OpenMP
2233 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002234 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002235 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2236 // message.
2237 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2238 ? diag::err_omp_prohibited_region_simd
2239 : diag::warn_omp_nesting_simd);
2240 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002241 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002242 if (ParentRegion == OMPD_atomic) {
2243 // OpenMP [2.16, Nesting of Regions]
2244 // OpenMP constructs may not be nested inside an atomic region.
2245 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2246 return true;
2247 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002248 if (CurrentRegion == OMPD_section) {
2249 // OpenMP [2.7.2, sections Construct, Restrictions]
2250 // Orphaned section directives are prohibited. That is, the section
2251 // directives must appear within the sections construct and must not be
2252 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002253 if (ParentRegion != OMPD_sections &&
2254 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002255 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2256 << (ParentRegion != OMPD_unknown)
2257 << getOpenMPDirectiveName(ParentRegion);
2258 return true;
2259 }
2260 return false;
2261 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002262 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002263 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002264 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002265 if (ParentRegion == OMPD_unknown &&
2266 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002267 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002268 if (CurrentRegion == OMPD_cancellation_point ||
2269 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002270 // OpenMP [2.16, Nesting of Regions]
2271 // A cancellation point construct for which construct-type-clause is
2272 // taskgroup must be nested inside a task construct. A cancellation
2273 // point construct for which construct-type-clause is not taskgroup must
2274 // be closely nested inside an OpenMP construct that matches the type
2275 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002276 // A cancel construct for which construct-type-clause is taskgroup must be
2277 // nested inside a task construct. A cancel construct for which
2278 // construct-type-clause is not taskgroup must be closely nested inside an
2279 // OpenMP construct that matches the type specified in
2280 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002281 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002282 !((CancelRegion == OMPD_parallel &&
2283 (ParentRegion == OMPD_parallel ||
2284 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002285 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002286 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2287 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002288 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2289 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002290 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2291 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002292 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002293 // OpenMP [2.16, Nesting of Regions]
2294 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002295 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002296 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002297 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002298 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2299 // OpenMP [2.16, Nesting of Regions]
2300 // A critical region may not be nested (closely or otherwise) inside a
2301 // critical region with the same name. Note that this restriction is not
2302 // sufficient to prevent deadlock.
2303 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002304 bool DeadLock = Stack->hasDirective(
2305 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2306 const DeclarationNameInfo &DNI,
2307 SourceLocation Loc) -> bool {
2308 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2309 PreviousCriticalLoc = Loc;
2310 return true;
2311 } else
2312 return false;
2313 },
2314 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002315 if (DeadLock) {
2316 SemaRef.Diag(StartLoc,
2317 diag::err_omp_prohibited_region_critical_same_name)
2318 << CurrentName.getName();
2319 if (PreviousCriticalLoc.isValid())
2320 SemaRef.Diag(PreviousCriticalLoc,
2321 diag::note_omp_previous_critical_region);
2322 return true;
2323 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002324 } else if (CurrentRegion == OMPD_barrier) {
2325 // OpenMP [2.16, Nesting of Regions]
2326 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002327 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002328 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2329 isOpenMPTaskingDirective(ParentRegion) ||
2330 ParentRegion == OMPD_master ||
2331 ParentRegion == OMPD_critical ||
2332 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002333 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002334 !isOpenMPParallelDirective(CurrentRegion) &&
2335 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002336 // OpenMP [2.16, Nesting of Regions]
2337 // A worksharing region may not be closely nested inside a worksharing,
2338 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002339 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2340 isOpenMPTaskingDirective(ParentRegion) ||
2341 ParentRegion == OMPD_master ||
2342 ParentRegion == OMPD_critical ||
2343 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002344 Recommend = ShouldBeInParallelRegion;
2345 } else if (CurrentRegion == OMPD_ordered) {
2346 // OpenMP [2.16, Nesting of Regions]
2347 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002348 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002349 // An ordered region must be closely nested inside a loop region (or
2350 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002351 // OpenMP [2.8.1,simd Construct, Restrictions]
2352 // An ordered construct with the simd clause is the only OpenMP construct
2353 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002354 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002355 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002356 !(isOpenMPSimdDirective(ParentRegion) ||
2357 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002358 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002359 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002360 // OpenMP [2.16, Nesting of Regions]
2361 // If specified, a teams construct must be contained within a target
2362 // construct.
2363 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002364 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002365 Recommend = ShouldBeInTargetRegion;
2366 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2367 }
Kelvin Libf594a52016-12-17 05:48:59 +00002368 if (!NestingProhibited &&
2369 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2370 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2371 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002372 // OpenMP [2.16, Nesting of Regions]
2373 // distribute, parallel, parallel sections, parallel workshare, and the
2374 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2375 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002376 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2377 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002378 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002379 }
David Majnemer9d168222016-08-05 17:44:54 +00002380 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002381 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002382 // OpenMP 4.5 [2.17 Nesting of Regions]
2383 // The region associated with the distribute construct must be strictly
2384 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002385 NestingProhibited =
2386 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002387 Recommend = ShouldBeInTeamsRegion;
2388 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002389 if (!NestingProhibited &&
2390 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2391 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2392 // OpenMP 4.5 [2.17 Nesting of Regions]
2393 // If a target, target update, target data, target enter data, or
2394 // target exit data construct is encountered during execution of a
2395 // target region, the behavior is unspecified.
2396 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002397 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2398 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002399 if (isOpenMPTargetExecutionDirective(K)) {
2400 OffendingRegion = K;
2401 return true;
2402 } else
2403 return false;
2404 },
2405 false /* don't skip top directive */);
2406 CloseNesting = false;
2407 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002408 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002409 if (OrphanSeen) {
2410 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2411 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2412 } else {
2413 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2414 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2415 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2416 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002417 return true;
2418 }
2419 }
2420 return false;
2421}
2422
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002423static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2424 ArrayRef<OMPClause *> Clauses,
2425 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2426 bool ErrorFound = false;
2427 unsigned NamedModifiersNumber = 0;
2428 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2429 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002430 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002431 for (const auto *C : Clauses) {
2432 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2433 // At most one if clause without a directive-name-modifier can appear on
2434 // the directive.
2435 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2436 if (FoundNameModifiers[CurNM]) {
2437 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2438 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2439 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2440 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002441 } else if (CurNM != OMPD_unknown) {
2442 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002443 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002444 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002445 FoundNameModifiers[CurNM] = IC;
2446 if (CurNM == OMPD_unknown)
2447 continue;
2448 // Check if the specified name modifier is allowed for the current
2449 // directive.
2450 // At most one if clause with the particular directive-name-modifier can
2451 // appear on the directive.
2452 bool MatchFound = false;
2453 for (auto NM : AllowedNameModifiers) {
2454 if (CurNM == NM) {
2455 MatchFound = true;
2456 break;
2457 }
2458 }
2459 if (!MatchFound) {
2460 S.Diag(IC->getNameModifierLoc(),
2461 diag::err_omp_wrong_if_directive_name_modifier)
2462 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2463 ErrorFound = true;
2464 }
2465 }
2466 }
2467 // If any if clause on the directive includes a directive-name-modifier then
2468 // all if clauses on the directive must include a directive-name-modifier.
2469 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2470 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2471 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2472 diag::err_omp_no_more_if_clause);
2473 } else {
2474 std::string Values;
2475 std::string Sep(", ");
2476 unsigned AllowedCnt = 0;
2477 unsigned TotalAllowedNum =
2478 AllowedNameModifiers.size() - NamedModifiersNumber;
2479 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2480 ++Cnt) {
2481 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2482 if (!FoundNameModifiers[NM]) {
2483 Values += "'";
2484 Values += getOpenMPDirectiveName(NM);
2485 Values += "'";
2486 if (AllowedCnt + 2 == TotalAllowedNum)
2487 Values += " or ";
2488 else if (AllowedCnt + 1 != TotalAllowedNum)
2489 Values += Sep;
2490 ++AllowedCnt;
2491 }
2492 }
2493 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2494 diag::err_omp_unnamed_if_clause)
2495 << (TotalAllowedNum > 1) << Values;
2496 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002497 for (auto Loc : NameModifierLoc) {
2498 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2499 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002500 ErrorFound = true;
2501 }
2502 return ErrorFound;
2503}
2504
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002505StmtResult Sema::ActOnOpenMPExecutableDirective(
2506 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2507 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2508 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002509 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002510 // First check CancelRegion which is then used in checkNestingOfRegions.
2511 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2512 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002513 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002514 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002515
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002516 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002517 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002518 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002519 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002520 if (AStmt) {
2521 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2522
2523 // Check default data sharing attributes for referenced variables.
2524 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002525 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2526 Stmt *S = AStmt;
2527 while (--ThisCaptureLevel >= 0)
2528 S = cast<CapturedStmt>(S)->getCapturedStmt();
2529 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002530 if (DSAChecker.isErrorFound())
2531 return StmtError();
2532 // Generate list of implicitly defined firstprivate variables.
2533 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002534
2535 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2536 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2537 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2538 SourceLocation(), SourceLocation())) {
2539 ClausesWithImplicit.push_back(Implicit);
2540 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2541 DSAChecker.getImplicitFirstprivate().size();
2542 } else
2543 ErrorFound = true;
2544 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002545 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002546
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002547 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002548 switch (Kind) {
2549 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002550 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2551 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002552 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002553 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002554 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002555 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2556 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002557 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002558 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002559 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2560 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002561 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002562 case OMPD_for_simd:
2563 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2564 EndLoc, VarsWithInheritedDSA);
2565 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002566 case OMPD_sections:
2567 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2568 EndLoc);
2569 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002570 case OMPD_section:
2571 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002572 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002573 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2574 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002575 case OMPD_single:
2576 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2577 EndLoc);
2578 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002579 case OMPD_master:
2580 assert(ClausesWithImplicit.empty() &&
2581 "No clauses are allowed for 'omp master' directive");
2582 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2583 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002584 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002585 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2586 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002587 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002588 case OMPD_parallel_for:
2589 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2590 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002591 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002592 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002593 case OMPD_parallel_for_simd:
2594 Res = ActOnOpenMPParallelForSimdDirective(
2595 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002596 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002597 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002598 case OMPD_parallel_sections:
2599 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2600 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002601 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002602 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002603 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002604 Res =
2605 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002606 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002607 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002608 case OMPD_taskyield:
2609 assert(ClausesWithImplicit.empty() &&
2610 "No clauses are allowed for 'omp taskyield' directive");
2611 assert(AStmt == nullptr &&
2612 "No associated statement allowed for 'omp taskyield' directive");
2613 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2614 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002615 case OMPD_barrier:
2616 assert(ClausesWithImplicit.empty() &&
2617 "No clauses are allowed for 'omp barrier' directive");
2618 assert(AStmt == nullptr &&
2619 "No associated statement allowed for 'omp barrier' directive");
2620 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2621 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002622 case OMPD_taskwait:
2623 assert(ClausesWithImplicit.empty() &&
2624 "No clauses are allowed for 'omp taskwait' directive");
2625 assert(AStmt == nullptr &&
2626 "No associated statement allowed for 'omp taskwait' directive");
2627 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2628 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002629 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002630 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2631 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002632 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002633 case OMPD_flush:
2634 assert(AStmt == nullptr &&
2635 "No associated statement allowed for 'omp flush' directive");
2636 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2637 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002638 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002639 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2640 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002641 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002642 case OMPD_atomic:
2643 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2644 EndLoc);
2645 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002646 case OMPD_teams:
2647 Res =
2648 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2649 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002650 case OMPD_target:
2651 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2652 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002653 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002654 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002655 case OMPD_target_parallel:
2656 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2657 StartLoc, EndLoc);
2658 AllowedNameModifiers.push_back(OMPD_target);
2659 AllowedNameModifiers.push_back(OMPD_parallel);
2660 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002661 case OMPD_target_parallel_for:
2662 Res = ActOnOpenMPTargetParallelForDirective(
2663 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2664 AllowedNameModifiers.push_back(OMPD_target);
2665 AllowedNameModifiers.push_back(OMPD_parallel);
2666 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002667 case OMPD_cancellation_point:
2668 assert(ClausesWithImplicit.empty() &&
2669 "No clauses are allowed for 'omp cancellation point' directive");
2670 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2671 "cancellation point' directive");
2672 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2673 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002674 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002675 assert(AStmt == nullptr &&
2676 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002677 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2678 CancelRegion);
2679 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002680 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002681 case OMPD_target_data:
2682 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2683 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002684 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002685 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002686 case OMPD_target_enter_data:
2687 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2688 EndLoc);
2689 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2690 break;
Samuel Antao72590762016-01-19 20:04:50 +00002691 case OMPD_target_exit_data:
2692 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2693 EndLoc);
2694 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2695 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002696 case OMPD_taskloop:
2697 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2698 EndLoc, VarsWithInheritedDSA);
2699 AllowedNameModifiers.push_back(OMPD_taskloop);
2700 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002701 case OMPD_taskloop_simd:
2702 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2703 EndLoc, VarsWithInheritedDSA);
2704 AllowedNameModifiers.push_back(OMPD_taskloop);
2705 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002706 case OMPD_distribute:
2707 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2708 EndLoc, VarsWithInheritedDSA);
2709 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002710 case OMPD_target_update:
2711 assert(!AStmt && "Statement is not allowed for target update");
2712 Res =
2713 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2714 AllowedNameModifiers.push_back(OMPD_target_update);
2715 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002716 case OMPD_distribute_parallel_for:
2717 Res = ActOnOpenMPDistributeParallelForDirective(
2718 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2719 AllowedNameModifiers.push_back(OMPD_parallel);
2720 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002721 case OMPD_distribute_parallel_for_simd:
2722 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2723 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2724 AllowedNameModifiers.push_back(OMPD_parallel);
2725 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002726 case OMPD_distribute_simd:
2727 Res = ActOnOpenMPDistributeSimdDirective(
2728 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2729 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002730 case OMPD_target_parallel_for_simd:
2731 Res = ActOnOpenMPTargetParallelForSimdDirective(
2732 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2733 AllowedNameModifiers.push_back(OMPD_target);
2734 AllowedNameModifiers.push_back(OMPD_parallel);
2735 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002736 case OMPD_target_simd:
2737 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2738 EndLoc, VarsWithInheritedDSA);
2739 AllowedNameModifiers.push_back(OMPD_target);
2740 break;
Kelvin Li02532872016-08-05 14:37:37 +00002741 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002742 Res = ActOnOpenMPTeamsDistributeDirective(
2743 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002744 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002745 case OMPD_teams_distribute_simd:
2746 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2747 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2748 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002749 case OMPD_teams_distribute_parallel_for_simd:
2750 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2751 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2752 AllowedNameModifiers.push_back(OMPD_parallel);
2753 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002754 case OMPD_teams_distribute_parallel_for:
2755 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2756 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2757 AllowedNameModifiers.push_back(OMPD_parallel);
2758 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002759 case OMPD_target_teams:
2760 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2761 EndLoc);
2762 AllowedNameModifiers.push_back(OMPD_target);
2763 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002764 case OMPD_target_teams_distribute:
2765 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2766 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2767 AllowedNameModifiers.push_back(OMPD_target);
2768 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002769 case OMPD_target_teams_distribute_parallel_for:
2770 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2771 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2772 AllowedNameModifiers.push_back(OMPD_target);
2773 AllowedNameModifiers.push_back(OMPD_parallel);
2774 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002775 case OMPD_target_teams_distribute_parallel_for_simd:
2776 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2777 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2778 AllowedNameModifiers.push_back(OMPD_target);
2779 AllowedNameModifiers.push_back(OMPD_parallel);
2780 break;
Kelvin Lida681182017-01-10 18:08:18 +00002781 case OMPD_target_teams_distribute_simd:
2782 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2783 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2784 AllowedNameModifiers.push_back(OMPD_target);
2785 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002786 case OMPD_declare_target:
2787 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002788 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002789 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002790 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002791 llvm_unreachable("OpenMP Directive is not allowed");
2792 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002793 llvm_unreachable("Unknown OpenMP directive");
2794 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002795
Alexey Bataev4acb8592014-07-07 13:01:15 +00002796 for (auto P : VarsWithInheritedDSA) {
2797 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2798 << P.first << P.second->getSourceRange();
2799 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002800 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2801
2802 if (!AllowedNameModifiers.empty())
2803 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2804 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002805
Alexey Bataeved09d242014-05-28 05:53:51 +00002806 if (ErrorFound)
2807 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002808 return Res;
2809}
2810
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002811Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2812 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002813 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002814 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2815 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002816 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002817 assert(Linears.size() == LinModifiers.size());
2818 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002819 if (!DG || DG.get().isNull())
2820 return DeclGroupPtrTy();
2821
2822 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002823 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002824 return DG;
2825 }
2826 auto *ADecl = DG.get().getSingleDecl();
2827 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2828 ADecl = FTD->getTemplatedDecl();
2829
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002830 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2831 if (!FD) {
2832 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002833 return DeclGroupPtrTy();
2834 }
2835
Alexey Bataev2af33e32016-04-07 12:45:37 +00002836 // OpenMP [2.8.2, declare simd construct, Description]
2837 // The parameter of the simdlen clause must be a constant positive integer
2838 // expression.
2839 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002840 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002841 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002842 // OpenMP [2.8.2, declare simd construct, Description]
2843 // The special this pointer can be used as if was one of the arguments to the
2844 // function in any of the linear, aligned, or uniform clauses.
2845 // The uniform clause declares one or more arguments to have an invariant
2846 // value for all concurrent invocations of the function in the execution of a
2847 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002848 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2849 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002850 for (auto *E : Uniforms) {
2851 E = E->IgnoreParenImpCasts();
2852 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2853 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2854 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2855 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002856 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2857 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002858 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002859 }
2860 if (isa<CXXThisExpr>(E)) {
2861 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002862 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002863 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002864 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2865 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002866 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002867 // OpenMP [2.8.2, declare simd construct, Description]
2868 // The aligned clause declares that the object to which each list item points
2869 // is aligned to the number of bytes expressed in the optional parameter of
2870 // the aligned clause.
2871 // The special this pointer can be used as if was one of the arguments to the
2872 // function in any of the linear, aligned, or uniform clauses.
2873 // The type of list items appearing in the aligned clause must be array,
2874 // pointer, reference to array, or reference to pointer.
2875 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2876 Expr *AlignedThis = nullptr;
2877 for (auto *E : Aligneds) {
2878 E = E->IgnoreParenImpCasts();
2879 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2880 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2881 auto *CanonPVD = PVD->getCanonicalDecl();
2882 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2883 FD->getParamDecl(PVD->getFunctionScopeIndex())
2884 ->getCanonicalDecl() == CanonPVD) {
2885 // OpenMP [2.8.1, simd construct, Restrictions]
2886 // A list-item cannot appear in more than one aligned clause.
2887 if (AlignedArgs.count(CanonPVD) > 0) {
2888 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2889 << 1 << E->getSourceRange();
2890 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2891 diag::note_omp_explicit_dsa)
2892 << getOpenMPClauseName(OMPC_aligned);
2893 continue;
2894 }
2895 AlignedArgs[CanonPVD] = E;
2896 QualType QTy = PVD->getType()
2897 .getNonReferenceType()
2898 .getUnqualifiedType()
2899 .getCanonicalType();
2900 const Type *Ty = QTy.getTypePtrOrNull();
2901 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2902 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2903 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2904 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2905 }
2906 continue;
2907 }
2908 }
2909 if (isa<CXXThisExpr>(E)) {
2910 if (AlignedThis) {
2911 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2912 << 2 << E->getSourceRange();
2913 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2914 << getOpenMPClauseName(OMPC_aligned);
2915 }
2916 AlignedThis = E;
2917 continue;
2918 }
2919 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2920 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2921 }
2922 // The optional parameter of the aligned clause, alignment, must be a constant
2923 // positive integer expression. If no optional parameter is specified,
2924 // implementation-defined default alignments for SIMD instructions on the
2925 // target platforms are assumed.
2926 SmallVector<Expr *, 4> NewAligns;
2927 for (auto *E : Alignments) {
2928 ExprResult Align;
2929 if (E)
2930 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2931 NewAligns.push_back(Align.get());
2932 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002933 // OpenMP [2.8.2, declare simd construct, Description]
2934 // The linear clause declares one or more list items to be private to a SIMD
2935 // lane and to have a linear relationship with respect to the iteration space
2936 // of a loop.
2937 // The special this pointer can be used as if was one of the arguments to the
2938 // function in any of the linear, aligned, or uniform clauses.
2939 // When a linear-step expression is specified in a linear clause it must be
2940 // either a constant integer expression or an integer-typed parameter that is
2941 // specified in a uniform clause on the directive.
2942 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2943 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2944 auto MI = LinModifiers.begin();
2945 for (auto *E : Linears) {
2946 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2947 ++MI;
2948 E = E->IgnoreParenImpCasts();
2949 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2950 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2951 auto *CanonPVD = PVD->getCanonicalDecl();
2952 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2953 FD->getParamDecl(PVD->getFunctionScopeIndex())
2954 ->getCanonicalDecl() == CanonPVD) {
2955 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2956 // A list-item cannot appear in more than one linear clause.
2957 if (LinearArgs.count(CanonPVD) > 0) {
2958 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2959 << getOpenMPClauseName(OMPC_linear)
2960 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2961 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2962 diag::note_omp_explicit_dsa)
2963 << getOpenMPClauseName(OMPC_linear);
2964 continue;
2965 }
2966 // Each argument can appear in at most one uniform or linear clause.
2967 if (UniformedArgs.count(CanonPVD) > 0) {
2968 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2969 << getOpenMPClauseName(OMPC_linear)
2970 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2971 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2972 diag::note_omp_explicit_dsa)
2973 << getOpenMPClauseName(OMPC_uniform);
2974 continue;
2975 }
2976 LinearArgs[CanonPVD] = E;
2977 if (E->isValueDependent() || E->isTypeDependent() ||
2978 E->isInstantiationDependent() ||
2979 E->containsUnexpandedParameterPack())
2980 continue;
2981 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2982 PVD->getOriginalType());
2983 continue;
2984 }
2985 }
2986 if (isa<CXXThisExpr>(E)) {
2987 if (UniformedLinearThis) {
2988 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2989 << getOpenMPClauseName(OMPC_linear)
2990 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2991 << E->getSourceRange();
2992 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2993 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2994 : OMPC_linear);
2995 continue;
2996 }
2997 UniformedLinearThis = E;
2998 if (E->isValueDependent() || E->isTypeDependent() ||
2999 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3000 continue;
3001 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3002 E->getType());
3003 continue;
3004 }
3005 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3006 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3007 }
3008 Expr *Step = nullptr;
3009 Expr *NewStep = nullptr;
3010 SmallVector<Expr *, 4> NewSteps;
3011 for (auto *E : Steps) {
3012 // Skip the same step expression, it was checked already.
3013 if (Step == E || !E) {
3014 NewSteps.push_back(E ? NewStep : nullptr);
3015 continue;
3016 }
3017 Step = E;
3018 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3019 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3020 auto *CanonPVD = PVD->getCanonicalDecl();
3021 if (UniformedArgs.count(CanonPVD) == 0) {
3022 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3023 << Step->getSourceRange();
3024 } else if (E->isValueDependent() || E->isTypeDependent() ||
3025 E->isInstantiationDependent() ||
3026 E->containsUnexpandedParameterPack() ||
3027 CanonPVD->getType()->hasIntegerRepresentation())
3028 NewSteps.push_back(Step);
3029 else {
3030 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3031 << Step->getSourceRange();
3032 }
3033 continue;
3034 }
3035 NewStep = Step;
3036 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3037 !Step->isInstantiationDependent() &&
3038 !Step->containsUnexpandedParameterPack()) {
3039 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3040 .get();
3041 if (NewStep)
3042 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3043 }
3044 NewSteps.push_back(NewStep);
3045 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003046 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3047 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003048 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003049 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3050 const_cast<Expr **>(Linears.data()), Linears.size(),
3051 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3052 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003053 ADecl->addAttr(NewAttr);
3054 return ConvertDeclToDeclGroup(ADecl);
3055}
3056
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003057StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3058 Stmt *AStmt,
3059 SourceLocation StartLoc,
3060 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003061 if (!AStmt)
3062 return StmtError();
3063
Alexey Bataev9959db52014-05-06 10:08:46 +00003064 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3065 // 1.2.2 OpenMP Language Terminology
3066 // Structured block - An executable statement with a single entry at the
3067 // top and a single exit at the bottom.
3068 // The point of exit cannot be a branch out of the structured block.
3069 // longjmp() and throw() must not violate the entry/exit criteria.
3070 CS->getCapturedDecl()->setNothrow();
3071
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003072 getCurFunction()->setHasBranchProtectedScope();
3073
Alexey Bataev25e5b442015-09-15 12:52:43 +00003074 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3075 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003076}
3077
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003078namespace {
3079/// \brief Helper class for checking canonical form of the OpenMP loops and
3080/// extracting iteration space of each loop in the loop nest, that will be used
3081/// for IR generation.
3082class OpenMPIterationSpaceChecker {
3083 /// \brief Reference to Sema.
3084 Sema &SemaRef;
3085 /// \brief A location for diagnostics (when there is no some better location).
3086 SourceLocation DefaultLoc;
3087 /// \brief A location for diagnostics (when increment is not compatible).
3088 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003089 /// \brief A source location for referring to loop init later.
3090 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 /// \brief A source location for referring to condition later.
3092 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003093 /// \brief A source location for referring to increment later.
3094 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003095 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003096 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003097 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003098 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003099 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003100 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003101 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003102 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003103 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003104 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003105 /// \brief This flag is true when condition is one of:
3106 /// Var < UB
3107 /// Var <= UB
3108 /// UB > Var
3109 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003110 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003112 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003113 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003114 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115
3116public:
3117 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003118 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003119 /// \brief Check init-expr for canonical loop form and save loop counter
3120 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003121 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003122 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3123 /// for less/greater and for strict/non-strict comparison.
3124 bool CheckCond(Expr *S);
3125 /// \brief Check incr-expr for canonical loop form and return true if it
3126 /// does not conform, otherwise save loop step (#Step).
3127 bool CheckInc(Expr *S);
3128 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003129 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003130 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003131 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003132 /// \brief Source range of the loop init.
3133 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3134 /// \brief Source range of the loop condition.
3135 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3136 /// \brief Source range of the loop increment.
3137 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3138 /// \brief True if the step should be subtracted.
3139 bool ShouldSubtractStep() const { return SubtractStep; }
3140 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003141 Expr *
3142 BuildNumIterations(Scope *S, const bool LimitedType,
3143 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003144 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003145 Expr *BuildPreCond(Scope *S, Expr *Cond,
3146 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003147 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003148 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3149 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003150 /// \brief Build reference expression to the private counter be used for
3151 /// codegen.
3152 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003153 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003154 Expr *BuildCounterInit() const;
3155 /// \brief Build step of the counter be used for codegen.
3156 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003157 /// \brief Return true if any expression is dependent.
3158 bool Dependent() const;
3159
3160private:
3161 /// \brief Check the right-hand side of an assignment in the increment
3162 /// expression.
3163 bool CheckIncRHS(Expr *RHS);
3164 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003165 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003166 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003167 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003168 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003169 /// \brief Helper to set loop increment.
3170 bool SetStep(Expr *NewStep, bool Subtract);
3171};
3172
3173bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003175 assert(!LB && !UB && !Step);
3176 return false;
3177 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003178 return LCDecl->getType()->isDependentType() ||
3179 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3180 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003181}
3182
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003183bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3184 Expr *NewLCRefExpr,
3185 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003187 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003188 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003189 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003190 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003191 LCDecl = getCanonicalDecl(NewLCDecl);
3192 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003193 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3194 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003195 if ((Ctor->isCopyOrMoveConstructor() ||
3196 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3197 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003198 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003199 LB = NewLB;
3200 return false;
3201}
3202
3203bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003204 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003205 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003206 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3207 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003208 if (!NewUB)
3209 return true;
3210 UB = NewUB;
3211 TestIsLessOp = LessOp;
3212 TestIsStrictOp = StrictOp;
3213 ConditionSrcRange = SR;
3214 ConditionLoc = SL;
3215 return false;
3216}
3217
3218bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3219 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003220 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003221 if (!NewStep)
3222 return true;
3223 if (!NewStep->isValueDependent()) {
3224 // Check that the step is integer expression.
3225 SourceLocation StepLoc = NewStep->getLocStart();
3226 ExprResult Val =
3227 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3228 if (Val.isInvalid())
3229 return true;
3230 NewStep = Val.get();
3231
3232 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3233 // If test-expr is of form var relational-op b and relational-op is < or
3234 // <= then incr-expr must cause var to increase on each iteration of the
3235 // loop. If test-expr is of form var relational-op b and relational-op is
3236 // > or >= then incr-expr must cause var to decrease on each iteration of
3237 // the loop.
3238 // If test-expr is of form b relational-op var and relational-op is < or
3239 // <= then incr-expr must cause var to decrease on each iteration of the
3240 // loop. If test-expr is of form b relational-op var and relational-op is
3241 // > or >= then incr-expr must cause var to increase on each iteration of
3242 // the loop.
3243 llvm::APSInt Result;
3244 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3245 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3246 bool IsConstNeg =
3247 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003248 bool IsConstPos =
3249 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003250 bool IsConstZero = IsConstant && !Result.getBoolValue();
3251 if (UB && (IsConstZero ||
3252 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003253 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003254 SemaRef.Diag(NewStep->getExprLoc(),
3255 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003256 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003257 SemaRef.Diag(ConditionLoc,
3258 diag::note_omp_loop_cond_requres_compatible_incr)
3259 << TestIsLessOp << ConditionSrcRange;
3260 return true;
3261 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003262 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003263 NewStep =
3264 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3265 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003266 Subtract = !Subtract;
3267 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003268 }
3269
3270 Step = NewStep;
3271 SubtractStep = Subtract;
3272 return false;
3273}
3274
Alexey Bataev9c821032015-04-30 04:23:23 +00003275bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003276 // Check init-expr for canonical loop form and save loop counter
3277 // variable - #Var and its initialization value - #LB.
3278 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3279 // var = lb
3280 // integer-type var = lb
3281 // random-access-iterator-type var = lb
3282 // pointer-type var = lb
3283 //
3284 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003285 if (EmitDiags) {
3286 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3287 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003288 return true;
3289 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003290 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3291 if (!ExprTemp->cleanupsHaveSideEffects())
3292 S = ExprTemp->getSubExpr();
3293
Alexander Musmana5f070a2014-10-01 06:03:56 +00003294 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003295 if (Expr *E = dyn_cast<Expr>(S))
3296 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003297 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003298 if (BO->getOpcode() == BO_Assign) {
3299 auto *LHS = BO->getLHS()->IgnoreParens();
3300 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3301 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3302 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3303 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3304 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3305 }
3306 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3307 if (ME->isArrow() &&
3308 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3309 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3310 }
3311 }
David Majnemer9d168222016-08-05 17:44:54 +00003312 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003313 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003314 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003315 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003316 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003317 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003318 SemaRef.Diag(S->getLocStart(),
3319 diag::ext_omp_loop_not_canonical_init)
3320 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003321 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003322 }
3323 }
3324 }
David Majnemer9d168222016-08-05 17:44:54 +00003325 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003326 if (CE->getOperator() == OO_Equal) {
3327 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003328 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003329 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3330 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3331 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3332 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3333 }
3334 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3335 if (ME->isArrow() &&
3336 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3337 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3338 }
3339 }
3340 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003341
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003342 if (Dependent() || SemaRef.CurContext->isDependentContext())
3343 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003344 if (EmitDiags) {
3345 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3346 << S->getSourceRange();
3347 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003348 return true;
3349}
3350
Alexey Bataev23b69422014-06-18 07:08:49 +00003351/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003352/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003353static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003354 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003355 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003356 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003357 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3358 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003359 if ((Ctor->isCopyOrMoveConstructor() ||
3360 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3361 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003362 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003363 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003364 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003365 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003366 }
3367 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3368 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3369 return getCanonicalDecl(ME->getMemberDecl());
3370 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003371}
3372
3373bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3374 // Check test-expr for canonical form, save upper-bound UB, flags for
3375 // less/greater and for strict/non-strict comparison.
3376 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3377 // var relational-op b
3378 // b relational-op var
3379 //
3380 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003381 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003382 return true;
3383 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003384 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003385 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003386 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003387 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003388 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003389 return SetUB(BO->getRHS(),
3390 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3391 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3392 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003393 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003394 return SetUB(BO->getLHS(),
3395 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3396 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3397 BO->getSourceRange(), BO->getOperatorLoc());
3398 }
David Majnemer9d168222016-08-05 17:44:54 +00003399 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003400 if (CE->getNumArgs() == 2) {
3401 auto Op = CE->getOperator();
3402 switch (Op) {
3403 case OO_Greater:
3404 case OO_GreaterEqual:
3405 case OO_Less:
3406 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003407 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003408 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3409 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3410 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003411 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003412 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3413 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3414 CE->getOperatorLoc());
3415 break;
3416 default:
3417 break;
3418 }
3419 }
3420 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003421 if (Dependent() || SemaRef.CurContext->isDependentContext())
3422 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003423 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003424 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003425 return true;
3426}
3427
3428bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3429 // RHS of canonical loop form increment can be:
3430 // var + incr
3431 // incr + var
3432 // var - incr
3433 //
3434 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003435 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003436 if (BO->isAdditiveOp()) {
3437 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003438 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003439 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003440 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003441 return SetStep(BO->getLHS(), false);
3442 }
David Majnemer9d168222016-08-05 17:44:54 +00003443 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003444 bool IsAdd = CE->getOperator() == OO_Plus;
3445 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003446 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003447 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003449 return SetStep(CE->getArg(0), false);
3450 }
3451 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003452 if (Dependent() || SemaRef.CurContext->isDependentContext())
3453 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003454 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003455 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003456 return true;
3457}
3458
3459bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3460 // Check incr-expr for canonical loop form and return true if it
3461 // does not conform.
3462 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3463 // ++var
3464 // var++
3465 // --var
3466 // var--
3467 // var += incr
3468 // var -= incr
3469 // var = var + incr
3470 // var = incr + var
3471 // var = var - incr
3472 //
3473 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003474 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003475 return true;
3476 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003477 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3478 if (!ExprTemp->cleanupsHaveSideEffects())
3479 S = ExprTemp->getSubExpr();
3480
Alexander Musmana5f070a2014-10-01 06:03:56 +00003481 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003482 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003483 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003484 if (UO->isIncrementDecrementOp() &&
3485 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003486 return SetStep(SemaRef
3487 .ActOnIntegerConstant(UO->getLocStart(),
3488 (UO->isDecrementOp() ? -1 : 1))
3489 .get(),
3490 false);
3491 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003492 switch (BO->getOpcode()) {
3493 case BO_AddAssign:
3494 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003495 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003496 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3497 break;
3498 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003499 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003500 return CheckIncRHS(BO->getRHS());
3501 break;
3502 default:
3503 break;
3504 }
David Majnemer9d168222016-08-05 17:44:54 +00003505 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003506 switch (CE->getOperator()) {
3507 case OO_PlusPlus:
3508 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003509 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003510 return SetStep(SemaRef
3511 .ActOnIntegerConstant(
3512 CE->getLocStart(),
3513 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3514 .get(),
3515 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003516 break;
3517 case OO_PlusEqual:
3518 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003519 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003520 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3521 break;
3522 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003523 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003524 return CheckIncRHS(CE->getArg(1));
3525 break;
3526 default:
3527 break;
3528 }
3529 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003530 if (Dependent() || SemaRef.CurContext->isDependentContext())
3531 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003532 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003533 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003534 return true;
3535}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003536
Alexey Bataev5a3af132016-03-29 08:58:54 +00003537static ExprResult
3538tryBuildCapture(Sema &SemaRef, Expr *Capture,
3539 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003540 if (SemaRef.CurContext->isDependentContext())
3541 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003542 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3543 return SemaRef.PerformImplicitConversion(
3544 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3545 /*AllowExplicit=*/true);
3546 auto I = Captures.find(Capture);
3547 if (I != Captures.end())
3548 return buildCapture(SemaRef, Capture, I->second);
3549 DeclRefExpr *Ref = nullptr;
3550 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3551 Captures[Capture] = Ref;
3552 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003553}
3554
Alexander Musmana5f070a2014-10-01 06:03:56 +00003555/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003556Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3557 Scope *S, const bool LimitedType,
3558 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003559 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003560 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003561 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003562 SemaRef.getLangOpts().CPlusPlus) {
3563 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003564 auto *UBExpr = TestIsLessOp ? UB : LB;
3565 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003566 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3567 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003568 if (!Upper || !Lower)
3569 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003570
3571 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3572
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003573 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003574 // BuildBinOp already emitted error, this one is to point user to upper
3575 // and lower bound, and to tell what is passed to 'operator-'.
3576 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3577 << Upper->getSourceRange() << Lower->getSourceRange();
3578 return nullptr;
3579 }
3580 }
3581
3582 if (!Diff.isUsable())
3583 return nullptr;
3584
3585 // Upper - Lower [- 1]
3586 if (TestIsStrictOp)
3587 Diff = SemaRef.BuildBinOp(
3588 S, DefaultLoc, BO_Sub, Diff.get(),
3589 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3590 if (!Diff.isUsable())
3591 return nullptr;
3592
3593 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003594 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3595 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003596 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003597 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003598 if (!Diff.isUsable())
3599 return nullptr;
3600
3601 // Parentheses (for dumping/debugging purposes only).
3602 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3603 if (!Diff.isUsable())
3604 return nullptr;
3605
3606 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003607 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003608 if (!Diff.isUsable())
3609 return nullptr;
3610
Alexander Musman174b3ca2014-10-06 11:16:29 +00003611 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003612 QualType Type = Diff.get()->getType();
3613 auto &C = SemaRef.Context;
3614 bool UseVarType = VarType->hasIntegerRepresentation() &&
3615 C.getTypeSize(Type) > C.getTypeSize(VarType);
3616 if (!Type->isIntegerType() || UseVarType) {
3617 unsigned NewSize =
3618 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3619 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3620 : Type->hasSignedIntegerRepresentation();
3621 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003622 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3623 Diff = SemaRef.PerformImplicitConversion(
3624 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3625 if (!Diff.isUsable())
3626 return nullptr;
3627 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003628 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003629 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003630 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3631 if (NewSize != C.getTypeSize(Type)) {
3632 if (NewSize < C.getTypeSize(Type)) {
3633 assert(NewSize == 64 && "incorrect loop var size");
3634 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3635 << InitSrcRange << ConditionSrcRange;
3636 }
3637 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003638 NewSize, Type->hasSignedIntegerRepresentation() ||
3639 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003640 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3641 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3642 Sema::AA_Converting, true);
3643 if (!Diff.isUsable())
3644 return nullptr;
3645 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003646 }
3647 }
3648
Alexander Musmana5f070a2014-10-01 06:03:56 +00003649 return Diff.get();
3650}
3651
Alexey Bataev5a3af132016-03-29 08:58:54 +00003652Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3653 Scope *S, Expr *Cond,
3654 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003655 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3656 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3657 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003658
Alexey Bataev5a3af132016-03-29 08:58:54 +00003659 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3660 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3661 if (!NewLB.isUsable() || !NewUB.isUsable())
3662 return nullptr;
3663
Alexey Bataev62dbb972015-04-22 11:59:37 +00003664 auto CondExpr = SemaRef.BuildBinOp(
3665 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3666 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003667 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003668 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003669 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3670 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003671 CondExpr = SemaRef.PerformImplicitConversion(
3672 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3673 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003674 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003675 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3676 // Otherwise use original loop conditon and evaluate it in runtime.
3677 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3678}
3679
Alexander Musmana5f070a2014-10-01 06:03:56 +00003680/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003681DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003682 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003683 auto *VD = dyn_cast<VarDecl>(LCDecl);
3684 if (!VD) {
3685 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3686 auto *Ref = buildDeclRefExpr(
3687 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003688 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3689 // If the loop control decl is explicitly marked as private, do not mark it
3690 // as captured again.
3691 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3692 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003693 return Ref;
3694 }
3695 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003696 DefaultLoc);
3697}
3698
3699Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003700 if (LCDecl && !LCDecl->isInvalidDecl()) {
3701 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003702 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003703 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3704 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003705 if (PrivateVar->isInvalidDecl())
3706 return nullptr;
3707 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3708 }
3709 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003710}
3711
Samuel Antao4c8035b2016-12-12 18:00:20 +00003712/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003713Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3714
3715/// \brief Build step of the counter be used for codegen.
3716Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3717
3718/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003719struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003720 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003721 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003722 /// \brief This expression calculates the number of iterations in the loop.
3723 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003724 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003725 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003726 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003727 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003728 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003729 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003730 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003731 /// \brief This is step for the #CounterVar used to generate its update:
3732 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003733 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003734 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003735 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003736 /// \brief Source range of the loop init.
3737 SourceRange InitSrcRange;
3738 /// \brief Source range of the loop condition.
3739 SourceRange CondSrcRange;
3740 /// \brief Source range of the loop increment.
3741 SourceRange IncSrcRange;
3742};
3743
Alexey Bataev23b69422014-06-18 07:08:49 +00003744} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003745
Alexey Bataev9c821032015-04-30 04:23:23 +00003746void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3747 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3748 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003749 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3750 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003751 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3752 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003753 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3754 if (auto *D = ISC.GetLoopDecl()) {
3755 auto *VD = dyn_cast<VarDecl>(D);
3756 if (!VD) {
3757 if (auto *Private = IsOpenMPCapturedDecl(D))
3758 VD = Private;
3759 else {
3760 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3761 /*WithInit=*/false);
3762 VD = cast<VarDecl>(Ref->getDecl());
3763 }
3764 }
3765 DSAStack->addLoopControlVariable(D, VD);
3766 }
3767 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003768 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003769 }
3770}
3771
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003772/// \brief Called on a for stmt to check and extract its iteration space
3773/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003774static bool CheckOpenMPIterationSpace(
3775 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3776 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003777 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003778 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003779 LoopIterationSpace &ResultIterSpace,
3780 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003781 // OpenMP [2.6, Canonical Loop Form]
3782 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003783 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003784 if (!For) {
3785 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003786 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3787 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3788 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3789 if (NestedLoopCount > 1) {
3790 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3791 SemaRef.Diag(DSA.getConstructLoc(),
3792 diag::note_omp_collapse_ordered_expr)
3793 << 2 << CollapseLoopCountExpr->getSourceRange()
3794 << OrderedLoopCountExpr->getSourceRange();
3795 else if (CollapseLoopCountExpr)
3796 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3797 diag::note_omp_collapse_ordered_expr)
3798 << 0 << CollapseLoopCountExpr->getSourceRange();
3799 else
3800 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3801 diag::note_omp_collapse_ordered_expr)
3802 << 1 << OrderedLoopCountExpr->getSourceRange();
3803 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003804 return true;
3805 }
3806 assert(For->getBody());
3807
3808 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3809
3810 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003811 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003812 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003813 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003814
3815 bool HasErrors = false;
3816
3817 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003818 if (auto *LCDecl = ISC.GetLoopDecl()) {
3819 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003820
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003821 // OpenMP [2.6, Canonical Loop Form]
3822 // Var is one of the following:
3823 // A variable of signed or unsigned integer type.
3824 // For C++, a variable of a random access iterator type.
3825 // For C, a variable of a pointer type.
3826 auto VarType = LCDecl->getType().getNonReferenceType();
3827 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3828 !VarType->isPointerType() &&
3829 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3830 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3831 << SemaRef.getLangOpts().CPlusPlus;
3832 HasErrors = true;
3833 }
3834
3835 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3836 // a Construct
3837 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3838 // parallel for construct is (are) private.
3839 // The loop iteration variable in the associated for-loop of a simd
3840 // construct with just one associated for-loop is linear with a
3841 // constant-linear-step that is the increment of the associated for-loop.
3842 // Exclude loop var from the list of variables with implicitly defined data
3843 // sharing attributes.
3844 VarsWithImplicitDSA.erase(LCDecl);
3845
3846 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3847 // in a Construct, C/C++].
3848 // The loop iteration variable in the associated for-loop of a simd
3849 // construct with just one associated for-loop may be listed in a linear
3850 // clause with a constant-linear-step that is the increment of the
3851 // associated for-loop.
3852 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3853 // parallel for construct may be listed in a private or lastprivate clause.
3854 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3855 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3856 // declared in the loop and it is predetermined as a private.
3857 auto PredeterminedCKind =
3858 isOpenMPSimdDirective(DKind)
3859 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3860 : OMPC_private;
3861 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3862 DVar.CKind != PredeterminedCKind) ||
3863 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3864 isOpenMPDistributeDirective(DKind)) &&
3865 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3866 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3867 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3868 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3869 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3870 << getOpenMPClauseName(PredeterminedCKind);
3871 if (DVar.RefExpr == nullptr)
3872 DVar.CKind = PredeterminedCKind;
3873 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3874 HasErrors = true;
3875 } else if (LoopDeclRefExpr != nullptr) {
3876 // Make the loop iteration variable private (for worksharing constructs),
3877 // linear (for simd directives with the only one associated loop) or
3878 // lastprivate (for simd directives with several collapsed or ordered
3879 // loops).
3880 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003881 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3882 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003883 /*FromParent=*/false);
3884 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3885 }
3886
3887 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3888
3889 // Check test-expr.
3890 HasErrors |= ISC.CheckCond(For->getCond());
3891
3892 // Check incr-expr.
3893 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003894 }
3895
Alexander Musmana5f070a2014-10-01 06:03:56 +00003896 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003897 return HasErrors;
3898
Alexander Musmana5f070a2014-10-01 06:03:56 +00003899 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003900 ResultIterSpace.PreCond =
3901 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003902 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003903 DSA.getCurScope(),
3904 (isOpenMPWorksharingDirective(DKind) ||
3905 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3906 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003907 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003908 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003909 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3910 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3911 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3912 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3913 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3914 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3915
Alexey Bataev62dbb972015-04-22 11:59:37 +00003916 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3917 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003918 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003919 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003920 ResultIterSpace.CounterInit == nullptr ||
3921 ResultIterSpace.CounterStep == nullptr);
3922
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003923 return HasErrors;
3924}
3925
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003926/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003927static ExprResult
3928BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3929 ExprResult Start,
3930 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003931 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003932 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3933 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003934 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003935 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003936 VarRef.get()->getType())) {
3937 NewStart = SemaRef.PerformImplicitConversion(
3938 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3939 /*AllowExplicit=*/true);
3940 if (!NewStart.isUsable())
3941 return ExprError();
3942 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003943
3944 auto Init =
3945 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3946 return Init;
3947}
3948
Alexander Musmana5f070a2014-10-01 06:03:56 +00003949/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003950static ExprResult
3951BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3952 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3953 ExprResult Step, bool Subtract,
3954 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003955 // Add parentheses (for debugging purposes only).
3956 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3957 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3958 !Step.isUsable())
3959 return ExprError();
3960
Alexey Bataev5a3af132016-03-29 08:58:54 +00003961 ExprResult NewStep = Step;
3962 if (Captures)
3963 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003964 if (NewStep.isInvalid())
3965 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003966 ExprResult Update =
3967 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003968 if (!Update.isUsable())
3969 return ExprError();
3970
Alexey Bataevc0214e02016-02-16 12:13:49 +00003971 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3972 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003973 ExprResult NewStart = Start;
3974 if (Captures)
3975 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003976 if (NewStart.isInvalid())
3977 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003978
Alexey Bataevc0214e02016-02-16 12:13:49 +00003979 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3980 ExprResult SavedUpdate = Update;
3981 ExprResult UpdateVal;
3982 if (VarRef.get()->getType()->isOverloadableType() ||
3983 NewStart.get()->getType()->isOverloadableType() ||
3984 Update.get()->getType()->isOverloadableType()) {
3985 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3986 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3987 Update =
3988 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3989 if (Update.isUsable()) {
3990 UpdateVal =
3991 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3992 VarRef.get(), SavedUpdate.get());
3993 if (UpdateVal.isUsable()) {
3994 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3995 UpdateVal.get());
3996 }
3997 }
3998 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3999 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004000
Alexey Bataevc0214e02016-02-16 12:13:49 +00004001 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4002 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4003 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4004 NewStart.get(), SavedUpdate.get());
4005 if (!Update.isUsable())
4006 return ExprError();
4007
Alexey Bataev11481f52016-02-17 10:29:05 +00004008 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4009 VarRef.get()->getType())) {
4010 Update = SemaRef.PerformImplicitConversion(
4011 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4012 if (!Update.isUsable())
4013 return ExprError();
4014 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004015
4016 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4017 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004018 return Update;
4019}
4020
4021/// \brief Convert integer expression \a E to make it have at least \a Bits
4022/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004023static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004024 if (E == nullptr)
4025 return ExprError();
4026 auto &C = SemaRef.Context;
4027 QualType OldType = E->getType();
4028 unsigned HasBits = C.getTypeSize(OldType);
4029 if (HasBits >= Bits)
4030 return ExprResult(E);
4031 // OK to convert to signed, because new type has more bits than old.
4032 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4033 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4034 true);
4035}
4036
4037/// \brief Check if the given expression \a E is a constant integer that fits
4038/// into \a Bits bits.
4039static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4040 if (E == nullptr)
4041 return false;
4042 llvm::APSInt Result;
4043 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4044 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4045 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004046}
4047
Alexey Bataev5a3af132016-03-29 08:58:54 +00004048/// Build preinits statement for the given declarations.
4049static Stmt *buildPreInits(ASTContext &Context,
4050 SmallVectorImpl<Decl *> &PreInits) {
4051 if (!PreInits.empty()) {
4052 return new (Context) DeclStmt(
4053 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4054 SourceLocation(), SourceLocation());
4055 }
4056 return nullptr;
4057}
4058
4059/// Build preinits statement for the given declarations.
4060static Stmt *buildPreInits(ASTContext &Context,
4061 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4062 if (!Captures.empty()) {
4063 SmallVector<Decl *, 16> PreInits;
4064 for (auto &Pair : Captures)
4065 PreInits.push_back(Pair.second->getDecl());
4066 return buildPreInits(Context, PreInits);
4067 }
4068 return nullptr;
4069}
4070
4071/// Build postupdate expression for the given list of postupdates expressions.
4072static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4073 Expr *PostUpdate = nullptr;
4074 if (!PostUpdates.empty()) {
4075 for (auto *E : PostUpdates) {
4076 Expr *ConvE = S.BuildCStyleCastExpr(
4077 E->getExprLoc(),
4078 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4079 E->getExprLoc(), E)
4080 .get();
4081 PostUpdate = PostUpdate
4082 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4083 PostUpdate, ConvE)
4084 .get()
4085 : ConvE;
4086 }
4087 }
4088 return PostUpdate;
4089}
4090
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004091/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004092/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4093/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004094static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004095CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4096 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4097 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004098 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004099 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004100 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004101 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004102 // Found 'collapse' clause - calculate collapse number.
4103 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004104 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004105 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004106 }
4107 if (OrderedLoopCountExpr) {
4108 // Found 'ordered' clause - calculate collapse number.
4109 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004110 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4111 if (Result.getLimitedValue() < NestedLoopCount) {
4112 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4113 diag::err_omp_wrong_ordered_loop_count)
4114 << OrderedLoopCountExpr->getSourceRange();
4115 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4116 diag::note_collapse_loop_count)
4117 << CollapseLoopCountExpr->getSourceRange();
4118 }
4119 NestedLoopCount = Result.getLimitedValue();
4120 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004121 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004122 // This is helper routine for loop directives (e.g., 'for', 'simd',
4123 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004124 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004125 SmallVector<LoopIterationSpace, 4> IterSpaces;
4126 IterSpaces.resize(NestedLoopCount);
4127 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004128 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004129 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004130 NestedLoopCount, CollapseLoopCountExpr,
4131 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004132 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004133 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004134 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004135 // OpenMP [2.8.1, simd construct, Restrictions]
4136 // All loops associated with the construct must be perfectly nested; that
4137 // is, there must be no intervening code nor any OpenMP directive between
4138 // any two loops.
4139 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004140 }
4141
Alexander Musmana5f070a2014-10-01 06:03:56 +00004142 Built.clear(/* size */ NestedLoopCount);
4143
4144 if (SemaRef.CurContext->isDependentContext())
4145 return NestedLoopCount;
4146
4147 // An example of what is generated for the following code:
4148 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004149 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004150 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004151 // for (k = 0; k < NK; ++k)
4152 // for (j = J0; j < NJ; j+=2) {
4153 // <loop body>
4154 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004155 //
4156 // We generate the code below.
4157 // Note: the loop body may be outlined in CodeGen.
4158 // Note: some counters may be C++ classes, operator- is used to find number of
4159 // iterations and operator+= to calculate counter value.
4160 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4161 // or i64 is currently supported).
4162 //
4163 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4164 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4165 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4166 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4167 // // similar updates for vars in clauses (e.g. 'linear')
4168 // <loop body (using local i and j)>
4169 // }
4170 // i = NI; // assign final values of counters
4171 // j = NJ;
4172 //
4173
4174 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4175 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004176 // Precondition tests if there is at least one iteration (all conditions are
4177 // true).
4178 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004179 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004180 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004181 32 /* Bits */, SemaRef
4182 .PerformImplicitConversion(
4183 N0->IgnoreImpCasts(), N0->getType(),
4184 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004185 .get(),
4186 SemaRef);
4187 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004188 64 /* Bits */, SemaRef
4189 .PerformImplicitConversion(
4190 N0->IgnoreImpCasts(), N0->getType(),
4191 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004192 .get(),
4193 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004194
4195 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4196 return NestedLoopCount;
4197
4198 auto &C = SemaRef.Context;
4199 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4200
4201 Scope *CurScope = DSA.getCurScope();
4202 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004203 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004204 PreCond =
4205 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4206 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004207 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004208 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004209 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004210 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4211 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004212 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004213 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004214 SemaRef
4215 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4216 Sema::AA_Converting,
4217 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004218 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004219 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004220 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004221 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004222 SemaRef
4223 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4224 Sema::AA_Converting,
4225 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004226 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004227 }
4228
4229 // Choose either the 32-bit or 64-bit version.
4230 ExprResult LastIteration = LastIteration64;
4231 if (LastIteration32.isUsable() &&
4232 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4233 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4234 FitsInto(
4235 32 /* Bits */,
4236 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4237 LastIteration64.get(), SemaRef)))
4238 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004239 QualType VType = LastIteration.get()->getType();
4240 QualType RealVType = VType;
4241 QualType StrideVType = VType;
4242 if (isOpenMPTaskLoopDirective(DKind)) {
4243 VType =
4244 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4245 StrideVType =
4246 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4247 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004248
4249 if (!LastIteration.isUsable())
4250 return 0;
4251
4252 // Save the number of iterations.
4253 ExprResult NumIterations = LastIteration;
4254 {
4255 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004256 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4257 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004258 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4259 if (!LastIteration.isUsable())
4260 return 0;
4261 }
4262
4263 // Calculate the last iteration number beforehand instead of doing this on
4264 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4265 llvm::APSInt Result;
4266 bool IsConstant =
4267 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4268 ExprResult CalcLastIteration;
4269 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004270 ExprResult SaveRef =
4271 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004272 LastIteration = SaveRef;
4273
4274 // Prepare SaveRef + 1.
4275 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004276 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004277 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4278 if (!NumIterations.isUsable())
4279 return 0;
4280 }
4281
4282 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4283
David Majnemer9d168222016-08-05 17:44:54 +00004284 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004285 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004286 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4287 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004288 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004289 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4290 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004291 SemaRef.AddInitializerToDecl(LBDecl,
4292 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4293 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004294
4295 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004296 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4297 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004298 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004299 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004300
4301 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4302 // This will be used to implement clause 'lastprivate'.
4303 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004304 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4305 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004306 SemaRef.AddInitializerToDecl(ILDecl,
4307 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4308 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004309
4310 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004311 VarDecl *STDecl =
4312 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4313 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004314 SemaRef.AddInitializerToDecl(STDecl,
4315 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4316 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004317
4318 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004319 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004320 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4321 UB.get(), LastIteration.get());
4322 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4323 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4324 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4325 CondOp.get());
4326 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004327
4328 // If we have a combined directive that combines 'distribute', 'for' or
4329 // 'simd' we need to be able to access the bounds of the schedule of the
4330 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4331 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4332 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004333
Carlo Bertolliffafe102017-04-20 00:39:39 +00004334 // Lower bound variable, initialized with zero.
4335 VarDecl *CombLBDecl =
4336 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4337 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4338 SemaRef.AddInitializerToDecl(
4339 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4340 /*DirectInit*/ false);
4341
4342 // Upper bound variable, initialized with last iteration number.
4343 VarDecl *CombUBDecl =
4344 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4345 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4346 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4347 /*DirectInit*/ false);
4348
4349 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4350 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4351 ExprResult CombCondOp =
4352 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4353 LastIteration.get(), CombUB.get());
4354 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4355 CombCondOp.get());
4356 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4357
4358 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004359 // We expect to have at least 2 more parameters than the 'parallel'
4360 // directive does - the lower and upper bounds of the previous schedule.
4361 assert(CD->getNumParams() >= 4 &&
4362 "Unexpected number of parameters in loop combined directive");
4363
4364 // Set the proper type for the bounds given what we learned from the
4365 // enclosed loops.
4366 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4367 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4368
4369 // Previous lower and upper bounds are obtained from the region
4370 // parameters.
4371 PrevLB =
4372 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4373 PrevUB =
4374 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4375 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004376 }
4377
4378 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004379 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004380 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004381 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004382 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4383 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004384 Expr *RHS =
4385 (isOpenMPWorksharingDirective(DKind) ||
4386 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4387 ? LB.get()
4388 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004389 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4390 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004391
4392 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4393 Expr *CombRHS =
4394 (isOpenMPWorksharingDirective(DKind) ||
4395 isOpenMPTaskLoopDirective(DKind) ||
4396 isOpenMPDistributeDirective(DKind))
4397 ? CombLB.get()
4398 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4399 CombInit =
4400 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4401 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4402 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004403 }
4404
Alexander Musmanc6388682014-12-15 07:07:06 +00004405 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004406 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004407 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004408 (isOpenMPWorksharingDirective(DKind) ||
4409 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004410 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4411 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4412 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004413 ExprResult CombCond;
4414 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4415 CombCond =
4416 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4417 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004418 // Loop increment (IV = IV + 1)
4419 SourceLocation IncLoc;
4420 ExprResult Inc =
4421 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4422 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4423 if (!Inc.isUsable())
4424 return 0;
4425 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004426 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4427 if (!Inc.isUsable())
4428 return 0;
4429
4430 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4431 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004432 // In combined construct, add combined version that use CombLB and CombUB
4433 // base variables for the update
4434 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004435 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4436 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004437 // LB + ST
4438 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4439 if (!NextLB.isUsable())
4440 return 0;
4441 // LB = LB + ST
4442 NextLB =
4443 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4444 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4445 if (!NextLB.isUsable())
4446 return 0;
4447 // UB + ST
4448 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4449 if (!NextUB.isUsable())
4450 return 0;
4451 // UB = UB + ST
4452 NextUB =
4453 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4454 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4455 if (!NextUB.isUsable())
4456 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004457 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4458 CombNextLB =
4459 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4460 if (!NextLB.isUsable())
4461 return 0;
4462 // LB = LB + ST
4463 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4464 CombNextLB.get());
4465 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4466 if (!CombNextLB.isUsable())
4467 return 0;
4468 // UB + ST
4469 CombNextUB =
4470 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4471 if (!CombNextUB.isUsable())
4472 return 0;
4473 // UB = UB + ST
4474 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4475 CombNextUB.get());
4476 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4477 if (!CombNextUB.isUsable())
4478 return 0;
4479 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004480 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004481
Carlo Bertolliffafe102017-04-20 00:39:39 +00004482 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004483 // directive with for as IV = IV + ST; ensure upper bound expression based
4484 // on PrevUB instead of NumIterations - used to implement 'for' when found
4485 // in combination with 'distribute', like in 'distribute parallel for'
4486 SourceLocation DistIncLoc;
4487 ExprResult DistCond, DistInc, PrevEUB;
4488 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4489 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4490 assert(DistCond.isUsable() && "distribute cond expr was not built");
4491
4492 DistInc =
4493 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4494 assert(DistInc.isUsable() && "distribute inc expr was not built");
4495 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4496 DistInc.get());
4497 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4498 assert(DistInc.isUsable() && "distribute inc expr was not built");
4499
4500 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4501 // construct
4502 SourceLocation DistEUBLoc;
4503 ExprResult IsUBGreater =
4504 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4505 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4506 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4507 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4508 CondOp.get());
4509 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4510 }
4511
Alexander Musmana5f070a2014-10-01 06:03:56 +00004512 // Build updates and final values of the loop counters.
4513 bool HasErrors = false;
4514 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004515 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004516 Built.Updates.resize(NestedLoopCount);
4517 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004518 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004519 {
4520 ExprResult Div;
4521 // Go from inner nested loop to outer.
4522 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4523 LoopIterationSpace &IS = IterSpaces[Cnt];
4524 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4525 // Build: Iter = (IV / Div) % IS.NumIters
4526 // where Div is product of previous iterations' IS.NumIters.
4527 ExprResult Iter;
4528 if (Div.isUsable()) {
4529 Iter =
4530 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4531 } else {
4532 Iter = IV;
4533 assert((Cnt == (int)NestedLoopCount - 1) &&
4534 "unusable div expected on first iteration only");
4535 }
4536
4537 if (Cnt != 0 && Iter.isUsable())
4538 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4539 IS.NumIterations);
4540 if (!Iter.isUsable()) {
4541 HasErrors = true;
4542 break;
4543 }
4544
Alexey Bataev39f915b82015-05-08 10:41:21 +00004545 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004546 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4547 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4548 IS.CounterVar->getExprLoc(),
4549 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004550 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004551 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004552 if (!Init.isUsable()) {
4553 HasErrors = true;
4554 break;
4555 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004556 ExprResult Update = BuildCounterUpdate(
4557 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4558 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004559 if (!Update.isUsable()) {
4560 HasErrors = true;
4561 break;
4562 }
4563
4564 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4565 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004566 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004567 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004568 if (!Final.isUsable()) {
4569 HasErrors = true;
4570 break;
4571 }
4572
4573 // Build Div for the next iteration: Div <- Div * IS.NumIters
4574 if (Cnt != 0) {
4575 if (Div.isUnset())
4576 Div = IS.NumIterations;
4577 else
4578 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4579 IS.NumIterations);
4580
4581 // Add parentheses (for debugging purposes only).
4582 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004583 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004584 if (!Div.isUsable()) {
4585 HasErrors = true;
4586 break;
4587 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004588 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004589 }
4590 if (!Update.isUsable() || !Final.isUsable()) {
4591 HasErrors = true;
4592 break;
4593 }
4594 // Save results
4595 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004596 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004597 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004598 Built.Updates[Cnt] = Update.get();
4599 Built.Finals[Cnt] = Final.get();
4600 }
4601 }
4602
4603 if (HasErrors)
4604 return 0;
4605
4606 // Save results
4607 Built.IterationVarRef = IV.get();
4608 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004609 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004610 Built.CalcLastIteration =
4611 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004612 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004613 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004614 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004615 Built.Init = Init.get();
4616 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004617 Built.LB = LB.get();
4618 Built.UB = UB.get();
4619 Built.IL = IL.get();
4620 Built.ST = ST.get();
4621 Built.EUB = EUB.get();
4622 Built.NLB = NextLB.get();
4623 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004624 Built.PrevLB = PrevLB.get();
4625 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004626 Built.DistInc = DistInc.get();
4627 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004628 Built.DistCombinedFields.LB = CombLB.get();
4629 Built.DistCombinedFields.UB = CombUB.get();
4630 Built.DistCombinedFields.EUB = CombEUB.get();
4631 Built.DistCombinedFields.Init = CombInit.get();
4632 Built.DistCombinedFields.Cond = CombCond.get();
4633 Built.DistCombinedFields.NLB = CombNextLB.get();
4634 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004635
Alexey Bataev8b427062016-05-25 12:36:08 +00004636 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4637 // Fill data for doacross depend clauses.
4638 for (auto Pair : DSA.getDoacrossDependClauses()) {
4639 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4640 Pair.first->setCounterValue(CounterVal);
4641 else {
4642 if (NestedLoopCount != Pair.second.size() ||
4643 NestedLoopCount != LoopMultipliers.size() + 1) {
4644 // Erroneous case - clause has some problems.
4645 Pair.first->setCounterValue(CounterVal);
4646 continue;
4647 }
4648 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4649 auto I = Pair.second.rbegin();
4650 auto IS = IterSpaces.rbegin();
4651 auto ILM = LoopMultipliers.rbegin();
4652 Expr *UpCounterVal = CounterVal;
4653 Expr *Multiplier = nullptr;
4654 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4655 if (I->first) {
4656 assert(IS->CounterStep);
4657 Expr *NormalizedOffset =
4658 SemaRef
4659 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4660 I->first, IS->CounterStep)
4661 .get();
4662 if (Multiplier) {
4663 NormalizedOffset =
4664 SemaRef
4665 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4666 NormalizedOffset, Multiplier)
4667 .get();
4668 }
4669 assert(I->second == OO_Plus || I->second == OO_Minus);
4670 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004671 UpCounterVal = SemaRef
4672 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4673 UpCounterVal, NormalizedOffset)
4674 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004675 }
4676 Multiplier = *ILM;
4677 ++I;
4678 ++IS;
4679 ++ILM;
4680 }
4681 Pair.first->setCounterValue(UpCounterVal);
4682 }
4683 }
4684
Alexey Bataevabfc0692014-06-25 06:52:00 +00004685 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004686}
4687
Alexey Bataev10e775f2015-07-30 11:36:16 +00004688static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004689 auto CollapseClauses =
4690 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4691 if (CollapseClauses.begin() != CollapseClauses.end())
4692 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004693 return nullptr;
4694}
4695
Alexey Bataev10e775f2015-07-30 11:36:16 +00004696static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004697 auto OrderedClauses =
4698 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4699 if (OrderedClauses.begin() != OrderedClauses.end())
4700 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004701 return nullptr;
4702}
4703
Kelvin Lic5609492016-07-15 04:39:07 +00004704static bool checkSimdlenSafelenSpecified(Sema &S,
4705 const ArrayRef<OMPClause *> Clauses) {
4706 OMPSafelenClause *Safelen = nullptr;
4707 OMPSimdlenClause *Simdlen = nullptr;
4708
4709 for (auto *Clause : Clauses) {
4710 if (Clause->getClauseKind() == OMPC_safelen)
4711 Safelen = cast<OMPSafelenClause>(Clause);
4712 else if (Clause->getClauseKind() == OMPC_simdlen)
4713 Simdlen = cast<OMPSimdlenClause>(Clause);
4714 if (Safelen && Simdlen)
4715 break;
4716 }
4717
4718 if (Simdlen && Safelen) {
4719 llvm::APSInt SimdlenRes, SafelenRes;
4720 auto SimdlenLength = Simdlen->getSimdlen();
4721 auto SafelenLength = Safelen->getSafelen();
4722 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4723 SimdlenLength->isInstantiationDependent() ||
4724 SimdlenLength->containsUnexpandedParameterPack())
4725 return false;
4726 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4727 SafelenLength->isInstantiationDependent() ||
4728 SafelenLength->containsUnexpandedParameterPack())
4729 return false;
4730 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4731 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4732 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4733 // If both simdlen and safelen clauses are specified, the value of the
4734 // simdlen parameter must be less than or equal to the value of the safelen
4735 // parameter.
4736 if (SimdlenRes > SafelenRes) {
4737 S.Diag(SimdlenLength->getExprLoc(),
4738 diag::err_omp_wrong_simdlen_safelen_values)
4739 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4740 return true;
4741 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004742 }
4743 return false;
4744}
4745
Alexey Bataev4acb8592014-07-07 13:01:15 +00004746StmtResult Sema::ActOnOpenMPSimdDirective(
4747 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4748 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004749 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004750 if (!AStmt)
4751 return StmtError();
4752
4753 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004754 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004755 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4756 // define the nested loops number.
4757 unsigned NestedLoopCount = CheckOpenMPLoop(
4758 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4759 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004760 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004761 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004762
Alexander Musmana5f070a2014-10-01 06:03:56 +00004763 assert((CurContext->isDependentContext() || B.builtAll()) &&
4764 "omp simd loop exprs were not built");
4765
Alexander Musman3276a272015-03-21 10:12:56 +00004766 if (!CurContext->isDependentContext()) {
4767 // Finalize the clauses that need pre-built expressions for CodeGen.
4768 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004769 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004770 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004771 B.NumIterations, *this, CurScope,
4772 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004773 return StmtError();
4774 }
4775 }
4776
Kelvin Lic5609492016-07-15 04:39:07 +00004777 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004778 return StmtError();
4779
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004780 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004781 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4782 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004783}
4784
Alexey Bataev4acb8592014-07-07 13:01:15 +00004785StmtResult Sema::ActOnOpenMPForDirective(
4786 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4787 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004788 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004789 if (!AStmt)
4790 return StmtError();
4791
4792 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004793 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004794 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4795 // define the nested loops number.
4796 unsigned NestedLoopCount = CheckOpenMPLoop(
4797 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4798 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004799 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004800 return StmtError();
4801
Alexander Musmana5f070a2014-10-01 06:03:56 +00004802 assert((CurContext->isDependentContext() || B.builtAll()) &&
4803 "omp for loop exprs were not built");
4804
Alexey Bataev54acd402015-08-04 11:18:19 +00004805 if (!CurContext->isDependentContext()) {
4806 // Finalize the clauses that need pre-built expressions for CodeGen.
4807 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004808 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004809 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004810 B.NumIterations, *this, CurScope,
4811 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004812 return StmtError();
4813 }
4814 }
4815
Alexey Bataevf29276e2014-06-18 04:14:57 +00004816 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004817 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004818 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004819}
4820
Alexander Musmanf82886e2014-09-18 05:12:34 +00004821StmtResult Sema::ActOnOpenMPForSimdDirective(
4822 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4823 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004824 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004825 if (!AStmt)
4826 return StmtError();
4827
4828 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004829 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004830 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4831 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004832 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004833 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4834 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4835 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004836 if (NestedLoopCount == 0)
4837 return StmtError();
4838
Alexander Musmanc6388682014-12-15 07:07:06 +00004839 assert((CurContext->isDependentContext() || B.builtAll()) &&
4840 "omp for simd loop exprs were not built");
4841
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004842 if (!CurContext->isDependentContext()) {
4843 // Finalize the clauses that need pre-built expressions for CodeGen.
4844 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004845 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004846 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004847 B.NumIterations, *this, CurScope,
4848 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004849 return StmtError();
4850 }
4851 }
4852
Kelvin Lic5609492016-07-15 04:39:07 +00004853 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004854 return StmtError();
4855
Alexander Musmanf82886e2014-09-18 05:12:34 +00004856 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004857 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4858 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004859}
4860
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004861StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4862 Stmt *AStmt,
4863 SourceLocation StartLoc,
4864 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004865 if (!AStmt)
4866 return StmtError();
4867
4868 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004869 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004870 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004871 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004872 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004873 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004874 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004875 return StmtError();
4876 // All associated statements must be '#pragma omp section' except for
4877 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004878 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004879 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4880 if (SectionStmt)
4881 Diag(SectionStmt->getLocStart(),
4882 diag::err_omp_sections_substmt_not_section);
4883 return StmtError();
4884 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004885 cast<OMPSectionDirective>(SectionStmt)
4886 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004887 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004888 } else {
4889 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4890 return StmtError();
4891 }
4892
4893 getCurFunction()->setHasBranchProtectedScope();
4894
Alexey Bataev25e5b442015-09-15 12:52:43 +00004895 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4896 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004897}
4898
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004899StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4900 SourceLocation StartLoc,
4901 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004902 if (!AStmt)
4903 return StmtError();
4904
4905 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004906
4907 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004908 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004909
Alexey Bataev25e5b442015-09-15 12:52:43 +00004910 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4911 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004912}
4913
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004914StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4915 Stmt *AStmt,
4916 SourceLocation StartLoc,
4917 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004918 if (!AStmt)
4919 return StmtError();
4920
4921 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004922
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004923 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004924
Alexey Bataev3255bf32015-01-19 05:20:46 +00004925 // OpenMP [2.7.3, single Construct, Restrictions]
4926 // The copyprivate clause must not be used with the nowait clause.
4927 OMPClause *Nowait = nullptr;
4928 OMPClause *Copyprivate = nullptr;
4929 for (auto *Clause : Clauses) {
4930 if (Clause->getClauseKind() == OMPC_nowait)
4931 Nowait = Clause;
4932 else if (Clause->getClauseKind() == OMPC_copyprivate)
4933 Copyprivate = Clause;
4934 if (Copyprivate && Nowait) {
4935 Diag(Copyprivate->getLocStart(),
4936 diag::err_omp_single_copyprivate_with_nowait);
4937 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4938 return StmtError();
4939 }
4940 }
4941
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004942 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4943}
4944
Alexander Musman80c22892014-07-17 08:54:58 +00004945StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4946 SourceLocation StartLoc,
4947 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004948 if (!AStmt)
4949 return StmtError();
4950
4951 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004952
4953 getCurFunction()->setHasBranchProtectedScope();
4954
4955 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4956}
4957
Alexey Bataev28c75412015-12-15 08:19:24 +00004958StmtResult Sema::ActOnOpenMPCriticalDirective(
4959 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4960 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004961 if (!AStmt)
4962 return StmtError();
4963
4964 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004965
Alexey Bataev28c75412015-12-15 08:19:24 +00004966 bool ErrorFound = false;
4967 llvm::APSInt Hint;
4968 SourceLocation HintLoc;
4969 bool DependentHint = false;
4970 for (auto *C : Clauses) {
4971 if (C->getClauseKind() == OMPC_hint) {
4972 if (!DirName.getName()) {
4973 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4974 ErrorFound = true;
4975 }
4976 Expr *E = cast<OMPHintClause>(C)->getHint();
4977 if (E->isTypeDependent() || E->isValueDependent() ||
4978 E->isInstantiationDependent())
4979 DependentHint = true;
4980 else {
4981 Hint = E->EvaluateKnownConstInt(Context);
4982 HintLoc = C->getLocStart();
4983 }
4984 }
4985 }
4986 if (ErrorFound)
4987 return StmtError();
4988 auto Pair = DSAStack->getCriticalWithHint(DirName);
4989 if (Pair.first && DirName.getName() && !DependentHint) {
4990 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4991 Diag(StartLoc, diag::err_omp_critical_with_hint);
4992 if (HintLoc.isValid()) {
4993 Diag(HintLoc, diag::note_omp_critical_hint_here)
4994 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4995 } else
4996 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4997 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4998 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4999 << 1
5000 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5001 /*Radix=*/10, /*Signed=*/false);
5002 } else
5003 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5004 }
5005 }
5006
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005007 getCurFunction()->setHasBranchProtectedScope();
5008
Alexey Bataev28c75412015-12-15 08:19:24 +00005009 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5010 Clauses, AStmt);
5011 if (!Pair.first && DirName.getName() && !DependentHint)
5012 DSAStack->addCriticalWithHint(Dir, Hint);
5013 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005014}
5015
Alexey Bataev4acb8592014-07-07 13:01:15 +00005016StmtResult Sema::ActOnOpenMPParallelForDirective(
5017 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5018 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005019 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005020 if (!AStmt)
5021 return StmtError();
5022
Alexey Bataev4acb8592014-07-07 13:01:15 +00005023 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5024 // 1.2.2 OpenMP Language Terminology
5025 // Structured block - An executable statement with a single entry at the
5026 // top and a single exit at the bottom.
5027 // The point of exit cannot be a branch out of the structured block.
5028 // longjmp() and throw() must not violate the entry/exit criteria.
5029 CS->getCapturedDecl()->setNothrow();
5030
Alexander Musmanc6388682014-12-15 07:07:06 +00005031 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005032 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5033 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005034 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005035 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5036 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5037 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005038 if (NestedLoopCount == 0)
5039 return StmtError();
5040
Alexander Musmana5f070a2014-10-01 06:03:56 +00005041 assert((CurContext->isDependentContext() || B.builtAll()) &&
5042 "omp parallel for loop exprs were not built");
5043
Alexey Bataev54acd402015-08-04 11:18:19 +00005044 if (!CurContext->isDependentContext()) {
5045 // Finalize the clauses that need pre-built expressions for CodeGen.
5046 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005047 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005048 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005049 B.NumIterations, *this, CurScope,
5050 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005051 return StmtError();
5052 }
5053 }
5054
Alexey Bataev4acb8592014-07-07 13:01:15 +00005055 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005056 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005057 NestedLoopCount, Clauses, AStmt, B,
5058 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005059}
5060
Alexander Musmane4e893b2014-09-23 09:33:00 +00005061StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5062 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5063 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005064 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005065 if (!AStmt)
5066 return StmtError();
5067
Alexander Musmane4e893b2014-09-23 09:33:00 +00005068 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5069 // 1.2.2 OpenMP Language Terminology
5070 // Structured block - An executable statement with a single entry at the
5071 // top and a single exit at the bottom.
5072 // The point of exit cannot be a branch out of the structured block.
5073 // longjmp() and throw() must not violate the entry/exit criteria.
5074 CS->getCapturedDecl()->setNothrow();
5075
Alexander Musmanc6388682014-12-15 07:07:06 +00005076 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005077 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5078 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005079 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005080 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5081 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5082 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005083 if (NestedLoopCount == 0)
5084 return StmtError();
5085
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005086 if (!CurContext->isDependentContext()) {
5087 // Finalize the clauses that need pre-built expressions for CodeGen.
5088 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005089 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005090 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005091 B.NumIterations, *this, CurScope,
5092 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005093 return StmtError();
5094 }
5095 }
5096
Kelvin Lic5609492016-07-15 04:39:07 +00005097 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005098 return StmtError();
5099
Alexander Musmane4e893b2014-09-23 09:33:00 +00005100 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005101 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005102 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005103}
5104
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005105StmtResult
5106Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5107 Stmt *AStmt, SourceLocation StartLoc,
5108 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005109 if (!AStmt)
5110 return StmtError();
5111
5112 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005113 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005114 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005115 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005116 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005117 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005118 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005119 return StmtError();
5120 // All associated statements must be '#pragma omp section' except for
5121 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005122 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005123 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5124 if (SectionStmt)
5125 Diag(SectionStmt->getLocStart(),
5126 diag::err_omp_parallel_sections_substmt_not_section);
5127 return StmtError();
5128 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005129 cast<OMPSectionDirective>(SectionStmt)
5130 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005131 }
5132 } else {
5133 Diag(AStmt->getLocStart(),
5134 diag::err_omp_parallel_sections_not_compound_stmt);
5135 return StmtError();
5136 }
5137
5138 getCurFunction()->setHasBranchProtectedScope();
5139
Alexey Bataev25e5b442015-09-15 12:52:43 +00005140 return OMPParallelSectionsDirective::Create(
5141 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005142}
5143
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005144StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5145 Stmt *AStmt, SourceLocation StartLoc,
5146 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005147 if (!AStmt)
5148 return StmtError();
5149
David Majnemer9d168222016-08-05 17:44:54 +00005150 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005151 // 1.2.2 OpenMP Language Terminology
5152 // Structured block - An executable statement with a single entry at the
5153 // top and a single exit at the bottom.
5154 // The point of exit cannot be a branch out of the structured block.
5155 // longjmp() and throw() must not violate the entry/exit criteria.
5156 CS->getCapturedDecl()->setNothrow();
5157
5158 getCurFunction()->setHasBranchProtectedScope();
5159
Alexey Bataev25e5b442015-09-15 12:52:43 +00005160 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5161 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005162}
5163
Alexey Bataev68446b72014-07-18 07:47:19 +00005164StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5165 SourceLocation EndLoc) {
5166 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5167}
5168
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005169StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5170 SourceLocation EndLoc) {
5171 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5172}
5173
Alexey Bataev2df347a2014-07-18 10:17:07 +00005174StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5175 SourceLocation EndLoc) {
5176 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5177}
5178
Alexey Bataev169d96a2017-07-18 20:17:46 +00005179StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5180 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005181 SourceLocation StartLoc,
5182 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005183 if (!AStmt)
5184 return StmtError();
5185
5186 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005187
5188 getCurFunction()->setHasBranchProtectedScope();
5189
Alexey Bataev169d96a2017-07-18 20:17:46 +00005190 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5191 AStmt);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005192}
5193
Alexey Bataev6125da92014-07-21 11:26:11 +00005194StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5195 SourceLocation StartLoc,
5196 SourceLocation EndLoc) {
5197 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5198 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5199}
5200
Alexey Bataev346265e2015-09-25 10:37:12 +00005201StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5202 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005203 SourceLocation StartLoc,
5204 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005205 OMPClause *DependFound = nullptr;
5206 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005207 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005208 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005209 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005210 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005211 for (auto *C : Clauses) {
5212 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5213 DependFound = C;
5214 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5215 if (DependSourceClause) {
5216 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5217 << getOpenMPDirectiveName(OMPD_ordered)
5218 << getOpenMPClauseName(OMPC_depend) << 2;
5219 ErrorFound = true;
5220 } else
5221 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005222 if (DependSinkClause) {
5223 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5224 << 0;
5225 ErrorFound = true;
5226 }
5227 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5228 if (DependSourceClause) {
5229 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5230 << 1;
5231 ErrorFound = true;
5232 }
5233 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005234 }
5235 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005236 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005237 else if (C->getClauseKind() == OMPC_simd)
5238 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005239 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005240 if (!ErrorFound && !SC &&
5241 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005242 // OpenMP [2.8.1,simd Construct, Restrictions]
5243 // An ordered construct with the simd clause is the only OpenMP construct
5244 // that can appear in the simd region.
5245 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005246 ErrorFound = true;
5247 } else if (DependFound && (TC || SC)) {
5248 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5249 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5250 ErrorFound = true;
5251 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5252 Diag(DependFound->getLocStart(),
5253 diag::err_omp_ordered_directive_without_param);
5254 ErrorFound = true;
5255 } else if (TC || Clauses.empty()) {
5256 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5257 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5258 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5259 << (TC != nullptr);
5260 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5261 ErrorFound = true;
5262 }
5263 }
5264 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005265 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005266
5267 if (AStmt) {
5268 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5269
5270 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005271 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005272
5273 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005274}
5275
Alexey Bataev1d160b12015-03-13 12:27:31 +00005276namespace {
5277/// \brief Helper class for checking expression in 'omp atomic [update]'
5278/// construct.
5279class OpenMPAtomicUpdateChecker {
5280 /// \brief Error results for atomic update expressions.
5281 enum ExprAnalysisErrorCode {
5282 /// \brief A statement is not an expression statement.
5283 NotAnExpression,
5284 /// \brief Expression is not builtin binary or unary operation.
5285 NotABinaryOrUnaryExpression,
5286 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5287 NotAnUnaryIncDecExpression,
5288 /// \brief An expression is not of scalar type.
5289 NotAScalarType,
5290 /// \brief A binary operation is not an assignment operation.
5291 NotAnAssignmentOp,
5292 /// \brief RHS part of the binary operation is not a binary expression.
5293 NotABinaryExpression,
5294 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5295 /// expression.
5296 NotABinaryOperator,
5297 /// \brief RHS binary operation does not have reference to the updated LHS
5298 /// part.
5299 NotAnUpdateExpression,
5300 /// \brief No errors is found.
5301 NoError
5302 };
5303 /// \brief Reference to Sema.
5304 Sema &SemaRef;
5305 /// \brief A location for note diagnostics (when error is found).
5306 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005307 /// \brief 'x' lvalue part of the source atomic expression.
5308 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005309 /// \brief 'expr' rvalue part of the source atomic expression.
5310 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005311 /// \brief Helper expression of the form
5312 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5313 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5314 Expr *UpdateExpr;
5315 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5316 /// important for non-associative operations.
5317 bool IsXLHSInRHSPart;
5318 BinaryOperatorKind Op;
5319 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005320 /// \brief true if the source expression is a postfix unary operation, false
5321 /// if it is a prefix unary operation.
5322 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005323
5324public:
5325 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005326 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005327 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005328 /// \brief Check specified statement that it is suitable for 'atomic update'
5329 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005330 /// expression. If DiagId and NoteId == 0, then only check is performed
5331 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005332 /// \param DiagId Diagnostic which should be emitted if error is found.
5333 /// \param NoteId Diagnostic note for the main error message.
5334 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005335 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005336 /// \brief Return the 'x' lvalue part of the source atomic expression.
5337 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005338 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5339 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005340 /// \brief Return the update expression used in calculation of the updated
5341 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5342 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5343 Expr *getUpdateExpr() const { return UpdateExpr; }
5344 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5345 /// false otherwise.
5346 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5347
Alexey Bataevb78ca832015-04-01 03:33:17 +00005348 /// \brief true if the source expression is a postfix unary operation, false
5349 /// if it is a prefix unary operation.
5350 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5351
Alexey Bataev1d160b12015-03-13 12:27:31 +00005352private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005353 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5354 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005355};
5356} // namespace
5357
5358bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5359 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5360 ExprAnalysisErrorCode ErrorFound = NoError;
5361 SourceLocation ErrorLoc, NoteLoc;
5362 SourceRange ErrorRange, NoteRange;
5363 // Allowed constructs are:
5364 // x = x binop expr;
5365 // x = expr binop x;
5366 if (AtomicBinOp->getOpcode() == BO_Assign) {
5367 X = AtomicBinOp->getLHS();
5368 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5369 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5370 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5371 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5372 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005373 Op = AtomicInnerBinOp->getOpcode();
5374 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005375 auto *LHS = AtomicInnerBinOp->getLHS();
5376 auto *RHS = AtomicInnerBinOp->getRHS();
5377 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5378 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5379 /*Canonical=*/true);
5380 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5381 /*Canonical=*/true);
5382 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5383 /*Canonical=*/true);
5384 if (XId == LHSId) {
5385 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005386 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005387 } else if (XId == RHSId) {
5388 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005389 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005390 } else {
5391 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5392 ErrorRange = AtomicInnerBinOp->getSourceRange();
5393 NoteLoc = X->getExprLoc();
5394 NoteRange = X->getSourceRange();
5395 ErrorFound = NotAnUpdateExpression;
5396 }
5397 } else {
5398 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5399 ErrorRange = AtomicInnerBinOp->getSourceRange();
5400 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5401 NoteRange = SourceRange(NoteLoc, NoteLoc);
5402 ErrorFound = NotABinaryOperator;
5403 }
5404 } else {
5405 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5406 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5407 ErrorFound = NotABinaryExpression;
5408 }
5409 } else {
5410 ErrorLoc = AtomicBinOp->getExprLoc();
5411 ErrorRange = AtomicBinOp->getSourceRange();
5412 NoteLoc = AtomicBinOp->getOperatorLoc();
5413 NoteRange = SourceRange(NoteLoc, NoteLoc);
5414 ErrorFound = NotAnAssignmentOp;
5415 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005416 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005417 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5418 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5419 return true;
5420 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005421 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005422 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005423}
5424
5425bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5426 unsigned NoteId) {
5427 ExprAnalysisErrorCode ErrorFound = NoError;
5428 SourceLocation ErrorLoc, NoteLoc;
5429 SourceRange ErrorRange, NoteRange;
5430 // Allowed constructs are:
5431 // x++;
5432 // x--;
5433 // ++x;
5434 // --x;
5435 // x binop= expr;
5436 // x = x binop expr;
5437 // x = expr binop x;
5438 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5439 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5440 if (AtomicBody->getType()->isScalarType() ||
5441 AtomicBody->isInstantiationDependent()) {
5442 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5443 AtomicBody->IgnoreParenImpCasts())) {
5444 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005445 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005446 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005447 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005448 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005449 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005450 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005451 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5452 AtomicBody->IgnoreParenImpCasts())) {
5453 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005454 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005455 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005456 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5457 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005458 // Check for Unary Operation
5459 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005460 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005461 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5462 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005463 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005464 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5465 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005466 } else {
5467 ErrorFound = NotAnUnaryIncDecExpression;
5468 ErrorLoc = AtomicUnaryOp->getExprLoc();
5469 ErrorRange = AtomicUnaryOp->getSourceRange();
5470 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5471 NoteRange = SourceRange(NoteLoc, NoteLoc);
5472 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005473 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005474 ErrorFound = NotABinaryOrUnaryExpression;
5475 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5476 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5477 }
5478 } else {
5479 ErrorFound = NotAScalarType;
5480 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5481 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5482 }
5483 } else {
5484 ErrorFound = NotAnExpression;
5485 NoteLoc = ErrorLoc = S->getLocStart();
5486 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5487 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005488 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005489 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5490 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5491 return true;
5492 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005493 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005494 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005495 // Build an update expression of form 'OpaqueValueExpr(x) binop
5496 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5497 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5498 auto *OVEX = new (SemaRef.getASTContext())
5499 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5500 auto *OVEExpr = new (SemaRef.getASTContext())
5501 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5502 auto Update =
5503 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5504 IsXLHSInRHSPart ? OVEExpr : OVEX);
5505 if (Update.isInvalid())
5506 return true;
5507 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5508 Sema::AA_Casting);
5509 if (Update.isInvalid())
5510 return true;
5511 UpdateExpr = Update.get();
5512 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005513 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005514}
5515
Alexey Bataev0162e452014-07-22 10:10:35 +00005516StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5517 Stmt *AStmt,
5518 SourceLocation StartLoc,
5519 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005520 if (!AStmt)
5521 return StmtError();
5522
David Majnemer9d168222016-08-05 17:44:54 +00005523 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005524 // 1.2.2 OpenMP Language Terminology
5525 // Structured block - An executable statement with a single entry at the
5526 // top and a single exit at the bottom.
5527 // The point of exit cannot be a branch out of the structured block.
5528 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005529 OpenMPClauseKind AtomicKind = OMPC_unknown;
5530 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005531 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005532 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005533 C->getClauseKind() == OMPC_update ||
5534 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005535 if (AtomicKind != OMPC_unknown) {
5536 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5537 << SourceRange(C->getLocStart(), C->getLocEnd());
5538 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5539 << getOpenMPClauseName(AtomicKind);
5540 } else {
5541 AtomicKind = C->getClauseKind();
5542 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005543 }
5544 }
5545 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005546
Alexey Bataev459dec02014-07-24 06:46:57 +00005547 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005548 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5549 Body = EWC->getSubExpr();
5550
Alexey Bataev62cec442014-11-18 10:14:22 +00005551 Expr *X = nullptr;
5552 Expr *V = nullptr;
5553 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005554 Expr *UE = nullptr;
5555 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005556 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005557 // OpenMP [2.12.6, atomic Construct]
5558 // In the next expressions:
5559 // * x and v (as applicable) are both l-value expressions with scalar type.
5560 // * During the execution of an atomic region, multiple syntactic
5561 // occurrences of x must designate the same storage location.
5562 // * Neither of v and expr (as applicable) may access the storage location
5563 // designated by x.
5564 // * Neither of x and expr (as applicable) may access the storage location
5565 // designated by v.
5566 // * expr is an expression with scalar type.
5567 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5568 // * binop, binop=, ++, and -- are not overloaded operators.
5569 // * The expression x binop expr must be numerically equivalent to x binop
5570 // (expr). This requirement is satisfied if the operators in expr have
5571 // precedence greater than binop, or by using parentheses around expr or
5572 // subexpressions of expr.
5573 // * The expression expr binop x must be numerically equivalent to (expr)
5574 // binop x. This requirement is satisfied if the operators in expr have
5575 // precedence equal to or greater than binop, or by using parentheses around
5576 // expr or subexpressions of expr.
5577 // * For forms that allow multiple occurrences of x, the number of times
5578 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005579 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005580 enum {
5581 NotAnExpression,
5582 NotAnAssignmentOp,
5583 NotAScalarType,
5584 NotAnLValue,
5585 NoError
5586 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005587 SourceLocation ErrorLoc, NoteLoc;
5588 SourceRange ErrorRange, NoteRange;
5589 // If clause is read:
5590 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005591 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5592 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005593 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5594 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5595 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5596 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5597 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5598 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5599 if (!X->isLValue() || !V->isLValue()) {
5600 auto NotLValueExpr = X->isLValue() ? V : X;
5601 ErrorFound = NotAnLValue;
5602 ErrorLoc = AtomicBinOp->getExprLoc();
5603 ErrorRange = AtomicBinOp->getSourceRange();
5604 NoteLoc = NotLValueExpr->getExprLoc();
5605 NoteRange = NotLValueExpr->getSourceRange();
5606 }
5607 } else if (!X->isInstantiationDependent() ||
5608 !V->isInstantiationDependent()) {
5609 auto NotScalarExpr =
5610 (X->isInstantiationDependent() || X->getType()->isScalarType())
5611 ? V
5612 : X;
5613 ErrorFound = NotAScalarType;
5614 ErrorLoc = AtomicBinOp->getExprLoc();
5615 ErrorRange = AtomicBinOp->getSourceRange();
5616 NoteLoc = NotScalarExpr->getExprLoc();
5617 NoteRange = NotScalarExpr->getSourceRange();
5618 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005619 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005620 ErrorFound = NotAnAssignmentOp;
5621 ErrorLoc = AtomicBody->getExprLoc();
5622 ErrorRange = AtomicBody->getSourceRange();
5623 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5624 : AtomicBody->getExprLoc();
5625 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5626 : AtomicBody->getSourceRange();
5627 }
5628 } else {
5629 ErrorFound = NotAnExpression;
5630 NoteLoc = ErrorLoc = Body->getLocStart();
5631 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005632 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005633 if (ErrorFound != NoError) {
5634 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5635 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005636 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5637 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005638 return StmtError();
5639 } else if (CurContext->isDependentContext())
5640 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005641 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005642 enum {
5643 NotAnExpression,
5644 NotAnAssignmentOp,
5645 NotAScalarType,
5646 NotAnLValue,
5647 NoError
5648 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005649 SourceLocation ErrorLoc, NoteLoc;
5650 SourceRange ErrorRange, NoteRange;
5651 // If clause is write:
5652 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005653 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5654 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005655 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5656 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005657 X = AtomicBinOp->getLHS();
5658 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005659 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5660 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5661 if (!X->isLValue()) {
5662 ErrorFound = NotAnLValue;
5663 ErrorLoc = AtomicBinOp->getExprLoc();
5664 ErrorRange = AtomicBinOp->getSourceRange();
5665 NoteLoc = X->getExprLoc();
5666 NoteRange = X->getSourceRange();
5667 }
5668 } else if (!X->isInstantiationDependent() ||
5669 !E->isInstantiationDependent()) {
5670 auto NotScalarExpr =
5671 (X->isInstantiationDependent() || X->getType()->isScalarType())
5672 ? E
5673 : X;
5674 ErrorFound = NotAScalarType;
5675 ErrorLoc = AtomicBinOp->getExprLoc();
5676 ErrorRange = AtomicBinOp->getSourceRange();
5677 NoteLoc = NotScalarExpr->getExprLoc();
5678 NoteRange = NotScalarExpr->getSourceRange();
5679 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005680 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005681 ErrorFound = NotAnAssignmentOp;
5682 ErrorLoc = AtomicBody->getExprLoc();
5683 ErrorRange = AtomicBody->getSourceRange();
5684 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5685 : AtomicBody->getExprLoc();
5686 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5687 : AtomicBody->getSourceRange();
5688 }
5689 } else {
5690 ErrorFound = NotAnExpression;
5691 NoteLoc = ErrorLoc = Body->getLocStart();
5692 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005693 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005694 if (ErrorFound != NoError) {
5695 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5696 << ErrorRange;
5697 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5698 << NoteRange;
5699 return StmtError();
5700 } else if (CurContext->isDependentContext())
5701 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005702 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005703 // If clause is update:
5704 // x++;
5705 // x--;
5706 // ++x;
5707 // --x;
5708 // x binop= expr;
5709 // x = x binop expr;
5710 // x = expr binop x;
5711 OpenMPAtomicUpdateChecker Checker(*this);
5712 if (Checker.checkStatement(
5713 Body, (AtomicKind == OMPC_update)
5714 ? diag::err_omp_atomic_update_not_expression_statement
5715 : diag::err_omp_atomic_not_expression_statement,
5716 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005717 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005718 if (!CurContext->isDependentContext()) {
5719 E = Checker.getExpr();
5720 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005721 UE = Checker.getUpdateExpr();
5722 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005723 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005724 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005725 enum {
5726 NotAnAssignmentOp,
5727 NotACompoundStatement,
5728 NotTwoSubstatements,
5729 NotASpecificExpression,
5730 NoError
5731 } ErrorFound = NoError;
5732 SourceLocation ErrorLoc, NoteLoc;
5733 SourceRange ErrorRange, NoteRange;
5734 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5735 // If clause is a capture:
5736 // v = x++;
5737 // v = x--;
5738 // v = ++x;
5739 // v = --x;
5740 // v = x binop= expr;
5741 // v = x = x binop expr;
5742 // v = x = expr binop x;
5743 auto *AtomicBinOp =
5744 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5745 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5746 V = AtomicBinOp->getLHS();
5747 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5748 OpenMPAtomicUpdateChecker Checker(*this);
5749 if (Checker.checkStatement(
5750 Body, diag::err_omp_atomic_capture_not_expression_statement,
5751 diag::note_omp_atomic_update))
5752 return StmtError();
5753 E = Checker.getExpr();
5754 X = Checker.getX();
5755 UE = Checker.getUpdateExpr();
5756 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5757 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005758 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005759 ErrorLoc = AtomicBody->getExprLoc();
5760 ErrorRange = AtomicBody->getSourceRange();
5761 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5762 : AtomicBody->getExprLoc();
5763 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5764 : AtomicBody->getSourceRange();
5765 ErrorFound = NotAnAssignmentOp;
5766 }
5767 if (ErrorFound != NoError) {
5768 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5769 << ErrorRange;
5770 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5771 return StmtError();
5772 } else if (CurContext->isDependentContext()) {
5773 UE = V = E = X = nullptr;
5774 }
5775 } else {
5776 // If clause is a capture:
5777 // { v = x; x = expr; }
5778 // { v = x; x++; }
5779 // { v = x; x--; }
5780 // { v = x; ++x; }
5781 // { v = x; --x; }
5782 // { v = x; x binop= expr; }
5783 // { v = x; x = x binop expr; }
5784 // { v = x; x = expr binop x; }
5785 // { x++; v = x; }
5786 // { x--; v = x; }
5787 // { ++x; v = x; }
5788 // { --x; v = x; }
5789 // { x binop= expr; v = x; }
5790 // { x = x binop expr; v = x; }
5791 // { x = expr binop x; v = x; }
5792 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5793 // Check that this is { expr1; expr2; }
5794 if (CS->size() == 2) {
5795 auto *First = CS->body_front();
5796 auto *Second = CS->body_back();
5797 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5798 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5799 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5800 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5801 // Need to find what subexpression is 'v' and what is 'x'.
5802 OpenMPAtomicUpdateChecker Checker(*this);
5803 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5804 BinaryOperator *BinOp = nullptr;
5805 if (IsUpdateExprFound) {
5806 BinOp = dyn_cast<BinaryOperator>(First);
5807 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5808 }
5809 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5810 // { v = x; x++; }
5811 // { v = x; x--; }
5812 // { v = x; ++x; }
5813 // { v = x; --x; }
5814 // { v = x; x binop= expr; }
5815 // { v = x; x = x binop expr; }
5816 // { v = x; x = expr binop x; }
5817 // Check that the first expression has form v = x.
5818 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5819 llvm::FoldingSetNodeID XId, PossibleXId;
5820 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5821 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5822 IsUpdateExprFound = XId == PossibleXId;
5823 if (IsUpdateExprFound) {
5824 V = BinOp->getLHS();
5825 X = Checker.getX();
5826 E = Checker.getExpr();
5827 UE = Checker.getUpdateExpr();
5828 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005829 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005830 }
5831 }
5832 if (!IsUpdateExprFound) {
5833 IsUpdateExprFound = !Checker.checkStatement(First);
5834 BinOp = nullptr;
5835 if (IsUpdateExprFound) {
5836 BinOp = dyn_cast<BinaryOperator>(Second);
5837 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5838 }
5839 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5840 // { x++; v = x; }
5841 // { x--; v = x; }
5842 // { ++x; v = x; }
5843 // { --x; v = x; }
5844 // { x binop= expr; v = x; }
5845 // { x = x binop expr; v = x; }
5846 // { x = expr binop x; v = x; }
5847 // Check that the second expression has form v = x.
5848 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5849 llvm::FoldingSetNodeID XId, PossibleXId;
5850 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5851 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5852 IsUpdateExprFound = XId == PossibleXId;
5853 if (IsUpdateExprFound) {
5854 V = BinOp->getLHS();
5855 X = Checker.getX();
5856 E = Checker.getExpr();
5857 UE = Checker.getUpdateExpr();
5858 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005859 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005860 }
5861 }
5862 }
5863 if (!IsUpdateExprFound) {
5864 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005865 auto *FirstExpr = dyn_cast<Expr>(First);
5866 auto *SecondExpr = dyn_cast<Expr>(Second);
5867 if (!FirstExpr || !SecondExpr ||
5868 !(FirstExpr->isInstantiationDependent() ||
5869 SecondExpr->isInstantiationDependent())) {
5870 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5871 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005872 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005873 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5874 : First->getLocStart();
5875 NoteRange = ErrorRange = FirstBinOp
5876 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005877 : SourceRange(ErrorLoc, ErrorLoc);
5878 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005879 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5880 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5881 ErrorFound = NotAnAssignmentOp;
5882 NoteLoc = ErrorLoc = SecondBinOp
5883 ? SecondBinOp->getOperatorLoc()
5884 : Second->getLocStart();
5885 NoteRange = ErrorRange =
5886 SecondBinOp ? SecondBinOp->getSourceRange()
5887 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005888 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005889 auto *PossibleXRHSInFirst =
5890 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5891 auto *PossibleXLHSInSecond =
5892 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5893 llvm::FoldingSetNodeID X1Id, X2Id;
5894 PossibleXRHSInFirst->Profile(X1Id, Context,
5895 /*Canonical=*/true);
5896 PossibleXLHSInSecond->Profile(X2Id, Context,
5897 /*Canonical=*/true);
5898 IsUpdateExprFound = X1Id == X2Id;
5899 if (IsUpdateExprFound) {
5900 V = FirstBinOp->getLHS();
5901 X = SecondBinOp->getLHS();
5902 E = SecondBinOp->getRHS();
5903 UE = nullptr;
5904 IsXLHSInRHSPart = false;
5905 IsPostfixUpdate = true;
5906 } else {
5907 ErrorFound = NotASpecificExpression;
5908 ErrorLoc = FirstBinOp->getExprLoc();
5909 ErrorRange = FirstBinOp->getSourceRange();
5910 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5911 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5912 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005913 }
5914 }
5915 }
5916 }
5917 } else {
5918 NoteLoc = ErrorLoc = Body->getLocStart();
5919 NoteRange = ErrorRange =
5920 SourceRange(Body->getLocStart(), Body->getLocStart());
5921 ErrorFound = NotTwoSubstatements;
5922 }
5923 } else {
5924 NoteLoc = ErrorLoc = Body->getLocStart();
5925 NoteRange = ErrorRange =
5926 SourceRange(Body->getLocStart(), Body->getLocStart());
5927 ErrorFound = NotACompoundStatement;
5928 }
5929 if (ErrorFound != NoError) {
5930 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5931 << ErrorRange;
5932 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5933 return StmtError();
5934 } else if (CurContext->isDependentContext()) {
5935 UE = V = E = X = nullptr;
5936 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005937 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005938 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005939
5940 getCurFunction()->setHasBranchProtectedScope();
5941
Alexey Bataev62cec442014-11-18 10:14:22 +00005942 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005943 X, V, E, UE, IsXLHSInRHSPart,
5944 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005945}
5946
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005947StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5948 Stmt *AStmt,
5949 SourceLocation StartLoc,
5950 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005951 if (!AStmt)
5952 return StmtError();
5953
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005954 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5955 // 1.2.2 OpenMP Language Terminology
5956 // Structured block - An executable statement with a single entry at the
5957 // top and a single exit at the bottom.
5958 // The point of exit cannot be a branch out of the structured block.
5959 // longjmp() and throw() must not violate the entry/exit criteria.
5960 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005961
Alexey Bataev13314bf2014-10-09 04:18:56 +00005962 // OpenMP [2.16, Nesting of Regions]
5963 // If specified, a teams construct must be contained within a target
5964 // construct. That target construct must contain no statements or directives
5965 // outside of the teams construct.
5966 if (DSAStack->hasInnerTeamsRegion()) {
5967 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5968 bool OMPTeamsFound = true;
5969 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5970 auto I = CS->body_begin();
5971 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005972 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005973 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5974 OMPTeamsFound = false;
5975 break;
5976 }
5977 ++I;
5978 }
5979 assert(I != CS->body_end() && "Not found statement");
5980 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005981 } else {
5982 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5983 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005984 }
5985 if (!OMPTeamsFound) {
5986 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5987 Diag(DSAStack->getInnerTeamsRegionLoc(),
5988 diag::note_omp_nested_teams_construct_here);
5989 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5990 << isa<OMPExecutableDirective>(S);
5991 return StmtError();
5992 }
5993 }
5994
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005995 getCurFunction()->setHasBranchProtectedScope();
5996
5997 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5998}
5999
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006000StmtResult
6001Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6002 Stmt *AStmt, SourceLocation StartLoc,
6003 SourceLocation EndLoc) {
6004 if (!AStmt)
6005 return StmtError();
6006
6007 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6008 // 1.2.2 OpenMP Language Terminology
6009 // Structured block - An executable statement with a single entry at the
6010 // top and a single exit at the bottom.
6011 // The point of exit cannot be a branch out of the structured block.
6012 // longjmp() and throw() must not violate the entry/exit criteria.
6013 CS->getCapturedDecl()->setNothrow();
6014
6015 getCurFunction()->setHasBranchProtectedScope();
6016
6017 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6018 AStmt);
6019}
6020
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006021StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6022 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6023 SourceLocation EndLoc,
6024 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6025 if (!AStmt)
6026 return StmtError();
6027
6028 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6029 // 1.2.2 OpenMP Language Terminology
6030 // Structured block - An executable statement with a single entry at the
6031 // top and a single exit at the bottom.
6032 // The point of exit cannot be a branch out of the structured block.
6033 // longjmp() and throw() must not violate the entry/exit criteria.
6034 CS->getCapturedDecl()->setNothrow();
6035
6036 OMPLoopDirective::HelperExprs B;
6037 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6038 // define the nested loops number.
6039 unsigned NestedLoopCount =
6040 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6041 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6042 VarsWithImplicitDSA, B);
6043 if (NestedLoopCount == 0)
6044 return StmtError();
6045
6046 assert((CurContext->isDependentContext() || B.builtAll()) &&
6047 "omp target parallel for loop exprs were not built");
6048
6049 if (!CurContext->isDependentContext()) {
6050 // Finalize the clauses that need pre-built expressions for CodeGen.
6051 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006052 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006053 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006054 B.NumIterations, *this, CurScope,
6055 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006056 return StmtError();
6057 }
6058 }
6059
6060 getCurFunction()->setHasBranchProtectedScope();
6061 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6062 NestedLoopCount, Clauses, AStmt,
6063 B, DSAStack->isCancelRegion());
6064}
6065
Alexey Bataev95b64a92017-05-30 16:00:04 +00006066/// Check for existence of a map clause in the list of clauses.
6067static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6068 const OpenMPClauseKind K) {
6069 return llvm::any_of(
6070 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6071}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006072
Alexey Bataev95b64a92017-05-30 16:00:04 +00006073template <typename... Params>
6074static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6075 const Params... ClauseTypes) {
6076 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006077}
6078
Michael Wong65f367f2015-07-21 13:44:28 +00006079StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6080 Stmt *AStmt,
6081 SourceLocation StartLoc,
6082 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006083 if (!AStmt)
6084 return StmtError();
6085
6086 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6087
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006088 // OpenMP [2.10.1, Restrictions, p. 97]
6089 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006090 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6091 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6092 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006093 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006094 return StmtError();
6095 }
6096
Michael Wong65f367f2015-07-21 13:44:28 +00006097 getCurFunction()->setHasBranchProtectedScope();
6098
6099 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6100 AStmt);
6101}
6102
Samuel Antaodf67fc42016-01-19 19:15:56 +00006103StmtResult
6104Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6105 SourceLocation StartLoc,
6106 SourceLocation EndLoc) {
6107 // OpenMP [2.10.2, Restrictions, p. 99]
6108 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006109 if (!hasClauses(Clauses, OMPC_map)) {
6110 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6111 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006112 return StmtError();
6113 }
6114
6115 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6116 Clauses);
6117}
6118
Samuel Antao72590762016-01-19 20:04:50 +00006119StmtResult
6120Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6121 SourceLocation StartLoc,
6122 SourceLocation EndLoc) {
6123 // OpenMP [2.10.3, Restrictions, p. 102]
6124 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006125 if (!hasClauses(Clauses, OMPC_map)) {
6126 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6127 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006128 return StmtError();
6129 }
6130
6131 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6132}
6133
Samuel Antao686c70c2016-05-26 17:30:50 +00006134StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6135 SourceLocation StartLoc,
6136 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006137 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006138 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6139 return StmtError();
6140 }
6141 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6142}
6143
Alexey Bataev13314bf2014-10-09 04:18:56 +00006144StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6145 Stmt *AStmt, SourceLocation StartLoc,
6146 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006147 if (!AStmt)
6148 return StmtError();
6149
Alexey Bataev13314bf2014-10-09 04:18:56 +00006150 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6151 // 1.2.2 OpenMP Language Terminology
6152 // Structured block - An executable statement with a single entry at the
6153 // top and a single exit at the bottom.
6154 // The point of exit cannot be a branch out of the structured block.
6155 // longjmp() and throw() must not violate the entry/exit criteria.
6156 CS->getCapturedDecl()->setNothrow();
6157
6158 getCurFunction()->setHasBranchProtectedScope();
6159
6160 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6161}
6162
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006163StmtResult
6164Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6165 SourceLocation EndLoc,
6166 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006167 if (DSAStack->isParentNowaitRegion()) {
6168 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6169 return StmtError();
6170 }
6171 if (DSAStack->isParentOrderedRegion()) {
6172 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6173 return StmtError();
6174 }
6175 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6176 CancelRegion);
6177}
6178
Alexey Bataev87933c72015-09-18 08:07:34 +00006179StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6180 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006181 SourceLocation EndLoc,
6182 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006183 if (DSAStack->isParentNowaitRegion()) {
6184 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6185 return StmtError();
6186 }
6187 if (DSAStack->isParentOrderedRegion()) {
6188 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6189 return StmtError();
6190 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006191 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006192 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6193 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006194}
6195
Alexey Bataev382967a2015-12-08 12:06:20 +00006196static bool checkGrainsizeNumTasksClauses(Sema &S,
6197 ArrayRef<OMPClause *> Clauses) {
6198 OMPClause *PrevClause = nullptr;
6199 bool ErrorFound = false;
6200 for (auto *C : Clauses) {
6201 if (C->getClauseKind() == OMPC_grainsize ||
6202 C->getClauseKind() == OMPC_num_tasks) {
6203 if (!PrevClause)
6204 PrevClause = C;
6205 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6206 S.Diag(C->getLocStart(),
6207 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6208 << getOpenMPClauseName(C->getClauseKind())
6209 << getOpenMPClauseName(PrevClause->getClauseKind());
6210 S.Diag(PrevClause->getLocStart(),
6211 diag::note_omp_previous_grainsize_num_tasks)
6212 << getOpenMPClauseName(PrevClause->getClauseKind());
6213 ErrorFound = true;
6214 }
6215 }
6216 }
6217 return ErrorFound;
6218}
6219
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006220static bool checkReductionClauseWithNogroup(Sema &S,
6221 ArrayRef<OMPClause *> Clauses) {
6222 OMPClause *ReductionClause = nullptr;
6223 OMPClause *NogroupClause = nullptr;
6224 for (auto *C : Clauses) {
6225 if (C->getClauseKind() == OMPC_reduction) {
6226 ReductionClause = C;
6227 if (NogroupClause)
6228 break;
6229 continue;
6230 }
6231 if (C->getClauseKind() == OMPC_nogroup) {
6232 NogroupClause = C;
6233 if (ReductionClause)
6234 break;
6235 continue;
6236 }
6237 }
6238 if (ReductionClause && NogroupClause) {
6239 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6240 << SourceRange(NogroupClause->getLocStart(),
6241 NogroupClause->getLocEnd());
6242 return true;
6243 }
6244 return false;
6245}
6246
Alexey Bataev49f6e782015-12-01 04:18:41 +00006247StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6248 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6249 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006250 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006251 if (!AStmt)
6252 return StmtError();
6253
6254 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6255 OMPLoopDirective::HelperExprs B;
6256 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6257 // define the nested loops number.
6258 unsigned NestedLoopCount =
6259 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006260 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006261 VarsWithImplicitDSA, B);
6262 if (NestedLoopCount == 0)
6263 return StmtError();
6264
6265 assert((CurContext->isDependentContext() || B.builtAll()) &&
6266 "omp for loop exprs were not built");
6267
Alexey Bataev382967a2015-12-08 12:06:20 +00006268 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6269 // The grainsize clause and num_tasks clause are mutually exclusive and may
6270 // not appear on the same taskloop directive.
6271 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6272 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006273 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6274 // If a reduction clause is present on the taskloop directive, the nogroup
6275 // clause must not be specified.
6276 if (checkReductionClauseWithNogroup(*this, Clauses))
6277 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006278
Alexey Bataev49f6e782015-12-01 04:18:41 +00006279 getCurFunction()->setHasBranchProtectedScope();
6280 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6281 NestedLoopCount, Clauses, AStmt, B);
6282}
6283
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006284StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6285 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6286 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006287 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006288 if (!AStmt)
6289 return StmtError();
6290
6291 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6292 OMPLoopDirective::HelperExprs B;
6293 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6294 // define the nested loops number.
6295 unsigned NestedLoopCount =
6296 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6297 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6298 VarsWithImplicitDSA, B);
6299 if (NestedLoopCount == 0)
6300 return StmtError();
6301
6302 assert((CurContext->isDependentContext() || B.builtAll()) &&
6303 "omp for loop exprs were not built");
6304
Alexey Bataev5a3af132016-03-29 08:58:54 +00006305 if (!CurContext->isDependentContext()) {
6306 // Finalize the clauses that need pre-built expressions for CodeGen.
6307 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006308 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006309 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006310 B.NumIterations, *this, CurScope,
6311 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006312 return StmtError();
6313 }
6314 }
6315
Alexey Bataev382967a2015-12-08 12:06:20 +00006316 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6317 // The grainsize clause and num_tasks clause are mutually exclusive and may
6318 // not appear on the same taskloop directive.
6319 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6320 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006321 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6322 // If a reduction clause is present on the taskloop directive, the nogroup
6323 // clause must not be specified.
6324 if (checkReductionClauseWithNogroup(*this, Clauses))
6325 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006326
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006327 getCurFunction()->setHasBranchProtectedScope();
6328 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6329 NestedLoopCount, Clauses, AStmt, B);
6330}
6331
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006332StmtResult Sema::ActOnOpenMPDistributeDirective(
6333 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6334 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006335 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006336 if (!AStmt)
6337 return StmtError();
6338
6339 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6340 OMPLoopDirective::HelperExprs B;
6341 // In presence of clause 'collapse' with number of loops, it will
6342 // define the nested loops number.
6343 unsigned NestedLoopCount =
6344 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6345 nullptr /*ordered not a clause on distribute*/, AStmt,
6346 *this, *DSAStack, VarsWithImplicitDSA, B);
6347 if (NestedLoopCount == 0)
6348 return StmtError();
6349
6350 assert((CurContext->isDependentContext() || B.builtAll()) &&
6351 "omp for loop exprs were not built");
6352
6353 getCurFunction()->setHasBranchProtectedScope();
6354 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6355 NestedLoopCount, Clauses, AStmt, B);
6356}
6357
Carlo Bertolli9925f152016-06-27 14:55:37 +00006358StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6359 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6360 SourceLocation EndLoc,
6361 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6362 if (!AStmt)
6363 return StmtError();
6364
6365 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6366 // 1.2.2 OpenMP Language Terminology
6367 // Structured block - An executable statement with a single entry at the
6368 // top and a single exit at the bottom.
6369 // The point of exit cannot be a branch out of the structured block.
6370 // longjmp() and throw() must not violate the entry/exit criteria.
6371 CS->getCapturedDecl()->setNothrow();
6372
6373 OMPLoopDirective::HelperExprs B;
6374 // In presence of clause 'collapse' with number of loops, it will
6375 // define the nested loops number.
6376 unsigned NestedLoopCount = CheckOpenMPLoop(
6377 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6378 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6379 VarsWithImplicitDSA, B);
6380 if (NestedLoopCount == 0)
6381 return StmtError();
6382
6383 assert((CurContext->isDependentContext() || B.builtAll()) &&
6384 "omp for loop exprs were not built");
6385
6386 getCurFunction()->setHasBranchProtectedScope();
6387 return OMPDistributeParallelForDirective::Create(
6388 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6389}
6390
Kelvin Li4a39add2016-07-05 05:00:15 +00006391StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6392 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6393 SourceLocation EndLoc,
6394 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6395 if (!AStmt)
6396 return StmtError();
6397
6398 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6399 // 1.2.2 OpenMP Language Terminology
6400 // Structured block - An executable statement with a single entry at the
6401 // top and a single exit at the bottom.
6402 // The point of exit cannot be a branch out of the structured block.
6403 // longjmp() and throw() must not violate the entry/exit criteria.
6404 CS->getCapturedDecl()->setNothrow();
6405
6406 OMPLoopDirective::HelperExprs B;
6407 // In presence of clause 'collapse' with number of loops, it will
6408 // define the nested loops number.
6409 unsigned NestedLoopCount = CheckOpenMPLoop(
6410 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6411 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6412 VarsWithImplicitDSA, B);
6413 if (NestedLoopCount == 0)
6414 return StmtError();
6415
6416 assert((CurContext->isDependentContext() || B.builtAll()) &&
6417 "omp for loop exprs were not built");
6418
Kelvin Lic5609492016-07-15 04:39:07 +00006419 if (checkSimdlenSafelenSpecified(*this, Clauses))
6420 return StmtError();
6421
Kelvin Li4a39add2016-07-05 05:00:15 +00006422 getCurFunction()->setHasBranchProtectedScope();
6423 return OMPDistributeParallelForSimdDirective::Create(
6424 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6425}
6426
Kelvin Li787f3fc2016-07-06 04:45:38 +00006427StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6428 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6429 SourceLocation EndLoc,
6430 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6431 if (!AStmt)
6432 return StmtError();
6433
6434 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6435 // 1.2.2 OpenMP Language Terminology
6436 // Structured block - An executable statement with a single entry at the
6437 // top and a single exit at the bottom.
6438 // The point of exit cannot be a branch out of the structured block.
6439 // longjmp() and throw() must not violate the entry/exit criteria.
6440 CS->getCapturedDecl()->setNothrow();
6441
6442 OMPLoopDirective::HelperExprs B;
6443 // In presence of clause 'collapse' with number of loops, it will
6444 // define the nested loops number.
6445 unsigned NestedLoopCount =
6446 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6447 nullptr /*ordered not a clause on distribute*/, AStmt,
6448 *this, *DSAStack, VarsWithImplicitDSA, B);
6449 if (NestedLoopCount == 0)
6450 return StmtError();
6451
6452 assert((CurContext->isDependentContext() || B.builtAll()) &&
6453 "omp for loop exprs were not built");
6454
Kelvin Lic5609492016-07-15 04:39:07 +00006455 if (checkSimdlenSafelenSpecified(*this, Clauses))
6456 return StmtError();
6457
Kelvin Li787f3fc2016-07-06 04:45:38 +00006458 getCurFunction()->setHasBranchProtectedScope();
6459 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6460 NestedLoopCount, Clauses, AStmt, B);
6461}
6462
Kelvin Lia579b912016-07-14 02:54:56 +00006463StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6464 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6465 SourceLocation EndLoc,
6466 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6467 if (!AStmt)
6468 return StmtError();
6469
6470 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6471 // 1.2.2 OpenMP Language Terminology
6472 // Structured block - An executable statement with a single entry at the
6473 // top and a single exit at the bottom.
6474 // The point of exit cannot be a branch out of the structured block.
6475 // longjmp() and throw() must not violate the entry/exit criteria.
6476 CS->getCapturedDecl()->setNothrow();
6477
6478 OMPLoopDirective::HelperExprs B;
6479 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6480 // define the nested loops number.
6481 unsigned NestedLoopCount = CheckOpenMPLoop(
6482 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6483 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6484 VarsWithImplicitDSA, B);
6485 if (NestedLoopCount == 0)
6486 return StmtError();
6487
6488 assert((CurContext->isDependentContext() || B.builtAll()) &&
6489 "omp target parallel for simd loop exprs were not built");
6490
6491 if (!CurContext->isDependentContext()) {
6492 // Finalize the clauses that need pre-built expressions for CodeGen.
6493 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006494 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006495 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6496 B.NumIterations, *this, CurScope,
6497 DSAStack))
6498 return StmtError();
6499 }
6500 }
Kelvin Lic5609492016-07-15 04:39:07 +00006501 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006502 return StmtError();
6503
6504 getCurFunction()->setHasBranchProtectedScope();
6505 return OMPTargetParallelForSimdDirective::Create(
6506 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6507}
6508
Kelvin Li986330c2016-07-20 22:57:10 +00006509StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6510 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6511 SourceLocation EndLoc,
6512 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6513 if (!AStmt)
6514 return StmtError();
6515
6516 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6517 // 1.2.2 OpenMP Language Terminology
6518 // Structured block - An executable statement with a single entry at the
6519 // top and a single exit at the bottom.
6520 // The point of exit cannot be a branch out of the structured block.
6521 // longjmp() and throw() must not violate the entry/exit criteria.
6522 CS->getCapturedDecl()->setNothrow();
6523
6524 OMPLoopDirective::HelperExprs B;
6525 // In presence of clause 'collapse' with number of loops, it will define the
6526 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006527 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006528 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6529 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6530 VarsWithImplicitDSA, B);
6531 if (NestedLoopCount == 0)
6532 return StmtError();
6533
6534 assert((CurContext->isDependentContext() || B.builtAll()) &&
6535 "omp target simd loop exprs were not built");
6536
6537 if (!CurContext->isDependentContext()) {
6538 // Finalize the clauses that need pre-built expressions for CodeGen.
6539 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006540 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006541 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6542 B.NumIterations, *this, CurScope,
6543 DSAStack))
6544 return StmtError();
6545 }
6546 }
6547
6548 if (checkSimdlenSafelenSpecified(*this, Clauses))
6549 return StmtError();
6550
6551 getCurFunction()->setHasBranchProtectedScope();
6552 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6553 NestedLoopCount, Clauses, AStmt, B);
6554}
6555
Kelvin Li02532872016-08-05 14:37:37 +00006556StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6557 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6558 SourceLocation EndLoc,
6559 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6560 if (!AStmt)
6561 return StmtError();
6562
6563 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6564 // 1.2.2 OpenMP Language Terminology
6565 // Structured block - An executable statement with a single entry at the
6566 // top and a single exit at the bottom.
6567 // The point of exit cannot be a branch out of the structured block.
6568 // longjmp() and throw() must not violate the entry/exit criteria.
6569 CS->getCapturedDecl()->setNothrow();
6570
6571 OMPLoopDirective::HelperExprs B;
6572 // In presence of clause 'collapse' with number of loops, it will
6573 // define the nested loops number.
6574 unsigned NestedLoopCount =
6575 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6576 nullptr /*ordered not a clause on distribute*/, AStmt,
6577 *this, *DSAStack, VarsWithImplicitDSA, B);
6578 if (NestedLoopCount == 0)
6579 return StmtError();
6580
6581 assert((CurContext->isDependentContext() || B.builtAll()) &&
6582 "omp teams distribute loop exprs were not built");
6583
6584 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006585 return OMPTeamsDistributeDirective::Create(
6586 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006587}
6588
Kelvin Li4e325f72016-10-25 12:50:55 +00006589StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6590 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6591 SourceLocation EndLoc,
6592 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6593 if (!AStmt)
6594 return StmtError();
6595
6596 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6597 // 1.2.2 OpenMP Language Terminology
6598 // Structured block - An executable statement with a single entry at the
6599 // top and a single exit at the bottom.
6600 // The point of exit cannot be a branch out of the structured block.
6601 // longjmp() and throw() must not violate the entry/exit criteria.
6602 CS->getCapturedDecl()->setNothrow();
6603
6604 OMPLoopDirective::HelperExprs B;
6605 // In presence of clause 'collapse' with number of loops, it will
6606 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006607 unsigned NestedLoopCount = CheckOpenMPLoop(
6608 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6609 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6610 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006611
6612 if (NestedLoopCount == 0)
6613 return StmtError();
6614
6615 assert((CurContext->isDependentContext() || B.builtAll()) &&
6616 "omp teams distribute simd loop exprs were not built");
6617
6618 if (!CurContext->isDependentContext()) {
6619 // Finalize the clauses that need pre-built expressions for CodeGen.
6620 for (auto C : Clauses) {
6621 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6622 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6623 B.NumIterations, *this, CurScope,
6624 DSAStack))
6625 return StmtError();
6626 }
6627 }
6628
6629 if (checkSimdlenSafelenSpecified(*this, Clauses))
6630 return StmtError();
6631
6632 getCurFunction()->setHasBranchProtectedScope();
6633 return OMPTeamsDistributeSimdDirective::Create(
6634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6635}
6636
Kelvin Li579e41c2016-11-30 23:51:03 +00006637StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6638 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6639 SourceLocation EndLoc,
6640 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6641 if (!AStmt)
6642 return StmtError();
6643
6644 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6645 // 1.2.2 OpenMP Language Terminology
6646 // Structured block - An executable statement with a single entry at the
6647 // top and a single exit at the bottom.
6648 // The point of exit cannot be a branch out of the structured block.
6649 // longjmp() and throw() must not violate the entry/exit criteria.
6650 CS->getCapturedDecl()->setNothrow();
6651
6652 OMPLoopDirective::HelperExprs B;
6653 // In presence of clause 'collapse' with number of loops, it will
6654 // define the nested loops number.
6655 auto NestedLoopCount = CheckOpenMPLoop(
6656 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6657 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6658 VarsWithImplicitDSA, B);
6659
6660 if (NestedLoopCount == 0)
6661 return StmtError();
6662
6663 assert((CurContext->isDependentContext() || B.builtAll()) &&
6664 "omp for loop exprs were not built");
6665
6666 if (!CurContext->isDependentContext()) {
6667 // Finalize the clauses that need pre-built expressions for CodeGen.
6668 for (auto C : Clauses) {
6669 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6670 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6671 B.NumIterations, *this, CurScope,
6672 DSAStack))
6673 return StmtError();
6674 }
6675 }
6676
6677 if (checkSimdlenSafelenSpecified(*this, Clauses))
6678 return StmtError();
6679
6680 getCurFunction()->setHasBranchProtectedScope();
6681 return OMPTeamsDistributeParallelForSimdDirective::Create(
6682 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6683}
6684
Kelvin Li7ade93f2016-12-09 03:24:30 +00006685StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6686 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6687 SourceLocation EndLoc,
6688 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6689 if (!AStmt)
6690 return StmtError();
6691
6692 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6693 // 1.2.2 OpenMP Language Terminology
6694 // Structured block - An executable statement with a single entry at the
6695 // top and a single exit at the bottom.
6696 // The point of exit cannot be a branch out of the structured block.
6697 // longjmp() and throw() must not violate the entry/exit criteria.
6698 CS->getCapturedDecl()->setNothrow();
6699
6700 OMPLoopDirective::HelperExprs B;
6701 // In presence of clause 'collapse' with number of loops, it will
6702 // define the nested loops number.
6703 unsigned NestedLoopCount = CheckOpenMPLoop(
6704 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6705 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6706 VarsWithImplicitDSA, B);
6707
6708 if (NestedLoopCount == 0)
6709 return StmtError();
6710
6711 assert((CurContext->isDependentContext() || B.builtAll()) &&
6712 "omp for loop exprs were not built");
6713
6714 if (!CurContext->isDependentContext()) {
6715 // Finalize the clauses that need pre-built expressions for CodeGen.
6716 for (auto C : Clauses) {
6717 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6718 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6719 B.NumIterations, *this, CurScope,
6720 DSAStack))
6721 return StmtError();
6722 }
6723 }
6724
6725 getCurFunction()->setHasBranchProtectedScope();
6726 return OMPTeamsDistributeParallelForDirective::Create(
6727 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6728}
6729
Kelvin Libf594a52016-12-17 05:48:59 +00006730StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6731 Stmt *AStmt,
6732 SourceLocation StartLoc,
6733 SourceLocation EndLoc) {
6734 if (!AStmt)
6735 return StmtError();
6736
6737 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6738 // 1.2.2 OpenMP Language Terminology
6739 // Structured block - An executable statement with a single entry at the
6740 // top and a single exit at the bottom.
6741 // The point of exit cannot be a branch out of the structured block.
6742 // longjmp() and throw() must not violate the entry/exit criteria.
6743 CS->getCapturedDecl()->setNothrow();
6744
6745 getCurFunction()->setHasBranchProtectedScope();
6746
6747 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6748 AStmt);
6749}
6750
Kelvin Li83c451e2016-12-25 04:52:54 +00006751StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6752 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6753 SourceLocation EndLoc,
6754 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6755 if (!AStmt)
6756 return StmtError();
6757
6758 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6759 // 1.2.2 OpenMP Language Terminology
6760 // Structured block - An executable statement with a single entry at the
6761 // top and a single exit at the bottom.
6762 // The point of exit cannot be a branch out of the structured block.
6763 // longjmp() and throw() must not violate the entry/exit criteria.
6764 CS->getCapturedDecl()->setNothrow();
6765
6766 OMPLoopDirective::HelperExprs B;
6767 // In presence of clause 'collapse' with number of loops, it will
6768 // define the nested loops number.
6769 auto NestedLoopCount = CheckOpenMPLoop(
6770 OMPD_target_teams_distribute,
6771 getCollapseNumberExpr(Clauses),
6772 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6773 VarsWithImplicitDSA, B);
6774 if (NestedLoopCount == 0)
6775 return StmtError();
6776
6777 assert((CurContext->isDependentContext() || B.builtAll()) &&
6778 "omp target teams distribute loop exprs were not built");
6779
6780 getCurFunction()->setHasBranchProtectedScope();
6781 return OMPTargetTeamsDistributeDirective::Create(
6782 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6783}
6784
Kelvin Li80e8f562016-12-29 22:16:30 +00006785StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6786 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6787 SourceLocation EndLoc,
6788 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6789 if (!AStmt)
6790 return StmtError();
6791
6792 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6793 // 1.2.2 OpenMP Language Terminology
6794 // Structured block - An executable statement with a single entry at the
6795 // top and a single exit at the bottom.
6796 // The point of exit cannot be a branch out of the structured block.
6797 // longjmp() and throw() must not violate the entry/exit criteria.
6798 CS->getCapturedDecl()->setNothrow();
6799
6800 OMPLoopDirective::HelperExprs B;
6801 // In presence of clause 'collapse' with number of loops, it will
6802 // define the nested loops number.
6803 auto NestedLoopCount = CheckOpenMPLoop(
6804 OMPD_target_teams_distribute_parallel_for,
6805 getCollapseNumberExpr(Clauses),
6806 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6807 VarsWithImplicitDSA, B);
6808 if (NestedLoopCount == 0)
6809 return StmtError();
6810
6811 assert((CurContext->isDependentContext() || B.builtAll()) &&
6812 "omp target teams distribute parallel for loop exprs were not built");
6813
6814 if (!CurContext->isDependentContext()) {
6815 // Finalize the clauses that need pre-built expressions for CodeGen.
6816 for (auto C : Clauses) {
6817 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6818 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6819 B.NumIterations, *this, CurScope,
6820 DSAStack))
6821 return StmtError();
6822 }
6823 }
6824
6825 getCurFunction()->setHasBranchProtectedScope();
6826 return OMPTargetTeamsDistributeParallelForDirective::Create(
6827 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6828}
6829
Kelvin Li1851df52017-01-03 05:23:48 +00006830StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6831 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6832 SourceLocation EndLoc,
6833 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6834 if (!AStmt)
6835 return StmtError();
6836
6837 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6838 // 1.2.2 OpenMP Language Terminology
6839 // Structured block - An executable statement with a single entry at the
6840 // top and a single exit at the bottom.
6841 // The point of exit cannot be a branch out of the structured block.
6842 // longjmp() and throw() must not violate the entry/exit criteria.
6843 CS->getCapturedDecl()->setNothrow();
6844
6845 OMPLoopDirective::HelperExprs B;
6846 // In presence of clause 'collapse' with number of loops, it will
6847 // define the nested loops number.
6848 auto NestedLoopCount = CheckOpenMPLoop(
6849 OMPD_target_teams_distribute_parallel_for_simd,
6850 getCollapseNumberExpr(Clauses),
6851 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6852 VarsWithImplicitDSA, B);
6853 if (NestedLoopCount == 0)
6854 return StmtError();
6855
6856 assert((CurContext->isDependentContext() || B.builtAll()) &&
6857 "omp target teams distribute parallel for simd loop exprs were not "
6858 "built");
6859
6860 if (!CurContext->isDependentContext()) {
6861 // Finalize the clauses that need pre-built expressions for CodeGen.
6862 for (auto C : Clauses) {
6863 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6864 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6865 B.NumIterations, *this, CurScope,
6866 DSAStack))
6867 return StmtError();
6868 }
6869 }
6870
6871 getCurFunction()->setHasBranchProtectedScope();
6872 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6873 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6874}
6875
Kelvin Lida681182017-01-10 18:08:18 +00006876StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6877 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6878 SourceLocation EndLoc,
6879 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6880 if (!AStmt)
6881 return StmtError();
6882
6883 auto *CS = cast<CapturedStmt>(AStmt);
6884 // 1.2.2 OpenMP Language Terminology
6885 // Structured block - An executable statement with a single entry at the
6886 // top and a single exit at the bottom.
6887 // The point of exit cannot be a branch out of the structured block.
6888 // longjmp() and throw() must not violate the entry/exit criteria.
6889 CS->getCapturedDecl()->setNothrow();
6890
6891 OMPLoopDirective::HelperExprs B;
6892 // In presence of clause 'collapse' with number of loops, it will
6893 // define the nested loops number.
6894 auto NestedLoopCount = CheckOpenMPLoop(
6895 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6896 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6897 VarsWithImplicitDSA, B);
6898 if (NestedLoopCount == 0)
6899 return StmtError();
6900
6901 assert((CurContext->isDependentContext() || B.builtAll()) &&
6902 "omp target teams distribute simd loop exprs were not built");
6903
6904 getCurFunction()->setHasBranchProtectedScope();
6905 return OMPTargetTeamsDistributeSimdDirective::Create(
6906 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6907}
6908
Alexey Bataeved09d242014-05-28 05:53:51 +00006909OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006910 SourceLocation StartLoc,
6911 SourceLocation LParenLoc,
6912 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006913 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006914 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006915 case OMPC_final:
6916 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6917 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006918 case OMPC_num_threads:
6919 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6920 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006921 case OMPC_safelen:
6922 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6923 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006924 case OMPC_simdlen:
6925 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6926 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006927 case OMPC_collapse:
6928 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6929 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006930 case OMPC_ordered:
6931 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6932 break;
Michael Wonge710d542015-08-07 16:16:36 +00006933 case OMPC_device:
6934 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6935 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006936 case OMPC_num_teams:
6937 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6938 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006939 case OMPC_thread_limit:
6940 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6941 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006942 case OMPC_priority:
6943 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6944 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006945 case OMPC_grainsize:
6946 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6947 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006948 case OMPC_num_tasks:
6949 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6950 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006951 case OMPC_hint:
6952 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6953 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006954 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006955 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006956 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006957 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006958 case OMPC_private:
6959 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006960 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006961 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006962 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00006963 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00006964 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006965 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006966 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006967 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006968 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006969 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006970 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006971 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006972 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006973 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006974 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006975 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006976 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006977 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006978 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006979 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006980 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006981 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006982 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006983 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006984 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006985 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006986 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006987 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006988 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006989 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006990 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006991 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006992 llvm_unreachable("Clause is not allowed.");
6993 }
6994 return Res;
6995}
6996
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006997// An OpenMP directive such as 'target parallel' has two captured regions:
6998// for the 'target' and 'parallel' respectively. This function returns
6999// the region in which to capture expressions associated with a clause.
7000// A return value of OMPD_unknown signifies that the expression should not
7001// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007002static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7003 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7004 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007005 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7006
7007 switch (CKind) {
7008 case OMPC_if:
7009 switch (DKind) {
7010 case OMPD_target_parallel:
7011 // If this clause applies to the nested 'parallel' region, capture within
7012 // the 'target' region, otherwise do not capture.
7013 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7014 CaptureRegion = OMPD_target;
7015 break;
7016 case OMPD_cancel:
7017 case OMPD_parallel:
7018 case OMPD_parallel_sections:
7019 case OMPD_parallel_for:
7020 case OMPD_parallel_for_simd:
7021 case OMPD_target:
7022 case OMPD_target_simd:
7023 case OMPD_target_parallel_for:
7024 case OMPD_target_parallel_for_simd:
7025 case OMPD_target_teams:
7026 case OMPD_target_teams_distribute:
7027 case OMPD_target_teams_distribute_simd:
7028 case OMPD_target_teams_distribute_parallel_for:
7029 case OMPD_target_teams_distribute_parallel_for_simd:
7030 case OMPD_teams_distribute_parallel_for:
7031 case OMPD_teams_distribute_parallel_for_simd:
7032 case OMPD_distribute_parallel_for:
7033 case OMPD_distribute_parallel_for_simd:
7034 case OMPD_task:
7035 case OMPD_taskloop:
7036 case OMPD_taskloop_simd:
7037 case OMPD_target_data:
7038 case OMPD_target_enter_data:
7039 case OMPD_target_exit_data:
7040 case OMPD_target_update:
7041 // Do not capture if-clause expressions.
7042 break;
7043 case OMPD_threadprivate:
7044 case OMPD_taskyield:
7045 case OMPD_barrier:
7046 case OMPD_taskwait:
7047 case OMPD_cancellation_point:
7048 case OMPD_flush:
7049 case OMPD_declare_reduction:
7050 case OMPD_declare_simd:
7051 case OMPD_declare_target:
7052 case OMPD_end_declare_target:
7053 case OMPD_teams:
7054 case OMPD_simd:
7055 case OMPD_for:
7056 case OMPD_for_simd:
7057 case OMPD_sections:
7058 case OMPD_section:
7059 case OMPD_single:
7060 case OMPD_master:
7061 case OMPD_critical:
7062 case OMPD_taskgroup:
7063 case OMPD_distribute:
7064 case OMPD_ordered:
7065 case OMPD_atomic:
7066 case OMPD_distribute_simd:
7067 case OMPD_teams_distribute:
7068 case OMPD_teams_distribute_simd:
7069 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7070 case OMPD_unknown:
7071 llvm_unreachable("Unknown OpenMP directive");
7072 }
7073 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007074 case OMPC_num_threads:
7075 switch (DKind) {
7076 case OMPD_target_parallel:
7077 CaptureRegion = OMPD_target;
7078 break;
7079 case OMPD_cancel:
7080 case OMPD_parallel:
7081 case OMPD_parallel_sections:
7082 case OMPD_parallel_for:
7083 case OMPD_parallel_for_simd:
7084 case OMPD_target:
7085 case OMPD_target_simd:
7086 case OMPD_target_parallel_for:
7087 case OMPD_target_parallel_for_simd:
7088 case OMPD_target_teams:
7089 case OMPD_target_teams_distribute:
7090 case OMPD_target_teams_distribute_simd:
7091 case OMPD_target_teams_distribute_parallel_for:
7092 case OMPD_target_teams_distribute_parallel_for_simd:
7093 case OMPD_teams_distribute_parallel_for:
7094 case OMPD_teams_distribute_parallel_for_simd:
7095 case OMPD_distribute_parallel_for:
7096 case OMPD_distribute_parallel_for_simd:
7097 case OMPD_task:
7098 case OMPD_taskloop:
7099 case OMPD_taskloop_simd:
7100 case OMPD_target_data:
7101 case OMPD_target_enter_data:
7102 case OMPD_target_exit_data:
7103 case OMPD_target_update:
7104 // Do not capture num_threads-clause expressions.
7105 break;
7106 case OMPD_threadprivate:
7107 case OMPD_taskyield:
7108 case OMPD_barrier:
7109 case OMPD_taskwait:
7110 case OMPD_cancellation_point:
7111 case OMPD_flush:
7112 case OMPD_declare_reduction:
7113 case OMPD_declare_simd:
7114 case OMPD_declare_target:
7115 case OMPD_end_declare_target:
7116 case OMPD_teams:
7117 case OMPD_simd:
7118 case OMPD_for:
7119 case OMPD_for_simd:
7120 case OMPD_sections:
7121 case OMPD_section:
7122 case OMPD_single:
7123 case OMPD_master:
7124 case OMPD_critical:
7125 case OMPD_taskgroup:
7126 case OMPD_distribute:
7127 case OMPD_ordered:
7128 case OMPD_atomic:
7129 case OMPD_distribute_simd:
7130 case OMPD_teams_distribute:
7131 case OMPD_teams_distribute_simd:
7132 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7133 case OMPD_unknown:
7134 llvm_unreachable("Unknown OpenMP directive");
7135 }
7136 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007137 case OMPC_num_teams:
7138 switch (DKind) {
7139 case OMPD_target_teams:
7140 CaptureRegion = OMPD_target;
7141 break;
7142 case OMPD_cancel:
7143 case OMPD_parallel:
7144 case OMPD_parallel_sections:
7145 case OMPD_parallel_for:
7146 case OMPD_parallel_for_simd:
7147 case OMPD_target:
7148 case OMPD_target_simd:
7149 case OMPD_target_parallel:
7150 case OMPD_target_parallel_for:
7151 case OMPD_target_parallel_for_simd:
7152 case OMPD_target_teams_distribute:
7153 case OMPD_target_teams_distribute_simd:
7154 case OMPD_target_teams_distribute_parallel_for:
7155 case OMPD_target_teams_distribute_parallel_for_simd:
7156 case OMPD_teams_distribute_parallel_for:
7157 case OMPD_teams_distribute_parallel_for_simd:
7158 case OMPD_distribute_parallel_for:
7159 case OMPD_distribute_parallel_for_simd:
7160 case OMPD_task:
7161 case OMPD_taskloop:
7162 case OMPD_taskloop_simd:
7163 case OMPD_target_data:
7164 case OMPD_target_enter_data:
7165 case OMPD_target_exit_data:
7166 case OMPD_target_update:
7167 case OMPD_teams:
7168 case OMPD_teams_distribute:
7169 case OMPD_teams_distribute_simd:
7170 // Do not capture num_teams-clause expressions.
7171 break;
7172 case OMPD_threadprivate:
7173 case OMPD_taskyield:
7174 case OMPD_barrier:
7175 case OMPD_taskwait:
7176 case OMPD_cancellation_point:
7177 case OMPD_flush:
7178 case OMPD_declare_reduction:
7179 case OMPD_declare_simd:
7180 case OMPD_declare_target:
7181 case OMPD_end_declare_target:
7182 case OMPD_simd:
7183 case OMPD_for:
7184 case OMPD_for_simd:
7185 case OMPD_sections:
7186 case OMPD_section:
7187 case OMPD_single:
7188 case OMPD_master:
7189 case OMPD_critical:
7190 case OMPD_taskgroup:
7191 case OMPD_distribute:
7192 case OMPD_ordered:
7193 case OMPD_atomic:
7194 case OMPD_distribute_simd:
7195 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7196 case OMPD_unknown:
7197 llvm_unreachable("Unknown OpenMP directive");
7198 }
7199 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007200 case OMPC_thread_limit:
7201 switch (DKind) {
7202 case OMPD_target_teams:
7203 CaptureRegion = OMPD_target;
7204 break;
7205 case OMPD_cancel:
7206 case OMPD_parallel:
7207 case OMPD_parallel_sections:
7208 case OMPD_parallel_for:
7209 case OMPD_parallel_for_simd:
7210 case OMPD_target:
7211 case OMPD_target_simd:
7212 case OMPD_target_parallel:
7213 case OMPD_target_parallel_for:
7214 case OMPD_target_parallel_for_simd:
7215 case OMPD_target_teams_distribute:
7216 case OMPD_target_teams_distribute_simd:
7217 case OMPD_target_teams_distribute_parallel_for:
7218 case OMPD_target_teams_distribute_parallel_for_simd:
7219 case OMPD_teams_distribute_parallel_for:
7220 case OMPD_teams_distribute_parallel_for_simd:
7221 case OMPD_distribute_parallel_for:
7222 case OMPD_distribute_parallel_for_simd:
7223 case OMPD_task:
7224 case OMPD_taskloop:
7225 case OMPD_taskloop_simd:
7226 case OMPD_target_data:
7227 case OMPD_target_enter_data:
7228 case OMPD_target_exit_data:
7229 case OMPD_target_update:
7230 case OMPD_teams:
7231 case OMPD_teams_distribute:
7232 case OMPD_teams_distribute_simd:
7233 // Do not capture thread_limit-clause expressions.
7234 break;
7235 case OMPD_threadprivate:
7236 case OMPD_taskyield:
7237 case OMPD_barrier:
7238 case OMPD_taskwait:
7239 case OMPD_cancellation_point:
7240 case OMPD_flush:
7241 case OMPD_declare_reduction:
7242 case OMPD_declare_simd:
7243 case OMPD_declare_target:
7244 case OMPD_end_declare_target:
7245 case OMPD_simd:
7246 case OMPD_for:
7247 case OMPD_for_simd:
7248 case OMPD_sections:
7249 case OMPD_section:
7250 case OMPD_single:
7251 case OMPD_master:
7252 case OMPD_critical:
7253 case OMPD_taskgroup:
7254 case OMPD_distribute:
7255 case OMPD_ordered:
7256 case OMPD_atomic:
7257 case OMPD_distribute_simd:
7258 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7259 case OMPD_unknown:
7260 llvm_unreachable("Unknown OpenMP directive");
7261 }
7262 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007263 case OMPC_schedule:
7264 case OMPC_dist_schedule:
7265 case OMPC_firstprivate:
7266 case OMPC_lastprivate:
7267 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007268 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007269 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007270 case OMPC_linear:
7271 case OMPC_default:
7272 case OMPC_proc_bind:
7273 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007274 case OMPC_safelen:
7275 case OMPC_simdlen:
7276 case OMPC_collapse:
7277 case OMPC_private:
7278 case OMPC_shared:
7279 case OMPC_aligned:
7280 case OMPC_copyin:
7281 case OMPC_copyprivate:
7282 case OMPC_ordered:
7283 case OMPC_nowait:
7284 case OMPC_untied:
7285 case OMPC_mergeable:
7286 case OMPC_threadprivate:
7287 case OMPC_flush:
7288 case OMPC_read:
7289 case OMPC_write:
7290 case OMPC_update:
7291 case OMPC_capture:
7292 case OMPC_seq_cst:
7293 case OMPC_depend:
7294 case OMPC_device:
7295 case OMPC_threads:
7296 case OMPC_simd:
7297 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007298 case OMPC_priority:
7299 case OMPC_grainsize:
7300 case OMPC_nogroup:
7301 case OMPC_num_tasks:
7302 case OMPC_hint:
7303 case OMPC_defaultmap:
7304 case OMPC_unknown:
7305 case OMPC_uniform:
7306 case OMPC_to:
7307 case OMPC_from:
7308 case OMPC_use_device_ptr:
7309 case OMPC_is_device_ptr:
7310 llvm_unreachable("Unexpected OpenMP clause.");
7311 }
7312 return CaptureRegion;
7313}
7314
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007315OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7316 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007317 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007318 SourceLocation NameModifierLoc,
7319 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007320 SourceLocation EndLoc) {
7321 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007322 Stmt *HelperValStmt = nullptr;
7323 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007324 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7325 !Condition->isInstantiationDependent() &&
7326 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007327 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007328 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007329 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007330
Richard Smith03a4aa32016-06-23 19:02:52 +00007331 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007332
7333 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7334 CaptureRegion =
7335 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7336 if (CaptureRegion != OMPD_unknown) {
7337 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7338 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7339 HelperValStmt = buildPreInits(Context, Captures);
7340 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007341 }
7342
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007343 return new (Context)
7344 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7345 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007346}
7347
Alexey Bataev3778b602014-07-17 07:32:53 +00007348OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7349 SourceLocation StartLoc,
7350 SourceLocation LParenLoc,
7351 SourceLocation EndLoc) {
7352 Expr *ValExpr = Condition;
7353 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7354 !Condition->isInstantiationDependent() &&
7355 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007356 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007357 if (Val.isInvalid())
7358 return nullptr;
7359
Richard Smith03a4aa32016-06-23 19:02:52 +00007360 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007361 }
7362
7363 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7364}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007365ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7366 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007367 if (!Op)
7368 return ExprError();
7369
7370 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7371 public:
7372 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007373 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007374 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7375 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007376 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7377 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007378 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7379 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007380 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7381 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007382 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7383 QualType T,
7384 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007385 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7386 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007387 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7388 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007389 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007390 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007391 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007392 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7393 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007394 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7395 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007396 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7397 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007398 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007399 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007400 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007401 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7402 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007403 llvm_unreachable("conversion functions are permitted");
7404 }
7405 } ConvertDiagnoser;
7406 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7407}
7408
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007409static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007410 OpenMPClauseKind CKind,
7411 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007412 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7413 !ValExpr->isInstantiationDependent()) {
7414 SourceLocation Loc = ValExpr->getExprLoc();
7415 ExprResult Value =
7416 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7417 if (Value.isInvalid())
7418 return false;
7419
7420 ValExpr = Value.get();
7421 // The expression must evaluate to a non-negative integer value.
7422 llvm::APSInt Result;
7423 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007424 Result.isSigned() &&
7425 !((!StrictlyPositive && Result.isNonNegative()) ||
7426 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007427 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007428 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7429 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007430 return false;
7431 }
7432 }
7433 return true;
7434}
7435
Alexey Bataev568a8332014-03-06 06:15:19 +00007436OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7437 SourceLocation StartLoc,
7438 SourceLocation LParenLoc,
7439 SourceLocation EndLoc) {
7440 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007441 Stmt *HelperValStmt = nullptr;
7442 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007443
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007444 // OpenMP [2.5, Restrictions]
7445 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007446 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7447 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007448 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007449
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007450 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7451 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7452 if (CaptureRegion != OMPD_unknown) {
7453 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7454 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7455 HelperValStmt = buildPreInits(Context, Captures);
7456 }
7457
7458 return new (Context) OMPNumThreadsClause(
7459 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007460}
7461
Alexey Bataev62c87d22014-03-21 04:51:18 +00007462ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007463 OpenMPClauseKind CKind,
7464 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007465 if (!E)
7466 return ExprError();
7467 if (E->isValueDependent() || E->isTypeDependent() ||
7468 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007469 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007470 llvm::APSInt Result;
7471 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7472 if (ICE.isInvalid())
7473 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007474 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7475 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007476 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007477 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7478 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007479 return ExprError();
7480 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007481 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7482 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7483 << E->getSourceRange();
7484 return ExprError();
7485 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007486 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7487 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007488 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007489 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007490 return ICE;
7491}
7492
7493OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7494 SourceLocation LParenLoc,
7495 SourceLocation EndLoc) {
7496 // OpenMP [2.8.1, simd construct, Description]
7497 // The parameter of the safelen clause must be a constant
7498 // positive integer expression.
7499 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7500 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007501 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007502 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007503 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007504}
7505
Alexey Bataev66b15b52015-08-21 11:14:16 +00007506OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7507 SourceLocation LParenLoc,
7508 SourceLocation EndLoc) {
7509 // OpenMP [2.8.1, simd construct, Description]
7510 // The parameter of the simdlen clause must be a constant
7511 // positive integer expression.
7512 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7513 if (Simdlen.isInvalid())
7514 return nullptr;
7515 return new (Context)
7516 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7517}
7518
Alexander Musman64d33f12014-06-04 07:53:32 +00007519OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7520 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007521 SourceLocation LParenLoc,
7522 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007523 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007524 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007525 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007526 // The parameter of the collapse clause must be a constant
7527 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007528 ExprResult NumForLoopsResult =
7529 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7530 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007531 return nullptr;
7532 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007533 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007534}
7535
Alexey Bataev10e775f2015-07-30 11:36:16 +00007536OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7537 SourceLocation EndLoc,
7538 SourceLocation LParenLoc,
7539 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007540 // OpenMP [2.7.1, loop construct, Description]
7541 // OpenMP [2.8.1, simd construct, Description]
7542 // OpenMP [2.9.6, distribute construct, Description]
7543 // The parameter of the ordered clause must be a constant
7544 // positive integer expression if any.
7545 if (NumForLoops && LParenLoc.isValid()) {
7546 ExprResult NumForLoopsResult =
7547 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7548 if (NumForLoopsResult.isInvalid())
7549 return nullptr;
7550 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007551 } else
7552 NumForLoops = nullptr;
7553 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007554 return new (Context)
7555 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7556}
7557
Alexey Bataeved09d242014-05-28 05:53:51 +00007558OMPClause *Sema::ActOnOpenMPSimpleClause(
7559 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7560 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007561 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007562 switch (Kind) {
7563 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007564 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007565 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7566 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007567 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007568 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007569 Res = ActOnOpenMPProcBindClause(
7570 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7571 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007572 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007573 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007574 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007575 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007576 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007577 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007578 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007579 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007580 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007581 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007582 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007583 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007584 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007585 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007586 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007587 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007588 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007589 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007590 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007591 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007592 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007593 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007594 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007595 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007596 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007597 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007598 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007599 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007600 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007601 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007602 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007603 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007604 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007605 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007606 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007607 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007608 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007609 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007610 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007611 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007612 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007613 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007614 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007615 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007616 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007617 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007618 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007619 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007620 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007621 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007622 llvm_unreachable("Clause is not allowed.");
7623 }
7624 return Res;
7625}
7626
Alexey Bataev6402bca2015-12-28 07:25:51 +00007627static std::string
7628getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7629 ArrayRef<unsigned> Exclude = llvm::None) {
7630 std::string Values;
7631 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7632 unsigned Skipped = Exclude.size();
7633 auto S = Exclude.begin(), E = Exclude.end();
7634 for (unsigned i = First; i < Last; ++i) {
7635 if (std::find(S, E, i) != E) {
7636 --Skipped;
7637 continue;
7638 }
7639 Values += "'";
7640 Values += getOpenMPSimpleClauseTypeName(K, i);
7641 Values += "'";
7642 if (i == Bound - Skipped)
7643 Values += " or ";
7644 else if (i != Bound + 1 - Skipped)
7645 Values += ", ";
7646 }
7647 return Values;
7648}
7649
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007650OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7651 SourceLocation KindKwLoc,
7652 SourceLocation StartLoc,
7653 SourceLocation LParenLoc,
7654 SourceLocation EndLoc) {
7655 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007656 static_assert(OMPC_DEFAULT_unknown > 0,
7657 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007658 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007659 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7660 /*Last=*/OMPC_DEFAULT_unknown)
7661 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007662 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007663 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007664 switch (Kind) {
7665 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007666 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007667 break;
7668 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007669 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007670 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007671 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007672 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007673 break;
7674 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007675 return new (Context)
7676 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007677}
7678
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007679OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7680 SourceLocation KindKwLoc,
7681 SourceLocation StartLoc,
7682 SourceLocation LParenLoc,
7683 SourceLocation EndLoc) {
7684 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007685 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007686 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7687 /*Last=*/OMPC_PROC_BIND_unknown)
7688 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007689 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007690 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007691 return new (Context)
7692 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007693}
7694
Alexey Bataev56dafe82014-06-20 07:16:17 +00007695OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007696 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007697 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007698 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007699 SourceLocation EndLoc) {
7700 OMPClause *Res = nullptr;
7701 switch (Kind) {
7702 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007703 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7704 assert(Argument.size() == NumberOfElements &&
7705 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007706 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007707 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7708 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7709 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7710 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7711 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007712 break;
7713 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007714 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7715 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7716 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7717 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007718 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007719 case OMPC_dist_schedule:
7720 Res = ActOnOpenMPDistScheduleClause(
7721 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7722 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7723 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007724 case OMPC_defaultmap:
7725 enum { Modifier, DefaultmapKind };
7726 Res = ActOnOpenMPDefaultmapClause(
7727 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7728 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007729 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7730 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007731 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007732 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007733 case OMPC_num_threads:
7734 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007735 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007736 case OMPC_collapse:
7737 case OMPC_default:
7738 case OMPC_proc_bind:
7739 case OMPC_private:
7740 case OMPC_firstprivate:
7741 case OMPC_lastprivate:
7742 case OMPC_shared:
7743 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007744 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007745 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007746 case OMPC_linear:
7747 case OMPC_aligned:
7748 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007749 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007750 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007751 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007752 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007753 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007754 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007755 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007756 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007757 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007758 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007759 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007760 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007761 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007762 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007763 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007764 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007765 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007766 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007767 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007768 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007769 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007770 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007771 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007772 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007773 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007774 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007775 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007776 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007777 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007778 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007779 llvm_unreachable("Clause is not allowed.");
7780 }
7781 return Res;
7782}
7783
Alexey Bataev6402bca2015-12-28 07:25:51 +00007784static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7785 OpenMPScheduleClauseModifier M2,
7786 SourceLocation M1Loc, SourceLocation M2Loc) {
7787 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7788 SmallVector<unsigned, 2> Excluded;
7789 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7790 Excluded.push_back(M2);
7791 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7792 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7793 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7794 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7795 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7796 << getListOfPossibleValues(OMPC_schedule,
7797 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7798 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7799 Excluded)
7800 << getOpenMPClauseName(OMPC_schedule);
7801 return true;
7802 }
7803 return false;
7804}
7805
Alexey Bataev56dafe82014-06-20 07:16:17 +00007806OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007807 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007808 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007809 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7810 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7811 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7812 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7813 return nullptr;
7814 // OpenMP, 2.7.1, Loop Construct, Restrictions
7815 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7816 // but not both.
7817 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7818 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7819 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7820 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7821 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7822 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7823 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7824 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7825 return nullptr;
7826 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007827 if (Kind == OMPC_SCHEDULE_unknown) {
7828 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007829 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7830 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7831 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7832 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7833 Exclude);
7834 } else {
7835 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7836 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007837 }
7838 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7839 << Values << getOpenMPClauseName(OMPC_schedule);
7840 return nullptr;
7841 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007842 // OpenMP, 2.7.1, Loop Construct, Restrictions
7843 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7844 // schedule(guided).
7845 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7846 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7847 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7848 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7849 diag::err_omp_schedule_nonmonotonic_static);
7850 return nullptr;
7851 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007852 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007853 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007854 if (ChunkSize) {
7855 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7856 !ChunkSize->isInstantiationDependent() &&
7857 !ChunkSize->containsUnexpandedParameterPack()) {
7858 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7859 ExprResult Val =
7860 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7861 if (Val.isInvalid())
7862 return nullptr;
7863
7864 ValExpr = Val.get();
7865
7866 // OpenMP [2.7.1, Restrictions]
7867 // chunk_size must be a loop invariant integer expression with a positive
7868 // value.
7869 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007870 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7871 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7872 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007873 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007874 return nullptr;
7875 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007876 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7877 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007878 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7879 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7880 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007881 }
7882 }
7883 }
7884
Alexey Bataev6402bca2015-12-28 07:25:51 +00007885 return new (Context)
7886 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007887 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007888}
7889
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007890OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7891 SourceLocation StartLoc,
7892 SourceLocation EndLoc) {
7893 OMPClause *Res = nullptr;
7894 switch (Kind) {
7895 case OMPC_ordered:
7896 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7897 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007898 case OMPC_nowait:
7899 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7900 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007901 case OMPC_untied:
7902 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7903 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007904 case OMPC_mergeable:
7905 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7906 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007907 case OMPC_read:
7908 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7909 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007910 case OMPC_write:
7911 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7912 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007913 case OMPC_update:
7914 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7915 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007916 case OMPC_capture:
7917 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7918 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007919 case OMPC_seq_cst:
7920 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7921 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007922 case OMPC_threads:
7923 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7924 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007925 case OMPC_simd:
7926 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7927 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007928 case OMPC_nogroup:
7929 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7930 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007931 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007932 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007933 case OMPC_num_threads:
7934 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007935 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007936 case OMPC_collapse:
7937 case OMPC_schedule:
7938 case OMPC_private:
7939 case OMPC_firstprivate:
7940 case OMPC_lastprivate:
7941 case OMPC_shared:
7942 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007943 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007944 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007945 case OMPC_linear:
7946 case OMPC_aligned:
7947 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007948 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007949 case OMPC_default:
7950 case OMPC_proc_bind:
7951 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007952 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007953 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007954 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007955 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007956 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007957 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007958 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007959 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007960 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007961 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007962 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007963 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007964 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007965 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007966 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007967 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007968 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007969 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007970 llvm_unreachable("Clause is not allowed.");
7971 }
7972 return Res;
7973}
7974
Alexey Bataev236070f2014-06-20 11:19:47 +00007975OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7976 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007977 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007978 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7979}
7980
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007981OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7982 SourceLocation EndLoc) {
7983 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7984}
7985
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007986OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7987 SourceLocation EndLoc) {
7988 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7989}
7990
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007991OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7992 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007993 return new (Context) OMPReadClause(StartLoc, EndLoc);
7994}
7995
Alexey Bataevdea47612014-07-23 07:46:59 +00007996OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7997 SourceLocation EndLoc) {
7998 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7999}
8000
Alexey Bataev67a4f222014-07-23 10:25:33 +00008001OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8002 SourceLocation EndLoc) {
8003 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8004}
8005
Alexey Bataev459dec02014-07-24 06:46:57 +00008006OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8007 SourceLocation EndLoc) {
8008 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8009}
8010
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008011OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8012 SourceLocation EndLoc) {
8013 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8014}
8015
Alexey Bataev346265e2015-09-25 10:37:12 +00008016OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8017 SourceLocation EndLoc) {
8018 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8019}
8020
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008021OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8022 SourceLocation EndLoc) {
8023 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8024}
8025
Alexey Bataevb825de12015-12-07 10:51:44 +00008026OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8027 SourceLocation EndLoc) {
8028 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8029}
8030
Alexey Bataevc5e02582014-06-16 07:08:35 +00008031OMPClause *Sema::ActOnOpenMPVarListClause(
8032 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8033 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8034 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008035 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008036 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8037 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8038 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008039 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008040 switch (Kind) {
8041 case OMPC_private:
8042 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8043 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008044 case OMPC_firstprivate:
8045 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8046 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008047 case OMPC_lastprivate:
8048 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8049 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008050 case OMPC_shared:
8051 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8052 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008053 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008054 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8055 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008056 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008057 case OMPC_task_reduction:
8058 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8059 EndLoc, ReductionIdScopeSpec,
8060 ReductionId);
8061 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008062 case OMPC_in_reduction:
8063 Res =
8064 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8065 EndLoc, ReductionIdScopeSpec, ReductionId);
8066 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008067 case OMPC_linear:
8068 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008069 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008070 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008071 case OMPC_aligned:
8072 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8073 ColonLoc, EndLoc);
8074 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008075 case OMPC_copyin:
8076 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8077 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008078 case OMPC_copyprivate:
8079 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8080 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008081 case OMPC_flush:
8082 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8083 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008084 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008085 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008086 StartLoc, LParenLoc, EndLoc);
8087 break;
8088 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008089 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8090 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8091 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008092 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008093 case OMPC_to:
8094 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8095 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008096 case OMPC_from:
8097 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8098 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008099 case OMPC_use_device_ptr:
8100 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8101 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008102 case OMPC_is_device_ptr:
8103 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8104 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008105 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008106 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008107 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008108 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008109 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008110 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008111 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008112 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008113 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008114 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008115 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008116 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008117 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008118 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008119 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008120 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008121 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008122 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008123 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008124 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008125 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008126 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008127 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008128 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008129 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008130 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008131 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008132 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008133 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008134 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008135 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008136 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008137 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008138 llvm_unreachable("Clause is not allowed.");
8139 }
8140 return Res;
8141}
8142
Alexey Bataev90c228f2016-02-08 09:29:13 +00008143ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008144 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008145 ExprResult Res = BuildDeclRefExpr(
8146 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8147 if (!Res.isUsable())
8148 return ExprError();
8149 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8150 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8151 if (!Res.isUsable())
8152 return ExprError();
8153 }
8154 if (VK != VK_LValue && Res.get()->isGLValue()) {
8155 Res = DefaultLvalueConversion(Res.get());
8156 if (!Res.isUsable())
8157 return ExprError();
8158 }
8159 return Res;
8160}
8161
Alexey Bataev60da77e2016-02-29 05:54:20 +00008162static std::pair<ValueDecl *, bool>
8163getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8164 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008165 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8166 RefExpr->containsUnexpandedParameterPack())
8167 return std::make_pair(nullptr, true);
8168
Alexey Bataevd985eda2016-02-10 11:29:16 +00008169 // OpenMP [3.1, C/C++]
8170 // A list item is a variable name.
8171 // OpenMP [2.9.3.3, Restrictions, p.1]
8172 // A variable that is part of another variable (as an array or
8173 // structure element) cannot appear in a private clause.
8174 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008175 enum {
8176 NoArrayExpr = -1,
8177 ArraySubscript = 0,
8178 OMPArraySection = 1
8179 } IsArrayExpr = NoArrayExpr;
8180 if (AllowArraySection) {
8181 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8182 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8183 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8184 Base = TempASE->getBase()->IgnoreParenImpCasts();
8185 RefExpr = Base;
8186 IsArrayExpr = ArraySubscript;
8187 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8188 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8189 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8190 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8191 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8192 Base = TempASE->getBase()->IgnoreParenImpCasts();
8193 RefExpr = Base;
8194 IsArrayExpr = OMPArraySection;
8195 }
8196 }
8197 ELoc = RefExpr->getExprLoc();
8198 ERange = RefExpr->getSourceRange();
8199 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008200 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8201 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8202 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8203 (S.getCurrentThisType().isNull() || !ME ||
8204 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8205 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008206 if (IsArrayExpr != NoArrayExpr)
8207 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8208 << ERange;
8209 else {
8210 S.Diag(ELoc,
8211 AllowArraySection
8212 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8213 : diag::err_omp_expected_var_name_member_expr)
8214 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8215 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008216 return std::make_pair(nullptr, false);
8217 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008218 return std::make_pair(
8219 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008220}
8221
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008222OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8223 SourceLocation StartLoc,
8224 SourceLocation LParenLoc,
8225 SourceLocation EndLoc) {
8226 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008227 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008228 for (auto &RefExpr : VarList) {
8229 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008230 SourceLocation ELoc;
8231 SourceRange ERange;
8232 Expr *SimpleRefExpr = RefExpr;
8233 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008234 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008235 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008236 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008237 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008238 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008239 ValueDecl *D = Res.first;
8240 if (!D)
8241 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008242
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008243 QualType Type = D->getType();
8244 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008245
8246 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8247 // A variable that appears in a private clause must not have an incomplete
8248 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008249 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008250 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008251 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008252
Alexey Bataev758e55e2013-09-06 18:03:48 +00008253 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8254 // in a Construct]
8255 // Variables with the predetermined data-sharing attributes may not be
8256 // listed in data-sharing attributes clauses, except for the cases
8257 // listed below. For these exceptions only, listing a predetermined
8258 // variable in a data-sharing attribute clause is allowed and overrides
8259 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008260 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008261 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008262 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8263 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008264 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008265 continue;
8266 }
8267
Kelvin Libf594a52016-12-17 05:48:59 +00008268 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008269 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008270 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008271 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008272 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8273 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008274 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008275 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008276 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008277 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008278 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008280 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008281 continue;
8282 }
8283
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008284 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8285 // A list item cannot appear in both a map clause and a data-sharing
8286 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008287 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008288 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008289 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008290 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008291 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008292 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008293 CurrDir == OMPD_target_parallel_for_simd ||
8294 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008295 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008296 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008297 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008298 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8299 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8300 ConflictKind = WhereFoundClauseKind;
8301 return true;
8302 })) {
8303 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008304 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008305 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008306 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008307 ReportOriginalDSA(*this, DSAStack, D, DVar);
8308 continue;
8309 }
8310 }
8311
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008312 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8313 // A variable of class type (or array thereof) that appears in a private
8314 // clause requires an accessible, unambiguous default constructor for the
8315 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008316 // Generate helper private variable and initialize it with the default
8317 // value. The address of the original variable is replaced by the address of
8318 // the new private variable in CodeGen. This new variable is not added to
8319 // IdResolver, so the code in the OpenMP region uses original variable for
8320 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008321 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008322 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8323 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008324 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008325 if (VDPrivate->isInvalidDecl())
8326 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008327 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008328 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008329
Alexey Bataev90c228f2016-02-08 09:29:13 +00008330 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008331 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008332 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008333 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008334 Vars.push_back((VD || CurContext->isDependentContext())
8335 ? RefExpr->IgnoreParens()
8336 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008337 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008338 }
8339
Alexey Bataeved09d242014-05-28 05:53:51 +00008340 if (Vars.empty())
8341 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008342
Alexey Bataev03b340a2014-10-21 03:16:40 +00008343 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8344 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008345}
8346
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008347namespace {
8348class DiagsUninitializedSeveretyRAII {
8349private:
8350 DiagnosticsEngine &Diags;
8351 SourceLocation SavedLoc;
8352 bool IsIgnored;
8353
8354public:
8355 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8356 bool IsIgnored)
8357 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8358 if (!IsIgnored) {
8359 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8360 /*Map*/ diag::Severity::Ignored, Loc);
8361 }
8362 }
8363 ~DiagsUninitializedSeveretyRAII() {
8364 if (!IsIgnored)
8365 Diags.popMappings(SavedLoc);
8366 }
8367};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008368}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008369
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008370OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8371 SourceLocation StartLoc,
8372 SourceLocation LParenLoc,
8373 SourceLocation EndLoc) {
8374 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008375 SmallVector<Expr *, 8> PrivateCopies;
8376 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008377 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008378 bool IsImplicitClause =
8379 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8380 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8381
Alexey Bataeved09d242014-05-28 05:53:51 +00008382 for (auto &RefExpr : VarList) {
8383 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008384 SourceLocation ELoc;
8385 SourceRange ERange;
8386 Expr *SimpleRefExpr = RefExpr;
8387 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008388 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008389 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008390 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008391 PrivateCopies.push_back(nullptr);
8392 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008393 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008394 ValueDecl *D = Res.first;
8395 if (!D)
8396 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008397
Alexey Bataev60da77e2016-02-29 05:54:20 +00008398 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008399 QualType Type = D->getType();
8400 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008401
8402 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8403 // A variable that appears in a private clause must not have an incomplete
8404 // type or a reference type.
8405 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008406 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008407 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008408 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008409
8410 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8411 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008412 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008413 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008414 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008415
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008416 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008417 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008418 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008419 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008420 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008421 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008422 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008423 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8424 // A list item that specifies a given variable may not appear in more
8425 // than one clause on the same directive, except that a variable may be
8426 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008427 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8428 // A list item may appear in a firstprivate or lastprivate clause but not
8429 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008430 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008431 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8432 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008433 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008434 << getOpenMPClauseName(DVar.CKind)
8435 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008436 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008437 continue;
8438 }
8439
8440 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8441 // in a Construct]
8442 // Variables with the predetermined data-sharing attributes may not be
8443 // listed in data-sharing attributes clauses, except for the cases
8444 // listed below. For these exceptions only, listing a predetermined
8445 // variable in a data-sharing attribute clause is allowed and overrides
8446 // the variable's predetermined data-sharing attributes.
8447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8448 // in a Construct, C/C++, p.2]
8449 // Variables with const-qualified type having no mutable member may be
8450 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008451 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008452 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8453 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008454 << getOpenMPClauseName(DVar.CKind)
8455 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008456 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008457 continue;
8458 }
8459
8460 // OpenMP [2.9.3.4, Restrictions, p.2]
8461 // A list item that is private within a parallel region must not appear
8462 // in a firstprivate clause on a worksharing construct if any of the
8463 // worksharing regions arising from the worksharing construct ever bind
8464 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008465 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8466 // A list item that is private within a teams region must not appear in a
8467 // firstprivate clause on a distribute construct if any of the distribute
8468 // regions arising from the distribute construct ever bind to any of the
8469 // teams regions arising from the teams construct.
8470 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8471 // A list item that appears in a reduction clause of a teams construct
8472 // must not appear in a firstprivate clause on a distribute construct if
8473 // any of the distribute regions arising from the distribute construct
8474 // ever bind to any of the teams regions arising from the teams construct.
8475 if ((isOpenMPWorksharingDirective(CurrDir) ||
8476 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008477 !isOpenMPParallelDirective(CurrDir) &&
8478 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008479 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008480 if (DVar.CKind != OMPC_shared &&
8481 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008482 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008483 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008484 Diag(ELoc, diag::err_omp_required_access)
8485 << getOpenMPClauseName(OMPC_firstprivate)
8486 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008487 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008488 continue;
8489 }
8490 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008491 // OpenMP [2.9.3.4, Restrictions, p.3]
8492 // A list item that appears in a reduction clause of a parallel construct
8493 // must not appear in a firstprivate clause on a worksharing or task
8494 // construct if any of the worksharing or task regions arising from the
8495 // worksharing or task construct ever bind to any of the parallel regions
8496 // arising from the parallel construct.
8497 // OpenMP [2.9.3.4, Restrictions, p.4]
8498 // A list item that appears in a reduction clause in worksharing
8499 // construct must not appear in a firstprivate clause in a task construct
8500 // encountered during execution of any of the worksharing regions arising
8501 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008502 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008503 DVar = DSAStack->hasInnermostDSA(
8504 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8505 [](OpenMPDirectiveKind K) -> bool {
8506 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008507 isOpenMPWorksharingDirective(K) ||
8508 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008509 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008510 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008511 if (DVar.CKind == OMPC_reduction &&
8512 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008513 isOpenMPWorksharingDirective(DVar.DKind) ||
8514 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008515 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8516 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008517 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008518 continue;
8519 }
8520 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008521
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008522 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8523 // A list item cannot appear in both a map clause and a data-sharing
8524 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008525 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008526 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008527 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008528 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008529 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008530 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008531 CurrDir == OMPD_target_parallel_for_simd ||
8532 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008533 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008534 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008535 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008536 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8537 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8538 ConflictKind = WhereFoundClauseKind;
8539 return true;
8540 })) {
8541 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008542 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008543 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008544 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8545 ReportOriginalDSA(*this, DSAStack, D, DVar);
8546 continue;
8547 }
8548 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008549 }
8550
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008551 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008552 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008553 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008554 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8555 << getOpenMPClauseName(OMPC_firstprivate) << Type
8556 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8557 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008558 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008559 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008560 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008561 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008562 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008563 continue;
8564 }
8565
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008566 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008567 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8568 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008569 // Generate helper private variable and initialize it with the value of the
8570 // original variable. The address of the original variable is replaced by
8571 // the address of the new private variable in the CodeGen. This new variable
8572 // is not added to IdResolver, so the code in the OpenMP region uses
8573 // original variable for proper diagnostics and variable capturing.
8574 Expr *VDInitRefExpr = nullptr;
8575 // For arrays generate initializer for single element and replace it by the
8576 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008577 if (Type->isArrayType()) {
8578 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008579 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008580 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008581 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008582 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008583 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008584 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008585 InitializedEntity Entity =
8586 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008587 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8588
8589 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8590 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8591 if (Result.isInvalid())
8592 VDPrivate->setInvalidDecl();
8593 else
8594 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008595 // Remove temp variable declaration.
8596 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008597 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008598 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8599 ".firstprivate.temp");
8600 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8601 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008602 AddInitializerToDecl(VDPrivate,
8603 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008604 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008605 }
8606 if (VDPrivate->isInvalidDecl()) {
8607 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008608 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008609 diag::note_omp_task_predetermined_firstprivate_here);
8610 }
8611 continue;
8612 }
8613 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008614 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008615 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8616 RefExpr->getExprLoc());
8617 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008618 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008619 if (TopDVar.CKind == OMPC_lastprivate)
8620 Ref = TopDVar.PrivateCopy;
8621 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008622 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008623 if (!IsOpenMPCapturedDecl(D))
8624 ExprCaptures.push_back(Ref->getDecl());
8625 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008626 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008627 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008628 Vars.push_back((VD || CurContext->isDependentContext())
8629 ? RefExpr->IgnoreParens()
8630 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008631 PrivateCopies.push_back(VDPrivateRefExpr);
8632 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008633 }
8634
Alexey Bataeved09d242014-05-28 05:53:51 +00008635 if (Vars.empty())
8636 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008637
8638 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008639 Vars, PrivateCopies, Inits,
8640 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008641}
8642
Alexander Musman1bb328c2014-06-04 13:06:39 +00008643OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8644 SourceLocation StartLoc,
8645 SourceLocation LParenLoc,
8646 SourceLocation EndLoc) {
8647 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008648 SmallVector<Expr *, 8> SrcExprs;
8649 SmallVector<Expr *, 8> DstExprs;
8650 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008651 SmallVector<Decl *, 4> ExprCaptures;
8652 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008653 for (auto &RefExpr : VarList) {
8654 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008655 SourceLocation ELoc;
8656 SourceRange ERange;
8657 Expr *SimpleRefExpr = RefExpr;
8658 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008659 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008660 // It will be analyzed later.
8661 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008662 SrcExprs.push_back(nullptr);
8663 DstExprs.push_back(nullptr);
8664 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008665 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008666 ValueDecl *D = Res.first;
8667 if (!D)
8668 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008669
Alexey Bataev74caaf22016-02-20 04:09:36 +00008670 QualType Type = D->getType();
8671 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008672
8673 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8674 // A variable that appears in a lastprivate clause must not have an
8675 // incomplete type or a reference type.
8676 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008677 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008678 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008679 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008680
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008681 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008682 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8683 // in a Construct]
8684 // Variables with the predetermined data-sharing attributes may not be
8685 // listed in data-sharing attributes clauses, except for the cases
8686 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008687 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8688 // A list item may appear in a firstprivate or lastprivate clause but not
8689 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008690 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008691 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008692 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00008693 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8694 Diag(ELoc, diag::err_omp_wrong_dsa)
8695 << getOpenMPClauseName(DVar.CKind)
8696 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008697 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008698 continue;
8699 }
8700
Alexey Bataevf29276e2014-06-18 04:14:57 +00008701 // OpenMP [2.14.3.5, Restrictions, p.2]
8702 // A list item that is private within a parallel region, or that appears in
8703 // the reduction clause of a parallel construct, must not appear in a
8704 // lastprivate clause on a worksharing construct if any of the corresponding
8705 // worksharing regions ever binds to any of the corresponding parallel
8706 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008707 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008708 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008709 !isOpenMPParallelDirective(CurrDir) &&
8710 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008711 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008712 if (DVar.CKind != OMPC_shared) {
8713 Diag(ELoc, diag::err_omp_required_access)
8714 << getOpenMPClauseName(OMPC_lastprivate)
8715 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008716 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008717 continue;
8718 }
8719 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008720
Alexander Musman1bb328c2014-06-04 13:06:39 +00008721 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008722 // A variable of class type (or array thereof) that appears in a
8723 // lastprivate clause requires an accessible, unambiguous default
8724 // constructor for the class type, unless the list item is also specified
8725 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008726 // A variable of class type (or array thereof) that appears in a
8727 // lastprivate clause requires an accessible, unambiguous copy assignment
8728 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008729 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008730 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008731 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008732 D->hasAttrs() ? &D->getAttrs() : nullptr);
8733 auto *PseudoSrcExpr =
8734 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008735 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008736 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008737 D->hasAttrs() ? &D->getAttrs() : nullptr);
8738 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008739 // For arrays generate assignment operation for single element and replace
8740 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008741 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008742 PseudoDstExpr, PseudoSrcExpr);
8743 if (AssignmentOp.isInvalid())
8744 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008745 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008746 /*DiscardedValue=*/true);
8747 if (AssignmentOp.isInvalid())
8748 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008749
Alexey Bataev74caaf22016-02-20 04:09:36 +00008750 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008751 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008752 if (TopDVar.CKind == OMPC_firstprivate)
8753 Ref = TopDVar.PrivateCopy;
8754 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008755 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008756 if (!IsOpenMPCapturedDecl(D))
8757 ExprCaptures.push_back(Ref->getDecl());
8758 }
8759 if (TopDVar.CKind == OMPC_firstprivate ||
8760 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008761 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008762 ExprResult RefRes = DefaultLvalueConversion(Ref);
8763 if (!RefRes.isUsable())
8764 continue;
8765 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008766 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8767 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008768 if (!PostUpdateRes.isUsable())
8769 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008770 ExprPostUpdates.push_back(
8771 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008772 }
8773 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008774 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008775 Vars.push_back((VD || CurContext->isDependentContext())
8776 ? RefExpr->IgnoreParens()
8777 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008778 SrcExprs.push_back(PseudoSrcExpr);
8779 DstExprs.push_back(PseudoDstExpr);
8780 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008781 }
8782
8783 if (Vars.empty())
8784 return nullptr;
8785
8786 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008787 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008788 buildPreInits(Context, ExprCaptures),
8789 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008790}
8791
Alexey Bataev758e55e2013-09-06 18:03:48 +00008792OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8793 SourceLocation StartLoc,
8794 SourceLocation LParenLoc,
8795 SourceLocation EndLoc) {
8796 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008797 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008798 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008799 SourceLocation ELoc;
8800 SourceRange ERange;
8801 Expr *SimpleRefExpr = RefExpr;
8802 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008803 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008804 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008805 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008806 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008807 ValueDecl *D = Res.first;
8808 if (!D)
8809 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008810
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008811 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008812 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8813 // in a Construct]
8814 // Variables with the predetermined data-sharing attributes may not be
8815 // listed in data-sharing attributes clauses, except for the cases
8816 // listed below. For these exceptions only, listing a predetermined
8817 // variable in a data-sharing attribute clause is allowed and overrides
8818 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008819 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008820 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8821 DVar.RefExpr) {
8822 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8823 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008824 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008825 continue;
8826 }
8827
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008828 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008829 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008830 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008831 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008832 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8833 ? RefExpr->IgnoreParens()
8834 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008835 }
8836
Alexey Bataeved09d242014-05-28 05:53:51 +00008837 if (Vars.empty())
8838 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008839
8840 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8841}
8842
Alexey Bataevc5e02582014-06-16 07:08:35 +00008843namespace {
8844class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8845 DSAStackTy *Stack;
8846
8847public:
8848 bool VisitDeclRefExpr(DeclRefExpr *E) {
8849 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008850 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008851 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8852 return false;
8853 if (DVar.CKind != OMPC_unknown)
8854 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008855 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8856 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008857 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008858 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008859 return true;
8860 return false;
8861 }
8862 return false;
8863 }
8864 bool VisitStmt(Stmt *S) {
8865 for (auto Child : S->children()) {
8866 if (Child && Visit(Child))
8867 return true;
8868 }
8869 return false;
8870 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008871 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008872};
Alexey Bataev23b69422014-06-18 07:08:49 +00008873} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008874
Alexey Bataev60da77e2016-02-29 05:54:20 +00008875namespace {
8876// Transform MemberExpression for specified FieldDecl of current class to
8877// DeclRefExpr to specified OMPCapturedExprDecl.
8878class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8879 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8880 ValueDecl *Field;
8881 DeclRefExpr *CapturedExpr;
8882
8883public:
8884 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8885 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8886
8887 ExprResult TransformMemberExpr(MemberExpr *E) {
8888 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8889 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008890 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008891 return CapturedExpr;
8892 }
8893 return BaseTransform::TransformMemberExpr(E);
8894 }
8895 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8896};
8897} // namespace
8898
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008899template <typename T>
8900static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8901 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8902 for (auto &Set : Lookups) {
8903 for (auto *D : Set) {
8904 if (auto Res = Gen(cast<ValueDecl>(D)))
8905 return Res;
8906 }
8907 }
8908 return T();
8909}
8910
8911static ExprResult
8912buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8913 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8914 const DeclarationNameInfo &ReductionId, QualType Ty,
8915 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8916 if (ReductionIdScopeSpec.isInvalid())
8917 return ExprError();
8918 SmallVector<UnresolvedSet<8>, 4> Lookups;
8919 if (S) {
8920 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8921 Lookup.suppressDiagnostics();
8922 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8923 auto *D = Lookup.getRepresentativeDecl();
8924 do {
8925 S = S->getParent();
8926 } while (S && !S->isDeclScope(D));
8927 if (S)
8928 S = S->getParent();
8929 Lookups.push_back(UnresolvedSet<8>());
8930 Lookups.back().append(Lookup.begin(), Lookup.end());
8931 Lookup.clear();
8932 }
8933 } else if (auto *ULE =
8934 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8935 Lookups.push_back(UnresolvedSet<8>());
8936 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008937 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008938 if (D == PrevD)
8939 Lookups.push_back(UnresolvedSet<8>());
8940 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8941 Lookups.back().addDecl(DRD);
8942 PrevD = D;
8943 }
8944 }
8945 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8946 Ty->containsUnexpandedParameterPack() ||
8947 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8948 return !D->isInvalidDecl() &&
8949 (D->getType()->isDependentType() ||
8950 D->getType()->isInstantiationDependentType() ||
8951 D->getType()->containsUnexpandedParameterPack());
8952 })) {
8953 UnresolvedSet<8> ResSet;
8954 for (auto &Set : Lookups) {
8955 ResSet.append(Set.begin(), Set.end());
8956 // The last item marks the end of all declarations at the specified scope.
8957 ResSet.addDecl(Set[Set.size() - 1]);
8958 }
8959 return UnresolvedLookupExpr::Create(
8960 SemaRef.Context, /*NamingClass=*/nullptr,
8961 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8962 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8963 }
8964 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8965 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8966 if (!D->isInvalidDecl() &&
8967 SemaRef.Context.hasSameType(D->getType(), Ty))
8968 return D;
8969 return nullptr;
8970 }))
8971 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8972 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8973 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8974 if (!D->isInvalidDecl() &&
8975 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8976 !Ty.isMoreQualifiedThan(D->getType()))
8977 return D;
8978 return nullptr;
8979 })) {
8980 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8981 /*DetectVirtual=*/false);
8982 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8983 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8984 VD->getType().getUnqualifiedType()))) {
8985 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8986 /*DiagID=*/0) !=
8987 Sema::AR_inaccessible) {
8988 SemaRef.BuildBasePathArray(Paths, BasePath);
8989 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8990 }
8991 }
8992 }
8993 }
8994 if (ReductionIdScopeSpec.isSet()) {
8995 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8996 return ExprError();
8997 }
8998 return ExprEmpty();
8999}
9000
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009001namespace {
9002/// Data for the reduction-based clauses.
9003struct ReductionData {
9004 /// List of original reduction items.
9005 SmallVector<Expr *, 8> Vars;
9006 /// List of private copies of the reduction items.
9007 SmallVector<Expr *, 8> Privates;
9008 /// LHS expressions for the reduction_op expressions.
9009 SmallVector<Expr *, 8> LHSs;
9010 /// RHS expressions for the reduction_op expressions.
9011 SmallVector<Expr *, 8> RHSs;
9012 /// Reduction operation expression.
9013 SmallVector<Expr *, 8> ReductionOps;
9014 /// List of captures for clause.
9015 SmallVector<Decl *, 4> ExprCaptures;
9016 /// List of postupdate expressions.
9017 SmallVector<Expr *, 4> ExprPostUpdates;
9018 ReductionData() = delete;
9019 /// Reserves required memory for the reduction data.
9020 ReductionData(unsigned Size) {
9021 Vars.reserve(Size);
9022 Privates.reserve(Size);
9023 LHSs.reserve(Size);
9024 RHSs.reserve(Size);
9025 ReductionOps.reserve(Size);
9026 ExprCaptures.reserve(Size);
9027 ExprPostUpdates.reserve(Size);
9028 }
9029 /// Stores reduction item and reduction operation only (required for dependent
9030 /// reduction item).
9031 void push(Expr *Item, Expr *ReductionOp) {
9032 Vars.emplace_back(Item);
9033 Privates.emplace_back(nullptr);
9034 LHSs.emplace_back(nullptr);
9035 RHSs.emplace_back(nullptr);
9036 ReductionOps.emplace_back(ReductionOp);
9037 }
9038 /// Stores reduction data.
9039 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS,
9040 Expr *ReductionOp) {
9041 Vars.emplace_back(Item);
9042 Privates.emplace_back(Private);
9043 LHSs.emplace_back(LHS);
9044 RHSs.emplace_back(RHS);
9045 ReductionOps.emplace_back(ReductionOp);
9046 }
9047};
9048} // namespace
9049
9050static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009051 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9052 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9053 SourceLocation ColonLoc, SourceLocation EndLoc,
9054 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009055 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009056 auto DN = ReductionId.getName();
9057 auto OOK = DN.getCXXOverloadedOperator();
9058 BinaryOperatorKind BOK = BO_Comma;
9059
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009060 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009061 // OpenMP [2.14.3.6, reduction clause]
9062 // C
9063 // reduction-identifier is either an identifier or one of the following
9064 // operators: +, -, *, &, |, ^, && and ||
9065 // C++
9066 // reduction-identifier is either an id-expression or one of the following
9067 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009068 switch (OOK) {
9069 case OO_Plus:
9070 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009071 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009072 break;
9073 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009074 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009075 break;
9076 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009077 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009078 break;
9079 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009080 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009081 break;
9082 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009083 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009084 break;
9085 case OO_AmpAmp:
9086 BOK = BO_LAnd;
9087 break;
9088 case OO_PipePipe:
9089 BOK = BO_LOr;
9090 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009091 case OO_New:
9092 case OO_Delete:
9093 case OO_Array_New:
9094 case OO_Array_Delete:
9095 case OO_Slash:
9096 case OO_Percent:
9097 case OO_Tilde:
9098 case OO_Exclaim:
9099 case OO_Equal:
9100 case OO_Less:
9101 case OO_Greater:
9102 case OO_LessEqual:
9103 case OO_GreaterEqual:
9104 case OO_PlusEqual:
9105 case OO_MinusEqual:
9106 case OO_StarEqual:
9107 case OO_SlashEqual:
9108 case OO_PercentEqual:
9109 case OO_CaretEqual:
9110 case OO_AmpEqual:
9111 case OO_PipeEqual:
9112 case OO_LessLess:
9113 case OO_GreaterGreater:
9114 case OO_LessLessEqual:
9115 case OO_GreaterGreaterEqual:
9116 case OO_EqualEqual:
9117 case OO_ExclaimEqual:
9118 case OO_PlusPlus:
9119 case OO_MinusMinus:
9120 case OO_Comma:
9121 case OO_ArrowStar:
9122 case OO_Arrow:
9123 case OO_Call:
9124 case OO_Subscript:
9125 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009126 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009127 case NUM_OVERLOADED_OPERATORS:
9128 llvm_unreachable("Unexpected reduction identifier");
9129 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009130 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009131 if (II->isStr("max"))
9132 BOK = BO_GT;
9133 else if (II->isStr("min"))
9134 BOK = BO_LT;
9135 }
9136 break;
9137 }
9138 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009139 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009140 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009141 else
9142 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009143 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009144
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009145 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9146 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009147 for (auto RefExpr : VarList) {
9148 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009149 // OpenMP [2.1, C/C++]
9150 // A list item is a variable or array section, subject to the restrictions
9151 // specified in Section 2.4 on page 42 and in each of the sections
9152 // describing clauses and directives for which a list appears.
9153 // OpenMP [2.14.3.3, Restrictions, p.1]
9154 // A variable that is part of another variable (as an array or
9155 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009156 if (!FirstIter && IR != ER)
9157 ++IR;
9158 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009159 SourceLocation ELoc;
9160 SourceRange ERange;
9161 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009162 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009163 /*AllowArraySection=*/true);
9164 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009165 // Try to find 'declare reduction' corresponding construct before using
9166 // builtin/overloaded operators.
9167 QualType Type = Context.DependentTy;
9168 CXXCastPath BasePath;
9169 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009170 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009171 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009172 Expr *ReductionOp = nullptr;
9173 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009174 (DeclareReductionRef.isUnset() ||
9175 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009176 ReductionOp = DeclareReductionRef.get();
9177 // It will be analyzed later.
9178 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009179 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009180 ValueDecl *D = Res.first;
9181 if (!D)
9182 continue;
9183
Alexey Bataeva1764212015-09-30 09:22:36 +00009184 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009185 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9186 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9187 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009188 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009189 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009190 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9191 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9192 Type = ATy->getElementType();
9193 else
9194 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009195 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009196 } else
9197 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9198 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009199
Alexey Bataevc5e02582014-06-16 07:08:35 +00009200 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9201 // A variable that appears in a private clause must not have an incomplete
9202 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009203 if (S.RequireCompleteType(ELoc, Type,
9204 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009205 continue;
9206 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009207 // A list item that appears in a reduction clause must not be
9208 // const-qualified.
9209 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009210 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009211 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009212 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9213 VarDecl::DeclarationOnly;
9214 S.Diag(D->getLocation(),
9215 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009216 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009217 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009218 continue;
9219 }
9220 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9221 // If a list-item is a reference type then it must bind to the same object
9222 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009223 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009224 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009225 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009226 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009227 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009228 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9229 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009230 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009231 continue;
9232 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009233 }
9234 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009235
Alexey Bataevc5e02582014-06-16 07:08:35 +00009236 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9237 // in a Construct]
9238 // Variables with the predetermined data-sharing attributes may not be
9239 // listed in data-sharing attributes clauses, except for the cases
9240 // listed below. For these exceptions only, listing a predetermined
9241 // variable in a data-sharing attribute clause is allowed and overrides
9242 // the variable's predetermined data-sharing attributes.
9243 // OpenMP [2.14.3.6, Restrictions, p.3]
9244 // Any number of reduction clauses can be specified on the directive,
9245 // but a list item can appear only once in the reduction clauses for that
9246 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009247 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009248 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009249 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009250 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009251 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009252 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009253 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009254 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009255 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009256 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009257 << getOpenMPClauseName(DVar.CKind)
9258 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009259 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009260 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009261 }
9262
9263 // OpenMP [2.14.3.6, Restrictions, p.1]
9264 // A list item that appears in a reduction clause of a worksharing
9265 // construct must be shared in the parallel regions to which any of the
9266 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009267 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009268 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009269 !isOpenMPParallelDirective(CurrDir) &&
9270 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009271 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009272 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009273 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009274 << getOpenMPClauseName(OMPC_reduction)
9275 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009276 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009277 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009278 }
9279 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009280
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009281 // Try to find 'declare reduction' corresponding construct before using
9282 // builtin/overloaded operators.
9283 CXXCastPath BasePath;
9284 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009285 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009286 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9287 if (DeclareReductionRef.isInvalid())
9288 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009289 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009290 (DeclareReductionRef.isUnset() ||
9291 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009292 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009293 continue;
9294 }
9295 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9296 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009297 S.Diag(ReductionId.getLocStart(),
9298 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009299 << Type << ReductionIdRange;
9300 continue;
9301 }
9302
9303 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9304 // The type of a list item that appears in a reduction clause must be valid
9305 // for the reduction-identifier. For a max or min reduction in C, the type
9306 // of the list item must be an allowed arithmetic data type: char, int,
9307 // float, double, or _Bool, possibly modified with long, short, signed, or
9308 // unsigned. For a max or min reduction in C++, the type of the list item
9309 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9310 // double, or bool, possibly modified with long, short, signed, or unsigned.
9311 if (DeclareReductionRef.isUnset()) {
9312 if ((BOK == BO_GT || BOK == BO_LT) &&
9313 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009314 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9315 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009316 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009317 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009318 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9319 VarDecl::DeclarationOnly;
9320 S.Diag(D->getLocation(),
9321 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009322 << D;
9323 }
9324 continue;
9325 }
9326 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009327 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009328 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9329 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009330 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009331 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9332 VarDecl::DeclarationOnly;
9333 S.Diag(D->getLocation(),
9334 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009335 << D;
9336 }
9337 continue;
9338 }
9339 }
9340
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009341 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009342 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009343 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009344 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009345 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009346 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009347 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009348 (!ASE &&
9349 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009350 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009351 // Create pseudo array type for private copy. The size for this array will
9352 // be generated during codegen.
9353 // For array subscripts or single variables Private Ty is the same as Type
9354 // (type of the variable or single array element).
9355 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009356 Type,
9357 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9358 VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009359 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009360 } else if (!ASE && !OASE &&
9361 Context.getAsArrayType(D->getType().getNonReferenceType()))
9362 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009363 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009364 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009365 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009366 // Add initializer for private variable.
9367 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009368 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9369 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009370 if (DeclareReductionRef.isUsable()) {
9371 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9372 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9373 if (DRD->getInitializer()) {
9374 Init = DRDRef;
9375 RHSVD->setInit(DRDRef);
9376 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009377 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009378 } else {
9379 switch (BOK) {
9380 case BO_Add:
9381 case BO_Xor:
9382 case BO_Or:
9383 case BO_LOr:
9384 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9385 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009386 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009387 break;
9388 case BO_Mul:
9389 case BO_LAnd:
9390 if (Type->isScalarType() || Type->isAnyComplexType()) {
9391 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009392 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009393 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009394 break;
9395 case BO_And: {
9396 // '&' reduction op - initializer is '~0'.
9397 QualType OrigType = Type;
9398 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9399 Type = ComplexTy->getElementType();
9400 if (Type->isRealFloatingType()) {
9401 llvm::APFloat InitValue =
9402 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9403 /*isIEEE=*/true);
9404 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9405 Type, ELoc);
9406 } else if (Type->isScalarType()) {
9407 auto Size = Context.getTypeSize(Type);
9408 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9409 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9410 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9411 }
9412 if (Init && OrigType->isAnyComplexType()) {
9413 // Init = 0xFFFF + 0xFFFFi;
9414 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009415 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009416 }
9417 Type = OrigType;
9418 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009419 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009420 case BO_LT:
9421 case BO_GT: {
9422 // 'min' reduction op - initializer is 'Largest representable number in
9423 // the reduction list item type'.
9424 // 'max' reduction op - initializer is 'Least representable number in
9425 // the reduction list item type'.
9426 if (Type->isIntegerType() || Type->isPointerType()) {
9427 bool IsSigned = Type->hasSignedIntegerRepresentation();
9428 auto Size = Context.getTypeSize(Type);
9429 QualType IntTy =
9430 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9431 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009432 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9433 : llvm::APInt::getMinValue(Size)
9434 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9435 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009436 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9437 if (Type->isPointerType()) {
9438 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009439 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009440 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9441 SourceLocation(), Init);
9442 if (CastExpr.isInvalid())
9443 continue;
9444 Init = CastExpr.get();
9445 }
9446 } else if (Type->isRealFloatingType()) {
9447 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9448 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9449 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9450 Type, ELoc);
9451 }
9452 break;
9453 }
9454 case BO_PtrMemD:
9455 case BO_PtrMemI:
9456 case BO_MulAssign:
9457 case BO_Div:
9458 case BO_Rem:
9459 case BO_Sub:
9460 case BO_Shl:
9461 case BO_Shr:
9462 case BO_LE:
9463 case BO_GE:
9464 case BO_EQ:
9465 case BO_NE:
9466 case BO_AndAssign:
9467 case BO_XorAssign:
9468 case BO_OrAssign:
9469 case BO_Assign:
9470 case BO_AddAssign:
9471 case BO_SubAssign:
9472 case BO_DivAssign:
9473 case BO_RemAssign:
9474 case BO_ShlAssign:
9475 case BO_ShrAssign:
9476 case BO_Comma:
9477 llvm_unreachable("Unexpected reduction operation");
9478 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009479 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009480 if (Init && DeclareReductionRef.isUnset())
9481 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9482 else if (!Init)
9483 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009484 if (RHSVD->isInvalidDecl())
9485 continue;
9486 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009487 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9488 << Type << ReductionIdRange;
9489 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9490 VarDecl::DeclarationOnly;
9491 S.Diag(D->getLocation(),
9492 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009493 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009494 continue;
9495 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009496 // Store initializer for single element in private copy. Will be used during
9497 // codegen.
9498 PrivateVD->setInit(RHSVD->getInit());
9499 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009500 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009501 ExprResult ReductionOp;
9502 if (DeclareReductionRef.isUsable()) {
9503 QualType RedTy = DeclareReductionRef.get()->getType();
9504 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009505 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9506 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009507 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009508 LHS = S.DefaultLvalueConversion(LHS.get());
9509 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009510 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9511 CK_UncheckedDerivedToBase, LHS.get(),
9512 &BasePath, LHS.get()->getValueKind());
9513 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9514 CK_UncheckedDerivedToBase, RHS.get(),
9515 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009516 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009517 FunctionProtoType::ExtProtoInfo EPI;
9518 QualType Params[] = {PtrRedTy, PtrRedTy};
9519 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9520 auto *OVE = new (Context) OpaqueValueExpr(
9521 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009522 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009523 Expr *Args[] = {LHS.get(), RHS.get()};
9524 ReductionOp = new (Context)
9525 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9526 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009527 ReductionOp = S.BuildBinOp(
9528 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009529 if (ReductionOp.isUsable()) {
9530 if (BOK != BO_LT && BOK != BO_GT) {
9531 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009532 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9533 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009534 } else {
9535 auto *ConditionalOp = new (Context) ConditionalOperator(
9536 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9537 RHSDRE, Type, VK_LValue, OK_Ordinary);
9538 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009539 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9540 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009541 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009542 if (ReductionOp.isUsable())
9543 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009544 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009545 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009546 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009547 }
9548
Alexey Bataevfa312f32017-07-21 18:48:21 +00009549 // OpenMP [2.15.4.6, Restrictions, p.2]
9550 // A list item that appears in an in_reduction clause of a task construct
9551 // must appear in a task_reduction clause of a construct associated with a
9552 // taskgroup region that includes the participating task in its taskgroup
9553 // set. The construct associated with the innermost region that meets this
9554 // condition must specify the same reduction-identifier as the in_reduction
9555 // clause.
9556 if (ClauseKind == OMPC_in_reduction) {
9557 DVar = Stack->hasDSA(
9558 D, [](OpenMPClauseKind K) { return K != OMPC_unknown; },
9559 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
9560 /*FromParent=*/true);
9561 if (DVar.CKind != OMPC_reduction || DVar.DKind != OMPD_taskgroup) {
9562 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
9563 continue;
9564 }
9565 SourceRange ParentSR;
9566 BinaryOperatorKind ParentBOK;
9567 const Expr *ParentReductionOp;
9568 bool IsParentBOK = Stack->getTopMostReductionData(D, ParentSR, ParentBOK);
9569 bool IsParentReductionOp =
9570 Stack->getTopMostReductionData(D, ParentSR, ParentReductionOp);
9571 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
9572 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
9573 IsParentReductionOp) {
9574 bool EmitError = true;
9575 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
9576 llvm::FoldingSetNodeID RedId, ParentRedId;
9577 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
9578 DeclareReductionRef.get()->Profile(RedId, Context,
9579 /*Canonical=*/true);
9580 EmitError = RedId != ParentRedId;
9581 }
9582 if (EmitError) {
9583 S.Diag(ReductionId.getLocStart(),
9584 diag::err_omp_reduction_identifier_mismatch)
9585 << ReductionIdRange << RefExpr->getSourceRange();
9586 S.Diag(ParentSR.getBegin(),
9587 diag::note_omp_previous_reduction_identifier)
9588 << ParentSR << DVar.RefExpr->getSourceRange();
9589 continue;
9590 }
9591 }
9592 }
9593
Alexey Bataev60da77e2016-02-29 05:54:20 +00009594 DeclRefExpr *Ref = nullptr;
9595 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009596 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009597 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009598 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009599 VarsExpr =
9600 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9601 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009602 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009603 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009604 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009605 if (!S.IsOpenMPCapturedDecl(D)) {
9606 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009607 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009608 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009609 if (!RefRes.isUsable())
9610 continue;
9611 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009612 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9613 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009614 if (!PostUpdateRes.isUsable())
9615 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009616 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9617 Stack->getCurrentDirective() == OMPD_taskgroup) {
9618 S.Diag(RefExpr->getExprLoc(),
9619 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009620 << RefExpr->getSourceRange();
9621 continue;
9622 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009623 RD.ExprPostUpdates.emplace_back(
9624 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009625 }
9626 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009627 }
Alexey Bataev169d96a2017-07-18 20:17:46 +00009628 // All reduction items are still marked as reduction (to do not increase
9629 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009630 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevfa312f32017-07-21 18:48:21 +00009631 if (DeclareReductionRef.isUsable())
9632 Stack->addReductionData(D, ReductionIdRange, DeclareReductionRef.get());
9633 else
9634 Stack->addReductionData(D, ReductionIdRange, BOK);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009635 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009636 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009637 return RD.Vars.empty();
9638}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009639
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009640OMPClause *Sema::ActOnOpenMPReductionClause(
9641 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9642 SourceLocation ColonLoc, SourceLocation EndLoc,
9643 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9644 ArrayRef<Expr *> UnresolvedReductions) {
9645 ReductionData RD(VarList.size());
9646
Alexey Bataev169d96a2017-07-18 20:17:46 +00009647 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
9648 StartLoc, LParenLoc, ColonLoc, EndLoc,
9649 ReductionIdScopeSpec, ReductionId,
9650 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009651 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009652
Alexey Bataevc5e02582014-06-16 07:08:35 +00009653 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009654 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9655 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9656 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9657 buildPreInits(Context, RD.ExprCaptures),
9658 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009659}
9660
Alexey Bataev169d96a2017-07-18 20:17:46 +00009661OMPClause *Sema::ActOnOpenMPTaskReductionClause(
9662 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9663 SourceLocation ColonLoc, SourceLocation EndLoc,
9664 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9665 ArrayRef<Expr *> UnresolvedReductions) {
9666 ReductionData RD(VarList.size());
9667
9668 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
9669 VarList, StartLoc, LParenLoc, ColonLoc,
9670 EndLoc, ReductionIdScopeSpec, ReductionId,
9671 UnresolvedReductions, RD))
9672 return nullptr;
9673
9674 return OMPTaskReductionClause::Create(
9675 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9676 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9677 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9678 buildPreInits(Context, RD.ExprCaptures),
9679 buildPostUpdate(*this, RD.ExprPostUpdates));
9680}
9681
Alexey Bataevfa312f32017-07-21 18:48:21 +00009682OMPClause *Sema::ActOnOpenMPInReductionClause(
9683 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9684 SourceLocation ColonLoc, SourceLocation EndLoc,
9685 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9686 ArrayRef<Expr *> UnresolvedReductions) {
9687 ReductionData RD(VarList.size());
9688
9689 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
9690 StartLoc, LParenLoc, ColonLoc, EndLoc,
9691 ReductionIdScopeSpec, ReductionId,
9692 UnresolvedReductions, RD))
9693 return nullptr;
9694
9695 return OMPInReductionClause::Create(
9696 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9697 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9698 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9699 buildPreInits(Context, RD.ExprCaptures),
9700 buildPostUpdate(*this, RD.ExprPostUpdates));
9701}
9702
Alexey Bataevecba70f2016-04-12 11:02:11 +00009703bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9704 SourceLocation LinLoc) {
9705 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9706 LinKind == OMPC_LINEAR_unknown) {
9707 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9708 return true;
9709 }
9710 return false;
9711}
9712
9713bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9714 OpenMPLinearClauseKind LinKind,
9715 QualType Type) {
9716 auto *VD = dyn_cast_or_null<VarDecl>(D);
9717 // A variable must not have an incomplete type or a reference type.
9718 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9719 return true;
9720 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9721 !Type->isReferenceType()) {
9722 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9723 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9724 return true;
9725 }
9726 Type = Type.getNonReferenceType();
9727
9728 // A list item must not be const-qualified.
9729 if (Type.isConstant(Context)) {
9730 Diag(ELoc, diag::err_omp_const_variable)
9731 << getOpenMPClauseName(OMPC_linear);
9732 if (D) {
9733 bool IsDecl =
9734 !VD ||
9735 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9736 Diag(D->getLocation(),
9737 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9738 << D;
9739 }
9740 return true;
9741 }
9742
9743 // A list item must be of integral or pointer type.
9744 Type = Type.getUnqualifiedType().getCanonicalType();
9745 const auto *Ty = Type.getTypePtrOrNull();
9746 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9747 !Ty->isPointerType())) {
9748 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9749 if (D) {
9750 bool IsDecl =
9751 !VD ||
9752 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9753 Diag(D->getLocation(),
9754 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9755 << D;
9756 }
9757 return true;
9758 }
9759 return false;
9760}
9761
Alexey Bataev182227b2015-08-20 10:54:39 +00009762OMPClause *Sema::ActOnOpenMPLinearClause(
9763 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9764 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9765 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009766 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009767 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009768 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009769 SmallVector<Decl *, 4> ExprCaptures;
9770 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009771 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009772 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009773 for (auto &RefExpr : VarList) {
9774 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009775 SourceLocation ELoc;
9776 SourceRange ERange;
9777 Expr *SimpleRefExpr = RefExpr;
9778 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9779 /*AllowArraySection=*/false);
9780 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009781 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009782 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009783 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009784 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009785 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009786 ValueDecl *D = Res.first;
9787 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009788 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009789
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009790 QualType Type = D->getType();
9791 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009792
9793 // OpenMP [2.14.3.7, linear clause]
9794 // A list-item cannot appear in more than one linear clause.
9795 // A list-item that appears in a linear clause cannot appear in any
9796 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009797 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009798 if (DVar.RefExpr) {
9799 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9800 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009801 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009802 continue;
9803 }
9804
Alexey Bataevecba70f2016-04-12 11:02:11 +00009805 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009806 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009807 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009808
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009809 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009810 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9811 D->hasAttrs() ? &D->getAttrs() : nullptr);
9812 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009813 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009814 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009815 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009816 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009817 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009818 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9819 if (!IsOpenMPCapturedDecl(D)) {
9820 ExprCaptures.push_back(Ref->getDecl());
9821 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9822 ExprResult RefRes = DefaultLvalueConversion(Ref);
9823 if (!RefRes.isUsable())
9824 continue;
9825 ExprResult PostUpdateRes =
9826 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9827 SimpleRefExpr, RefRes.get());
9828 if (!PostUpdateRes.isUsable())
9829 continue;
9830 ExprPostUpdates.push_back(
9831 IgnoredValueConversions(PostUpdateRes.get()).get());
9832 }
9833 }
9834 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009835 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009836 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009837 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009838 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009839 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009840 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009841 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9842
9843 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009844 Vars.push_back((VD || CurContext->isDependentContext())
9845 ? RefExpr->IgnoreParens()
9846 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009847 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009848 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009849 }
9850
9851 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009852 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009853
9854 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009855 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009856 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9857 !Step->isInstantiationDependent() &&
9858 !Step->containsUnexpandedParameterPack()) {
9859 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009860 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009861 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009862 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009863 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009864
Alexander Musman3276a272015-03-21 10:12:56 +00009865 // Build var to save the step value.
9866 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009867 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009868 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009869 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009870 ExprResult CalcStep =
9871 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009872 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009873
Alexander Musman8dba6642014-04-22 13:09:42 +00009874 // Warn about zero linear step (it would be probably better specified as
9875 // making corresponding variables 'const').
9876 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009877 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9878 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009879 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9880 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009881 if (!IsConstant && CalcStep.isUsable()) {
9882 // Calculate the step beforehand instead of doing this on each iteration.
9883 // (This is not used if the number of iterations may be kfold-ed).
9884 CalcStepExpr = CalcStep.get();
9885 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009886 }
9887
Alexey Bataev182227b2015-08-20 10:54:39 +00009888 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9889 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009890 StepExpr, CalcStepExpr,
9891 buildPreInits(Context, ExprCaptures),
9892 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009893}
9894
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009895static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9896 Expr *NumIterations, Sema &SemaRef,
9897 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009898 // Walk the vars and build update/final expressions for the CodeGen.
9899 SmallVector<Expr *, 8> Updates;
9900 SmallVector<Expr *, 8> Finals;
9901 Expr *Step = Clause.getStep();
9902 Expr *CalcStep = Clause.getCalcStep();
9903 // OpenMP [2.14.3.7, linear clause]
9904 // If linear-step is not specified it is assumed to be 1.
9905 if (Step == nullptr)
9906 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009907 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009908 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009909 }
Alexander Musman3276a272015-03-21 10:12:56 +00009910 bool HasErrors = false;
9911 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009912 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009913 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009914 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009915 SourceLocation ELoc;
9916 SourceRange ERange;
9917 Expr *SimpleRefExpr = RefExpr;
9918 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9919 /*AllowArraySection=*/false);
9920 ValueDecl *D = Res.first;
9921 if (Res.second || !D) {
9922 Updates.push_back(nullptr);
9923 Finals.push_back(nullptr);
9924 HasErrors = true;
9925 continue;
9926 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009927 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009928 Expr *InitExpr = *CurInit;
9929
9930 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009931 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009932 Expr *CapturedRef;
9933 if (LinKind == OMPC_LINEAR_uval)
9934 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9935 else
9936 CapturedRef =
9937 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9938 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9939 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009940
9941 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009942 ExprResult Update;
9943 if (!Info.first) {
9944 Update =
9945 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9946 InitExpr, IV, Step, /* Subtract */ false);
9947 } else
9948 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009949 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9950 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009951
9952 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009953 ExprResult Final;
9954 if (!Info.first) {
9955 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9956 InitExpr, NumIterations, Step,
9957 /* Subtract */ false);
9958 } else
9959 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009960 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9961 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009962
Alexander Musman3276a272015-03-21 10:12:56 +00009963 if (!Update.isUsable() || !Final.isUsable()) {
9964 Updates.push_back(nullptr);
9965 Finals.push_back(nullptr);
9966 HasErrors = true;
9967 } else {
9968 Updates.push_back(Update.get());
9969 Finals.push_back(Final.get());
9970 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009971 ++CurInit;
9972 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009973 }
9974 Clause.setUpdates(Updates);
9975 Clause.setFinals(Finals);
9976 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009977}
9978
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009979OMPClause *Sema::ActOnOpenMPAlignedClause(
9980 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9981 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9982
9983 SmallVector<Expr *, 8> Vars;
9984 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009985 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9986 SourceLocation ELoc;
9987 SourceRange ERange;
9988 Expr *SimpleRefExpr = RefExpr;
9989 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9990 /*AllowArraySection=*/false);
9991 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009992 // It will be analyzed later.
9993 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009994 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009995 ValueDecl *D = Res.first;
9996 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009997 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009998
Alexey Bataev1efd1662016-03-29 10:59:56 +00009999 QualType QType = D->getType();
10000 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010001
10002 // OpenMP [2.8.1, simd construct, Restrictions]
10003 // The type of list items appearing in the aligned clause must be
10004 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010005 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010006 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010007 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010008 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010009 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010010 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010011 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010012 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010013 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010014 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010015 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010016 continue;
10017 }
10018
10019 // OpenMP [2.8.1, simd construct, Restrictions]
10020 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010021 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010022 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010023 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10024 << getOpenMPClauseName(OMPC_aligned);
10025 continue;
10026 }
10027
Alexey Bataev1efd1662016-03-29 10:59:56 +000010028 DeclRefExpr *Ref = nullptr;
10029 if (!VD && IsOpenMPCapturedDecl(D))
10030 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10031 Vars.push_back(DefaultFunctionArrayConversion(
10032 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10033 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010034 }
10035
10036 // OpenMP [2.8.1, simd construct, Description]
10037 // The parameter of the aligned clause, alignment, must be a constant
10038 // positive integer expression.
10039 // If no optional parameter is specified, implementation-defined default
10040 // alignments for SIMD instructions on the target platforms are assumed.
10041 if (Alignment != nullptr) {
10042 ExprResult AlignResult =
10043 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10044 if (AlignResult.isInvalid())
10045 return nullptr;
10046 Alignment = AlignResult.get();
10047 }
10048 if (Vars.empty())
10049 return nullptr;
10050
10051 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10052 EndLoc, Vars, Alignment);
10053}
10054
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010055OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10056 SourceLocation StartLoc,
10057 SourceLocation LParenLoc,
10058 SourceLocation EndLoc) {
10059 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010060 SmallVector<Expr *, 8> SrcExprs;
10061 SmallVector<Expr *, 8> DstExprs;
10062 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010063 for (auto &RefExpr : VarList) {
10064 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10065 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010066 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010067 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010068 SrcExprs.push_back(nullptr);
10069 DstExprs.push_back(nullptr);
10070 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010071 continue;
10072 }
10073
Alexey Bataeved09d242014-05-28 05:53:51 +000010074 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010075 // OpenMP [2.1, C/C++]
10076 // A list item is a variable name.
10077 // OpenMP [2.14.4.1, Restrictions, p.1]
10078 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010079 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010080 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010081 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10082 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010083 continue;
10084 }
10085
10086 Decl *D = DE->getDecl();
10087 VarDecl *VD = cast<VarDecl>(D);
10088
10089 QualType Type = VD->getType();
10090 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10091 // It will be analyzed later.
10092 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010093 SrcExprs.push_back(nullptr);
10094 DstExprs.push_back(nullptr);
10095 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010096 continue;
10097 }
10098
10099 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10100 // A list item that appears in a copyin clause must be threadprivate.
10101 if (!DSAStack->isThreadPrivate(VD)) {
10102 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010103 << getOpenMPClauseName(OMPC_copyin)
10104 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010105 continue;
10106 }
10107
10108 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10109 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010110 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010111 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010112 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010113 auto *SrcVD =
10114 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10115 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010116 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010117 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10118 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010119 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10120 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010121 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010122 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010123 // For arrays generate assignment operation for single element and replace
10124 // it by the original array element in CodeGen.
10125 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10126 PseudoDstExpr, PseudoSrcExpr);
10127 if (AssignmentOp.isInvalid())
10128 continue;
10129 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10130 /*DiscardedValue=*/true);
10131 if (AssignmentOp.isInvalid())
10132 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010133
10134 DSAStack->addDSA(VD, DE, OMPC_copyin);
10135 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010136 SrcExprs.push_back(PseudoSrcExpr);
10137 DstExprs.push_back(PseudoDstExpr);
10138 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010139 }
10140
Alexey Bataeved09d242014-05-28 05:53:51 +000010141 if (Vars.empty())
10142 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010143
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010144 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10145 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010146}
10147
Alexey Bataevbae9a792014-06-27 10:37:06 +000010148OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10149 SourceLocation StartLoc,
10150 SourceLocation LParenLoc,
10151 SourceLocation EndLoc) {
10152 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010153 SmallVector<Expr *, 8> SrcExprs;
10154 SmallVector<Expr *, 8> DstExprs;
10155 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010156 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010157 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10158 SourceLocation ELoc;
10159 SourceRange ERange;
10160 Expr *SimpleRefExpr = RefExpr;
10161 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10162 /*AllowArraySection=*/false);
10163 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010164 // It will be analyzed later.
10165 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010166 SrcExprs.push_back(nullptr);
10167 DstExprs.push_back(nullptr);
10168 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010169 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010170 ValueDecl *D = Res.first;
10171 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010172 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010173
Alexey Bataeve122da12016-03-17 10:50:17 +000010174 QualType Type = D->getType();
10175 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010176
10177 // OpenMP [2.14.4.2, Restrictions, p.2]
10178 // A list item that appears in a copyprivate clause may not appear in a
10179 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010180 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10181 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010182 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10183 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010184 Diag(ELoc, diag::err_omp_wrong_dsa)
10185 << getOpenMPClauseName(DVar.CKind)
10186 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010187 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010188 continue;
10189 }
10190
10191 // OpenMP [2.11.4.2, Restrictions, p.1]
10192 // All list items that appear in a copyprivate clause must be either
10193 // threadprivate or private in the enclosing context.
10194 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010195 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010196 if (DVar.CKind == OMPC_shared) {
10197 Diag(ELoc, diag::err_omp_required_access)
10198 << getOpenMPClauseName(OMPC_copyprivate)
10199 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010200 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010201 continue;
10202 }
10203 }
10204 }
10205
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010206 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010207 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010208 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010209 << getOpenMPClauseName(OMPC_copyprivate) << Type
10210 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010211 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010212 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010213 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010214 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010215 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010216 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010217 continue;
10218 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010219
Alexey Bataevbae9a792014-06-27 10:37:06 +000010220 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10221 // A variable of class type (or array thereof) that appears in a
10222 // copyin clause requires an accessible, unambiguous copy assignment
10223 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010224 Type = Context.getBaseElementType(Type.getNonReferenceType())
10225 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010226 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010227 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10228 D->hasAttrs() ? &D->getAttrs() : nullptr);
10229 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010230 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010231 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10232 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010233 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010234 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010235 PseudoDstExpr, PseudoSrcExpr);
10236 if (AssignmentOp.isInvalid())
10237 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010238 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010239 /*DiscardedValue=*/true);
10240 if (AssignmentOp.isInvalid())
10241 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010242
10243 // No need to mark vars as copyprivate, they are already threadprivate or
10244 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010245 assert(VD || IsOpenMPCapturedDecl(D));
10246 Vars.push_back(
10247 VD ? RefExpr->IgnoreParens()
10248 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010249 SrcExprs.push_back(PseudoSrcExpr);
10250 DstExprs.push_back(PseudoDstExpr);
10251 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010252 }
10253
10254 if (Vars.empty())
10255 return nullptr;
10256
Alexey Bataeva63048e2015-03-23 06:18:07 +000010257 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10258 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010259}
10260
Alexey Bataev6125da92014-07-21 11:26:11 +000010261OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10262 SourceLocation StartLoc,
10263 SourceLocation LParenLoc,
10264 SourceLocation EndLoc) {
10265 if (VarList.empty())
10266 return nullptr;
10267
10268 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10269}
Alexey Bataevdea47612014-07-23 07:46:59 +000010270
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010271OMPClause *
10272Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10273 SourceLocation DepLoc, SourceLocation ColonLoc,
10274 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10275 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010276 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010277 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010278 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010279 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010280 return nullptr;
10281 }
10282 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010283 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10284 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010285 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010286 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010287 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10288 /*Last=*/OMPC_DEPEND_unknown, Except)
10289 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010290 return nullptr;
10291 }
10292 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010293 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010294 llvm::APSInt DepCounter(/*BitWidth=*/32);
10295 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10296 if (DepKind == OMPC_DEPEND_sink) {
10297 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10298 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10299 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010300 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010301 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010302 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10303 DSAStack->getParentOrderedRegionParam()) {
10304 for (auto &RefExpr : VarList) {
10305 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010306 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010307 // It will be analyzed later.
10308 Vars.push_back(RefExpr);
10309 continue;
10310 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010311
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010312 SourceLocation ELoc = RefExpr->getExprLoc();
10313 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10314 if (DepKind == OMPC_DEPEND_sink) {
10315 if (DepCounter >= TotalDepCount) {
10316 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10317 continue;
10318 }
10319 ++DepCounter;
10320 // OpenMP [2.13.9, Summary]
10321 // depend(dependence-type : vec), where dependence-type is:
10322 // 'sink' and where vec is the iteration vector, which has the form:
10323 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10324 // where n is the value specified by the ordered clause in the loop
10325 // directive, xi denotes the loop iteration variable of the i-th nested
10326 // loop associated with the loop directive, and di is a constant
10327 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010328 if (CurContext->isDependentContext()) {
10329 // It will be analyzed later.
10330 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010331 continue;
10332 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010333 SimpleExpr = SimpleExpr->IgnoreImplicit();
10334 OverloadedOperatorKind OOK = OO_None;
10335 SourceLocation OOLoc;
10336 Expr *LHS = SimpleExpr;
10337 Expr *RHS = nullptr;
10338 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10339 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10340 OOLoc = BO->getOperatorLoc();
10341 LHS = BO->getLHS()->IgnoreParenImpCasts();
10342 RHS = BO->getRHS()->IgnoreParenImpCasts();
10343 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10344 OOK = OCE->getOperator();
10345 OOLoc = OCE->getOperatorLoc();
10346 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10347 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10348 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10349 OOK = MCE->getMethodDecl()
10350 ->getNameInfo()
10351 .getName()
10352 .getCXXOverloadedOperator();
10353 OOLoc = MCE->getCallee()->getExprLoc();
10354 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10355 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10356 }
10357 SourceLocation ELoc;
10358 SourceRange ERange;
10359 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10360 /*AllowArraySection=*/false);
10361 if (Res.second) {
10362 // It will be analyzed later.
10363 Vars.push_back(RefExpr);
10364 }
10365 ValueDecl *D = Res.first;
10366 if (!D)
10367 continue;
10368
10369 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10370 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10371 continue;
10372 }
10373 if (RHS) {
10374 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10375 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10376 if (RHSRes.isInvalid())
10377 continue;
10378 }
10379 if (!CurContext->isDependentContext() &&
10380 DSAStack->getParentOrderedRegionParam() &&
10381 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10382 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10383 << DSAStack->getParentLoopControlVariable(
10384 DepCounter.getZExtValue());
10385 continue;
10386 }
10387 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010388 } else {
10389 // OpenMP [2.11.1.1, Restrictions, p.3]
10390 // A variable that is part of another variable (such as a field of a
10391 // structure) but is not an array element or an array section cannot
10392 // appear in a depend clause.
10393 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10394 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10395 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10396 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10397 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010398 (ASE &&
10399 !ASE->getBase()
10400 ->getType()
10401 .getNonReferenceType()
10402 ->isPointerType() &&
10403 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010404 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10405 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010406 continue;
10407 }
10408 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010409 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10410 }
10411
10412 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10413 TotalDepCount > VarList.size() &&
10414 DSAStack->getParentOrderedRegionParam()) {
10415 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10416 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10417 }
10418 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10419 Vars.empty())
10420 return nullptr;
10421 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010422 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10423 DepKind, DepLoc, ColonLoc, Vars);
10424 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10425 DSAStack->addDoacrossDependClause(C, OpsOffs);
10426 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010427}
Michael Wonge710d542015-08-07 16:16:36 +000010428
10429OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10430 SourceLocation LParenLoc,
10431 SourceLocation EndLoc) {
10432 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010433
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010434 // OpenMP [2.9.1, Restrictions]
10435 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010436 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10437 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010438 return nullptr;
10439
Michael Wonge710d542015-08-07 16:16:36 +000010440 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10441}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010442
10443static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10444 DSAStackTy *Stack, CXXRecordDecl *RD) {
10445 if (!RD || RD->isInvalidDecl())
10446 return true;
10447
10448 auto QTy = SemaRef.Context.getRecordType(RD);
10449 if (RD->isDynamicClass()) {
10450 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10451 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10452 return false;
10453 }
10454 auto *DC = RD;
10455 bool IsCorrect = true;
10456 for (auto *I : DC->decls()) {
10457 if (I) {
10458 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10459 if (MD->isStatic()) {
10460 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10461 SemaRef.Diag(MD->getLocation(),
10462 diag::note_omp_static_member_in_target);
10463 IsCorrect = false;
10464 }
10465 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10466 if (VD->isStaticDataMember()) {
10467 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10468 SemaRef.Diag(VD->getLocation(),
10469 diag::note_omp_static_member_in_target);
10470 IsCorrect = false;
10471 }
10472 }
10473 }
10474 }
10475
10476 for (auto &I : RD->bases()) {
10477 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10478 I.getType()->getAsCXXRecordDecl()))
10479 IsCorrect = false;
10480 }
10481 return IsCorrect;
10482}
10483
10484static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10485 DSAStackTy *Stack, QualType QTy) {
10486 NamedDecl *ND;
10487 if (QTy->isIncompleteType(&ND)) {
10488 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10489 return false;
10490 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010491 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010492 return false;
10493 }
10494 return true;
10495}
10496
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010497/// \brief Return true if it can be proven that the provided array expression
10498/// (array section or array subscript) does NOT specify the whole size of the
10499/// array whose base type is \a BaseQTy.
10500static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10501 const Expr *E,
10502 QualType BaseQTy) {
10503 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10504
10505 // If this is an array subscript, it refers to the whole size if the size of
10506 // the dimension is constant and equals 1. Also, an array section assumes the
10507 // format of an array subscript if no colon is used.
10508 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10509 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10510 return ATy->getSize().getSExtValue() != 1;
10511 // Size can't be evaluated statically.
10512 return false;
10513 }
10514
10515 assert(OASE && "Expecting array section if not an array subscript.");
10516 auto *LowerBound = OASE->getLowerBound();
10517 auto *Length = OASE->getLength();
10518
10519 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010520 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010521 if (LowerBound) {
10522 llvm::APSInt ConstLowerBound;
10523 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10524 return false; // Can't get the integer value as a constant.
10525 if (ConstLowerBound.getSExtValue())
10526 return true;
10527 }
10528
10529 // If we don't have a length we covering the whole dimension.
10530 if (!Length)
10531 return false;
10532
10533 // If the base is a pointer, we don't have a way to get the size of the
10534 // pointee.
10535 if (BaseQTy->isPointerType())
10536 return false;
10537
10538 // We can only check if the length is the same as the size of the dimension
10539 // if we have a constant array.
10540 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10541 if (!CATy)
10542 return false;
10543
10544 llvm::APSInt ConstLength;
10545 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10546 return false; // Can't get the integer value as a constant.
10547
10548 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10549}
10550
10551// Return true if it can be proven that the provided array expression (array
10552// section or array subscript) does NOT specify a single element of the array
10553// whose base type is \a BaseQTy.
10554static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010555 const Expr *E,
10556 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010557 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10558
10559 // An array subscript always refer to a single element. Also, an array section
10560 // assumes the format of an array subscript if no colon is used.
10561 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10562 return false;
10563
10564 assert(OASE && "Expecting array section if not an array subscript.");
10565 auto *Length = OASE->getLength();
10566
10567 // If we don't have a length we have to check if the array has unitary size
10568 // for this dimension. Also, we should always expect a length if the base type
10569 // is pointer.
10570 if (!Length) {
10571 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10572 return ATy->getSize().getSExtValue() != 1;
10573 // We cannot assume anything.
10574 return false;
10575 }
10576
10577 // Check if the length evaluates to 1.
10578 llvm::APSInt ConstLength;
10579 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10580 return false; // Can't get the integer value as a constant.
10581
10582 return ConstLength.getSExtValue() != 1;
10583}
10584
Samuel Antao661c0902016-05-26 17:39:58 +000010585// Return the expression of the base of the mappable expression or null if it
10586// cannot be determined and do all the necessary checks to see if the expression
10587// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010588// components of the expression.
10589static Expr *CheckMapClauseExpressionBase(
10590 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010591 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10592 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010593 SourceLocation ELoc = E->getExprLoc();
10594 SourceRange ERange = E->getSourceRange();
10595
10596 // The base of elements of list in a map clause have to be either:
10597 // - a reference to variable or field.
10598 // - a member expression.
10599 // - an array expression.
10600 //
10601 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10602 // reference to 'r'.
10603 //
10604 // If we have:
10605 //
10606 // struct SS {
10607 // Bla S;
10608 // foo() {
10609 // #pragma omp target map (S.Arr[:12]);
10610 // }
10611 // }
10612 //
10613 // We want to retrieve the member expression 'this->S';
10614
10615 Expr *RelevantExpr = nullptr;
10616
Samuel Antao5de996e2016-01-22 20:21:36 +000010617 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10618 // If a list item is an array section, it must specify contiguous storage.
10619 //
10620 // For this restriction it is sufficient that we make sure only references
10621 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010622 // exist except in the rightmost expression (unless they cover the whole
10623 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010624 //
10625 // r.ArrS[3:5].Arr[6:7]
10626 //
10627 // r.ArrS[3:5].x
10628 //
10629 // but these would be valid:
10630 // r.ArrS[3].Arr[6:7]
10631 //
10632 // r.ArrS[3].x
10633
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010634 bool AllowUnitySizeArraySection = true;
10635 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010636
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010637 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010638 E = E->IgnoreParenImpCasts();
10639
10640 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10641 if (!isa<VarDecl>(CurE->getDecl()))
10642 break;
10643
10644 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010645
10646 // If we got a reference to a declaration, we should not expect any array
10647 // section before that.
10648 AllowUnitySizeArraySection = false;
10649 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010650
10651 // Record the component.
10652 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10653 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010654 continue;
10655 }
10656
10657 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10658 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10659
10660 if (isa<CXXThisExpr>(BaseE))
10661 // We found a base expression: this->Val.
10662 RelevantExpr = CurE;
10663 else
10664 E = BaseE;
10665
10666 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10667 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10668 << CurE->getSourceRange();
10669 break;
10670 }
10671
10672 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10673
10674 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10675 // A bit-field cannot appear in a map clause.
10676 //
10677 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010678 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10679 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010680 break;
10681 }
10682
10683 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10684 // If the type of a list item is a reference to a type T then the type
10685 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010686 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010687
10688 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10689 // A list item cannot be a variable that is a member of a structure with
10690 // a union type.
10691 //
10692 if (auto *RT = CurType->getAs<RecordType>())
10693 if (RT->isUnionType()) {
10694 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10695 << CurE->getSourceRange();
10696 break;
10697 }
10698
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010699 // If we got a member expression, we should not expect any array section
10700 // before that:
10701 //
10702 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10703 // If a list item is an element of a structure, only the rightmost symbol
10704 // of the variable reference can be an array section.
10705 //
10706 AllowUnitySizeArraySection = false;
10707 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010708
10709 // Record the component.
10710 CurComponents.push_back(
10711 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010712 continue;
10713 }
10714
10715 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10716 E = CurE->getBase()->IgnoreParenImpCasts();
10717
10718 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10719 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10720 << 0 << CurE->getSourceRange();
10721 break;
10722 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010723
10724 // If we got an array subscript that express the whole dimension we
10725 // can have any array expressions before. If it only expressing part of
10726 // the dimension, we can only have unitary-size array expressions.
10727 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10728 E->getType()))
10729 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010730
10731 // Record the component - we don't have any declaration associated.
10732 CurComponents.push_back(
10733 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010734 continue;
10735 }
10736
10737 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010738 E = CurE->getBase()->IgnoreParenImpCasts();
10739
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010740 auto CurType =
10741 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10742
Samuel Antao5de996e2016-01-22 20:21:36 +000010743 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10744 // If the type of a list item is a reference to a type T then the type
10745 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010746 if (CurType->isReferenceType())
10747 CurType = CurType->getPointeeType();
10748
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010749 bool IsPointer = CurType->isAnyPointerType();
10750
10751 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010752 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10753 << 0 << CurE->getSourceRange();
10754 break;
10755 }
10756
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010757 bool NotWhole =
10758 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10759 bool NotUnity =
10760 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10761
Samuel Antaodab51bb2016-07-18 23:22:11 +000010762 if (AllowWholeSizeArraySection) {
10763 // Any array section is currently allowed. Allowing a whole size array
10764 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010765 //
10766 // If this array section refers to the whole dimension we can still
10767 // accept other array sections before this one, except if the base is a
10768 // pointer. Otherwise, only unitary sections are accepted.
10769 if (NotWhole || IsPointer)
10770 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010771 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010772 // A unity or whole array section is not allowed and that is not
10773 // compatible with the properties of the current array section.
10774 SemaRef.Diag(
10775 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10776 << CurE->getSourceRange();
10777 break;
10778 }
Samuel Antao90927002016-04-26 14:54:23 +000010779
10780 // Record the component - we don't have any declaration associated.
10781 CurComponents.push_back(
10782 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010783 continue;
10784 }
10785
10786 // If nothing else worked, this is not a valid map clause expression.
10787 SemaRef.Diag(ELoc,
10788 diag::err_omp_expected_named_var_member_or_array_expression)
10789 << ERange;
10790 break;
10791 }
10792
10793 return RelevantExpr;
10794}
10795
10796// Return true if expression E associated with value VD has conflicts with other
10797// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010798static bool CheckMapConflicts(
10799 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10800 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010801 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10802 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010803 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010804 SourceLocation ELoc = E->getExprLoc();
10805 SourceRange ERange = E->getSourceRange();
10806
10807 // In order to easily check the conflicts we need to match each component of
10808 // the expression under test with the components of the expressions that are
10809 // already in the stack.
10810
Samuel Antao5de996e2016-01-22 20:21:36 +000010811 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010812 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010813 "Map clause expression with unexpected base!");
10814
10815 // Variables to help detecting enclosing problems in data environment nests.
10816 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010817 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010818
Samuel Antao90927002016-04-26 14:54:23 +000010819 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10820 VD, CurrentRegionOnly,
10821 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010822 StackComponents,
10823 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010824
Samuel Antao5de996e2016-01-22 20:21:36 +000010825 assert(!StackComponents.empty() &&
10826 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010827 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010828 "Map clause expression with unexpected base!");
10829
Samuel Antao90927002016-04-26 14:54:23 +000010830 // The whole expression in the stack.
10831 auto *RE = StackComponents.front().getAssociatedExpression();
10832
Samuel Antao5de996e2016-01-22 20:21:36 +000010833 // Expressions must start from the same base. Here we detect at which
10834 // point both expressions diverge from each other and see if we can
10835 // detect if the memory referred to both expressions is contiguous and
10836 // do not overlap.
10837 auto CI = CurComponents.rbegin();
10838 auto CE = CurComponents.rend();
10839 auto SI = StackComponents.rbegin();
10840 auto SE = StackComponents.rend();
10841 for (; CI != CE && SI != SE; ++CI, ++SI) {
10842
10843 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10844 // At most one list item can be an array item derived from a given
10845 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010846 if (CurrentRegionOnly &&
10847 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10848 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10849 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10850 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10851 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010852 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010853 << CI->getAssociatedExpression()->getSourceRange();
10854 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10855 diag::note_used_here)
10856 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010857 return true;
10858 }
10859
10860 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010861 if (CI->getAssociatedExpression()->getStmtClass() !=
10862 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010863 break;
10864
10865 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010866 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010867 break;
10868 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010869 // Check if the extra components of the expressions in the enclosing
10870 // data environment are redundant for the current base declaration.
10871 // If they are, the maps completely overlap, which is legal.
10872 for (; SI != SE; ++SI) {
10873 QualType Type;
10874 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010875 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010876 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010877 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10878 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010879 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10880 Type =
10881 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10882 }
10883 if (Type.isNull() || Type->isAnyPointerType() ||
10884 CheckArrayExpressionDoesNotReferToWholeSize(
10885 SemaRef, SI->getAssociatedExpression(), Type))
10886 break;
10887 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010888
10889 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10890 // List items of map clauses in the same construct must not share
10891 // original storage.
10892 //
10893 // If the expressions are exactly the same or one is a subset of the
10894 // other, it means they are sharing storage.
10895 if (CI == CE && SI == SE) {
10896 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010897 if (CKind == OMPC_map)
10898 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10899 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010900 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010901 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10902 << ERange;
10903 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010904 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10905 << RE->getSourceRange();
10906 return true;
10907 } else {
10908 // If we find the same expression in the enclosing data environment,
10909 // that is legal.
10910 IsEnclosedByDataEnvironmentExpr = true;
10911 return false;
10912 }
10913 }
10914
Samuel Antao90927002016-04-26 14:54:23 +000010915 QualType DerivedType =
10916 std::prev(CI)->getAssociatedDeclaration()->getType();
10917 SourceLocation DerivedLoc =
10918 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010919
10920 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10921 // If the type of a list item is a reference to a type T then the type
10922 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010923 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010924
10925 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10926 // A variable for which the type is pointer and an array section
10927 // derived from that variable must not appear as list items of map
10928 // clauses of the same construct.
10929 //
10930 // Also, cover one of the cases in:
10931 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10932 // If any part of the original storage of a list item has corresponding
10933 // storage in the device data environment, all of the original storage
10934 // must have corresponding storage in the device data environment.
10935 //
10936 if (DerivedType->isAnyPointerType()) {
10937 if (CI == CE || SI == SE) {
10938 SemaRef.Diag(
10939 DerivedLoc,
10940 diag::err_omp_pointer_mapped_along_with_derived_section)
10941 << DerivedLoc;
10942 } else {
10943 assert(CI != CE && SI != SE);
10944 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10945 << DerivedLoc;
10946 }
10947 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10948 << RE->getSourceRange();
10949 return true;
10950 }
10951
10952 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10953 // List items of map clauses in the same construct must not share
10954 // original storage.
10955 //
10956 // An expression is a subset of the other.
10957 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010958 if (CKind == OMPC_map)
10959 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10960 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010961 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010962 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10963 << ERange;
10964 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010965 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10966 << RE->getSourceRange();
10967 return true;
10968 }
10969
10970 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010971 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010972 if (!CurrentRegionOnly && SI != SE)
10973 EnclosingExpr = RE;
10974
10975 // The current expression is a subset of the expression in the data
10976 // environment.
10977 IsEnclosedByDataEnvironmentExpr |=
10978 (!CurrentRegionOnly && CI != CE && SI == SE);
10979
10980 return false;
10981 });
10982
10983 if (CurrentRegionOnly)
10984 return FoundError;
10985
10986 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10987 // If any part of the original storage of a list item has corresponding
10988 // storage in the device data environment, all of the original storage must
10989 // have corresponding storage in the device data environment.
10990 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10991 // If a list item is an element of a structure, and a different element of
10992 // the structure has a corresponding list item in the device data environment
10993 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010994 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010995 // data environment prior to the task encountering the construct.
10996 //
10997 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10998 SemaRef.Diag(ELoc,
10999 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11000 << ERange;
11001 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11002 << EnclosingExpr->getSourceRange();
11003 return true;
11004 }
11005
11006 return FoundError;
11007}
11008
Samuel Antao661c0902016-05-26 17:39:58 +000011009namespace {
11010// Utility struct that gathers all the related lists associated with a mappable
11011// expression.
11012struct MappableVarListInfo final {
11013 // The list of expressions.
11014 ArrayRef<Expr *> VarList;
11015 // The list of processed expressions.
11016 SmallVector<Expr *, 16> ProcessedVarList;
11017 // The mappble components for each expression.
11018 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11019 // The base declaration of the variable.
11020 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11021
11022 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11023 // We have a list of components and base declarations for each entry in the
11024 // variable list.
11025 VarComponents.reserve(VarList.size());
11026 VarBaseDeclarations.reserve(VarList.size());
11027 }
11028};
11029}
11030
11031// Check the validity of the provided variable list for the provided clause kind
11032// \a CKind. In the check process the valid expressions, and mappable expression
11033// components and variables are extracted and used to fill \a Vars,
11034// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11035// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11036static void
11037checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11038 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11039 SourceLocation StartLoc,
11040 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11041 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011042 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11043 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011044 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011045
Samuel Antao90927002016-04-26 14:54:23 +000011046 // Keep track of the mappable components and base declarations in this clause.
11047 // Each entry in the list is going to have a list of components associated. We
11048 // record each set of the components so that we can build the clause later on.
11049 // In the end we should have the same amount of declarations and component
11050 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011051
Samuel Antao661c0902016-05-26 17:39:58 +000011052 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011053 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011054 SourceLocation ELoc = RE->getExprLoc();
11055
Kelvin Li0bff7af2015-11-23 05:32:03 +000011056 auto *VE = RE->IgnoreParenLValueCasts();
11057
11058 if (VE->isValueDependent() || VE->isTypeDependent() ||
11059 VE->isInstantiationDependent() ||
11060 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011061 // We can only analyze this information once the missing information is
11062 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011063 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011064 continue;
11065 }
11066
11067 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011068
Samuel Antao5de996e2016-01-22 20:21:36 +000011069 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011070 SemaRef.Diag(ELoc,
11071 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011072 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011073 continue;
11074 }
11075
Samuel Antao90927002016-04-26 14:54:23 +000011076 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11077 ValueDecl *CurDeclaration = nullptr;
11078
11079 // Obtain the array or member expression bases if required. Also, fill the
11080 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011081 auto *BE =
11082 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011083 if (!BE)
11084 continue;
11085
Samuel Antao90927002016-04-26 14:54:23 +000011086 assert(!CurComponents.empty() &&
11087 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011088
Samuel Antao90927002016-04-26 14:54:23 +000011089 // For the following checks, we rely on the base declaration which is
11090 // expected to be associated with the last component. The declaration is
11091 // expected to be a variable or a field (if 'this' is being mapped).
11092 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11093 assert(CurDeclaration && "Null decl on map clause.");
11094 assert(
11095 CurDeclaration->isCanonicalDecl() &&
11096 "Expecting components to have associated only canonical declarations.");
11097
11098 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11099 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011100
11101 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011102 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011103
11104 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011105 // threadprivate variables cannot appear in a map clause.
11106 // OpenMP 4.5 [2.10.5, target update Construct]
11107 // threadprivate variables cannot appear in a from clause.
11108 if (VD && DSAS->isThreadPrivate(VD)) {
11109 auto DVar = DSAS->getTopDSA(VD, false);
11110 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11111 << getOpenMPClauseName(CKind);
11112 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011113 continue;
11114 }
11115
Samuel Antao5de996e2016-01-22 20:21:36 +000011116 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11117 // A list item cannot appear in both a map clause and a data-sharing
11118 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011119
Samuel Antao5de996e2016-01-22 20:21:36 +000011120 // Check conflicts with other map clause expressions. We check the conflicts
11121 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011122 // environment, because the restrictions are different. We only have to
11123 // check conflicts across regions for the map clauses.
11124 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11125 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011126 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011127 if (CKind == OMPC_map &&
11128 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11129 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011130 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011131
Samuel Antao661c0902016-05-26 17:39:58 +000011132 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011133 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11134 // If the type of a list item is a reference to a type T then the type will
11135 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011136 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011137
Samuel Antao661c0902016-05-26 17:39:58 +000011138 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11139 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011140 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011141 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011142 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11143 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011144 continue;
11145
Samuel Antao661c0902016-05-26 17:39:58 +000011146 if (CKind == OMPC_map) {
11147 // target enter data
11148 // OpenMP [2.10.2, Restrictions, p. 99]
11149 // A map-type must be specified in all map clauses and must be either
11150 // to or alloc.
11151 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11152 if (DKind == OMPD_target_enter_data &&
11153 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11154 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11155 << (IsMapTypeImplicit ? 1 : 0)
11156 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11157 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011158 continue;
11159 }
Samuel Antao661c0902016-05-26 17:39:58 +000011160
11161 // target exit_data
11162 // OpenMP [2.10.3, Restrictions, p. 102]
11163 // A map-type must be specified in all map clauses and must be either
11164 // from, release, or delete.
11165 if (DKind == OMPD_target_exit_data &&
11166 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11167 MapType == OMPC_MAP_delete)) {
11168 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11169 << (IsMapTypeImplicit ? 1 : 0)
11170 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11171 << getOpenMPDirectiveName(DKind);
11172 continue;
11173 }
11174
11175 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11176 // A list item cannot appear in both a map clause and a data-sharing
11177 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011178 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011179 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011180 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011181 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11182 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011183 auto DVar = DSAS->getTopDSA(VD, false);
11184 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011185 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011186 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011187 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011188 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11189 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11190 continue;
11191 }
11192 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011193 }
11194
Samuel Antao90927002016-04-26 14:54:23 +000011195 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011196 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011197
11198 // Store the components in the stack so that they can be used to check
11199 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011200 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11201 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011202
11203 // Save the components and declaration to create the clause. For purposes of
11204 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011205 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011206 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11207 MVLI.VarComponents.back().append(CurComponents.begin(),
11208 CurComponents.end());
11209 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11210 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011211 }
Samuel Antao661c0902016-05-26 17:39:58 +000011212}
11213
11214OMPClause *
11215Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11216 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11217 SourceLocation MapLoc, SourceLocation ColonLoc,
11218 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11219 SourceLocation LParenLoc, SourceLocation EndLoc) {
11220 MappableVarListInfo MVLI(VarList);
11221 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11222 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011223
Samuel Antao5de996e2016-01-22 20:21:36 +000011224 // We need to produce a map clause even if we don't have variables so that
11225 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011226 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11227 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11228 MVLI.VarComponents, MapTypeModifier, MapType,
11229 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011230}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011231
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011232QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11233 TypeResult ParsedType) {
11234 assert(ParsedType.isUsable());
11235
11236 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11237 if (ReductionType.isNull())
11238 return QualType();
11239
11240 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11241 // A type name in a declare reduction directive cannot be a function type, an
11242 // array type, a reference type, or a type qualified with const, volatile or
11243 // restrict.
11244 if (ReductionType.hasQualifiers()) {
11245 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11246 return QualType();
11247 }
11248
11249 if (ReductionType->isFunctionType()) {
11250 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11251 return QualType();
11252 }
11253 if (ReductionType->isReferenceType()) {
11254 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11255 return QualType();
11256 }
11257 if (ReductionType->isArrayType()) {
11258 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11259 return QualType();
11260 }
11261 return ReductionType;
11262}
11263
11264Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11265 Scope *S, DeclContext *DC, DeclarationName Name,
11266 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11267 AccessSpecifier AS, Decl *PrevDeclInScope) {
11268 SmallVector<Decl *, 8> Decls;
11269 Decls.reserve(ReductionTypes.size());
11270
11271 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11272 ForRedeclaration);
11273 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11274 // A reduction-identifier may not be re-declared in the current scope for the
11275 // same type or for a type that is compatible according to the base language
11276 // rules.
11277 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11278 OMPDeclareReductionDecl *PrevDRD = nullptr;
11279 bool InCompoundScope = true;
11280 if (S != nullptr) {
11281 // Find previous declaration with the same name not referenced in other
11282 // declarations.
11283 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11284 InCompoundScope =
11285 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11286 LookupName(Lookup, S);
11287 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11288 /*AllowInlineNamespace=*/false);
11289 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11290 auto Filter = Lookup.makeFilter();
11291 while (Filter.hasNext()) {
11292 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11293 if (InCompoundScope) {
11294 auto I = UsedAsPrevious.find(PrevDecl);
11295 if (I == UsedAsPrevious.end())
11296 UsedAsPrevious[PrevDecl] = false;
11297 if (auto *D = PrevDecl->getPrevDeclInScope())
11298 UsedAsPrevious[D] = true;
11299 }
11300 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11301 PrevDecl->getLocation();
11302 }
11303 Filter.done();
11304 if (InCompoundScope) {
11305 for (auto &PrevData : UsedAsPrevious) {
11306 if (!PrevData.second) {
11307 PrevDRD = PrevData.first;
11308 break;
11309 }
11310 }
11311 }
11312 } else if (PrevDeclInScope != nullptr) {
11313 auto *PrevDRDInScope = PrevDRD =
11314 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11315 do {
11316 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11317 PrevDRDInScope->getLocation();
11318 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11319 } while (PrevDRDInScope != nullptr);
11320 }
11321 for (auto &TyData : ReductionTypes) {
11322 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11323 bool Invalid = false;
11324 if (I != PreviousRedeclTypes.end()) {
11325 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11326 << TyData.first;
11327 Diag(I->second, diag::note_previous_definition);
11328 Invalid = true;
11329 }
11330 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11331 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11332 Name, TyData.first, PrevDRD);
11333 DC->addDecl(DRD);
11334 DRD->setAccess(AS);
11335 Decls.push_back(DRD);
11336 if (Invalid)
11337 DRD->setInvalidDecl();
11338 else
11339 PrevDRD = DRD;
11340 }
11341
11342 return DeclGroupPtrTy::make(
11343 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11344}
11345
11346void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11347 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11348
11349 // Enter new function scope.
11350 PushFunctionScope();
11351 getCurFunction()->setHasBranchProtectedScope();
11352 getCurFunction()->setHasOMPDeclareReductionCombiner();
11353
11354 if (S != nullptr)
11355 PushDeclContext(S, DRD);
11356 else
11357 CurContext = DRD;
11358
Faisal Valid143a0c2017-04-01 21:30:49 +000011359 PushExpressionEvaluationContext(
11360 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011361
11362 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011363 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11364 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11365 // uses semantics of argument handles by value, but it should be passed by
11366 // reference. C lang does not support references, so pass all parameters as
11367 // pointers.
11368 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011369 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011370 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011371 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11372 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11373 // uses semantics of argument handles by value, but it should be passed by
11374 // reference. C lang does not support references, so pass all parameters as
11375 // pointers.
11376 // Create 'T omp_out;' variable.
11377 auto *OmpOutParm =
11378 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11379 if (S != nullptr) {
11380 PushOnScopeChains(OmpInParm, S);
11381 PushOnScopeChains(OmpOutParm, S);
11382 } else {
11383 DRD->addDecl(OmpInParm);
11384 DRD->addDecl(OmpOutParm);
11385 }
11386}
11387
11388void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11389 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11390 DiscardCleanupsInEvaluationContext();
11391 PopExpressionEvaluationContext();
11392
11393 PopDeclContext();
11394 PopFunctionScopeInfo();
11395
11396 if (Combiner != nullptr)
11397 DRD->setCombiner(Combiner);
11398 else
11399 DRD->setInvalidDecl();
11400}
11401
11402void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11403 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11404
11405 // Enter new function scope.
11406 PushFunctionScope();
11407 getCurFunction()->setHasBranchProtectedScope();
11408
11409 if (S != nullptr)
11410 PushDeclContext(S, DRD);
11411 else
11412 CurContext = DRD;
11413
Faisal Valid143a0c2017-04-01 21:30:49 +000011414 PushExpressionEvaluationContext(
11415 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011416
11417 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011418 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11419 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11420 // uses semantics of argument handles by value, but it should be passed by
11421 // reference. C lang does not support references, so pass all parameters as
11422 // pointers.
11423 // Create 'T omp_priv;' variable.
11424 auto *OmpPrivParm =
11425 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011426 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11427 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11428 // uses semantics of argument handles by value, but it should be passed by
11429 // reference. C lang does not support references, so pass all parameters as
11430 // pointers.
11431 // Create 'T omp_orig;' variable.
11432 auto *OmpOrigParm =
11433 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011434 if (S != nullptr) {
11435 PushOnScopeChains(OmpPrivParm, S);
11436 PushOnScopeChains(OmpOrigParm, S);
11437 } else {
11438 DRD->addDecl(OmpPrivParm);
11439 DRD->addDecl(OmpOrigParm);
11440 }
11441}
11442
11443void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11444 Expr *Initializer) {
11445 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11446 DiscardCleanupsInEvaluationContext();
11447 PopExpressionEvaluationContext();
11448
11449 PopDeclContext();
11450 PopFunctionScopeInfo();
11451
11452 if (Initializer != nullptr)
11453 DRD->setInitializer(Initializer);
11454 else
11455 DRD->setInvalidDecl();
11456}
11457
11458Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11459 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11460 for (auto *D : DeclReductions.get()) {
11461 if (IsValid) {
11462 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11463 if (S != nullptr)
11464 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11465 } else
11466 D->setInvalidDecl();
11467 }
11468 return DeclReductions;
11469}
11470
David Majnemer9d168222016-08-05 17:44:54 +000011471OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011472 SourceLocation StartLoc,
11473 SourceLocation LParenLoc,
11474 SourceLocation EndLoc) {
11475 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011476 Stmt *HelperValStmt = nullptr;
11477 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011478
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011479 // OpenMP [teams Constrcut, Restrictions]
11480 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011481 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11482 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011483 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011484
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011485 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11486 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11487 if (CaptureRegion != OMPD_unknown) {
11488 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11489 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11490 HelperValStmt = buildPreInits(Context, Captures);
11491 }
11492
11493 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11494 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011495}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011496
11497OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11498 SourceLocation StartLoc,
11499 SourceLocation LParenLoc,
11500 SourceLocation EndLoc) {
11501 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011502 Stmt *HelperValStmt = nullptr;
11503 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011504
11505 // OpenMP [teams Constrcut, Restrictions]
11506 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011507 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11508 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011509 return nullptr;
11510
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011511 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11512 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11513 if (CaptureRegion != OMPD_unknown) {
11514 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11515 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11516 HelperValStmt = buildPreInits(Context, Captures);
11517 }
11518
11519 return new (Context) OMPThreadLimitClause(
11520 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011521}
Alexey Bataeva0569352015-12-01 10:17:31 +000011522
11523OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11524 SourceLocation StartLoc,
11525 SourceLocation LParenLoc,
11526 SourceLocation EndLoc) {
11527 Expr *ValExpr = Priority;
11528
11529 // OpenMP [2.9.1, task Constrcut]
11530 // The priority-value is a non-negative numerical scalar expression.
11531 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11532 /*StrictlyPositive=*/false))
11533 return nullptr;
11534
11535 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11536}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011537
11538OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11539 SourceLocation StartLoc,
11540 SourceLocation LParenLoc,
11541 SourceLocation EndLoc) {
11542 Expr *ValExpr = Grainsize;
11543
11544 // OpenMP [2.9.2, taskloop Constrcut]
11545 // The parameter of the grainsize clause must be a positive integer
11546 // expression.
11547 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11548 /*StrictlyPositive=*/true))
11549 return nullptr;
11550
11551 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11552}
Alexey Bataev382967a2015-12-08 12:06:20 +000011553
11554OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11555 SourceLocation StartLoc,
11556 SourceLocation LParenLoc,
11557 SourceLocation EndLoc) {
11558 Expr *ValExpr = NumTasks;
11559
11560 // OpenMP [2.9.2, taskloop Constrcut]
11561 // The parameter of the num_tasks clause must be a positive integer
11562 // expression.
11563 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11564 /*StrictlyPositive=*/true))
11565 return nullptr;
11566
11567 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11568}
11569
Alexey Bataev28c75412015-12-15 08:19:24 +000011570OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11571 SourceLocation LParenLoc,
11572 SourceLocation EndLoc) {
11573 // OpenMP [2.13.2, critical construct, Description]
11574 // ... where hint-expression is an integer constant expression that evaluates
11575 // to a valid lock hint.
11576 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11577 if (HintExpr.isInvalid())
11578 return nullptr;
11579 return new (Context)
11580 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11581}
11582
Carlo Bertollib4adf552016-01-15 18:50:31 +000011583OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11584 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11585 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11586 SourceLocation EndLoc) {
11587 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11588 std::string Values;
11589 Values += "'";
11590 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11591 Values += "'";
11592 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11593 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11594 return nullptr;
11595 }
11596 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011597 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011598 if (ChunkSize) {
11599 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11600 !ChunkSize->isInstantiationDependent() &&
11601 !ChunkSize->containsUnexpandedParameterPack()) {
11602 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11603 ExprResult Val =
11604 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11605 if (Val.isInvalid())
11606 return nullptr;
11607
11608 ValExpr = Val.get();
11609
11610 // OpenMP [2.7.1, Restrictions]
11611 // chunk_size must be a loop invariant integer expression with a positive
11612 // value.
11613 llvm::APSInt Result;
11614 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11615 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11616 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11617 << "dist_schedule" << ChunkSize->getSourceRange();
11618 return nullptr;
11619 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011620 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11621 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011622 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11623 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11624 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011625 }
11626 }
11627 }
11628
11629 return new (Context)
11630 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011631 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011632}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011633
11634OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11635 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11636 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11637 SourceLocation KindLoc, SourceLocation EndLoc) {
11638 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011639 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011640 std::string Value;
11641 SourceLocation Loc;
11642 Value += "'";
11643 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11644 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011645 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011646 Loc = MLoc;
11647 } else {
11648 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011649 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011650 Loc = KindLoc;
11651 }
11652 Value += "'";
11653 Diag(Loc, diag::err_omp_unexpected_clause_value)
11654 << Value << getOpenMPClauseName(OMPC_defaultmap);
11655 return nullptr;
11656 }
11657
11658 return new (Context)
11659 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11660}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011661
11662bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11663 DeclContext *CurLexicalContext = getCurLexicalContext();
11664 if (!CurLexicalContext->isFileContext() &&
11665 !CurLexicalContext->isExternCContext() &&
11666 !CurLexicalContext->isExternCXXContext()) {
11667 Diag(Loc, diag::err_omp_region_not_file_context);
11668 return false;
11669 }
11670 if (IsInOpenMPDeclareTargetContext) {
11671 Diag(Loc, diag::err_omp_enclosed_declare_target);
11672 return false;
11673 }
11674
11675 IsInOpenMPDeclareTargetContext = true;
11676 return true;
11677}
11678
11679void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11680 assert(IsInOpenMPDeclareTargetContext &&
11681 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11682
11683 IsInOpenMPDeclareTargetContext = false;
11684}
11685
David Majnemer9d168222016-08-05 17:44:54 +000011686void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11687 CXXScopeSpec &ScopeSpec,
11688 const DeclarationNameInfo &Id,
11689 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11690 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011691 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11692 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11693
11694 if (Lookup.isAmbiguous())
11695 return;
11696 Lookup.suppressDiagnostics();
11697
11698 if (!Lookup.isSingleResult()) {
11699 if (TypoCorrection Corrected =
11700 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11701 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11702 CTK_ErrorRecovery)) {
11703 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11704 << Id.getName());
11705 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11706 return;
11707 }
11708
11709 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11710 return;
11711 }
11712
11713 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11714 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11715 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11716 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11717
11718 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11719 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11720 ND->addAttr(A);
11721 if (ASTMutationListener *ML = Context.getASTMutationListener())
11722 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11723 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11724 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11725 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11726 << Id.getName();
11727 }
11728 } else
11729 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11730}
11731
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011732static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11733 Sema &SemaRef, Decl *D) {
11734 if (!D)
11735 return;
11736 Decl *LD = nullptr;
11737 if (isa<TagDecl>(D)) {
11738 LD = cast<TagDecl>(D)->getDefinition();
11739 } else if (isa<VarDecl>(D)) {
11740 LD = cast<VarDecl>(D)->getDefinition();
11741
11742 // If this is an implicit variable that is legal and we do not need to do
11743 // anything.
11744 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011745 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11746 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11747 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011748 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011749 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011750 return;
11751 }
11752
11753 } else if (isa<FunctionDecl>(D)) {
11754 const FunctionDecl *FD = nullptr;
11755 if (cast<FunctionDecl>(D)->hasBody(FD))
11756 LD = const_cast<FunctionDecl *>(FD);
11757
11758 // If the definition is associated with the current declaration in the
11759 // target region (it can be e.g. a lambda) that is legal and we do not need
11760 // to do anything else.
11761 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011762 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11763 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11764 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011765 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011766 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011767 return;
11768 }
11769 }
11770 if (!LD)
11771 LD = D;
11772 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11773 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11774 // Outlined declaration is not declared target.
11775 if (LD->isOutOfLine()) {
11776 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11777 SemaRef.Diag(SL, diag::note_used_here) << SR;
11778 } else {
11779 DeclContext *DC = LD->getDeclContext();
11780 while (DC) {
11781 if (isa<FunctionDecl>(DC) &&
11782 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11783 break;
11784 DC = DC->getParent();
11785 }
11786 if (DC)
11787 return;
11788
11789 // Is not declared in target context.
11790 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11791 SemaRef.Diag(SL, diag::note_used_here) << SR;
11792 }
11793 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011794 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11795 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11796 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011797 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011798 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011799 }
11800}
11801
11802static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11803 Sema &SemaRef, DSAStackTy *Stack,
11804 ValueDecl *VD) {
11805 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11806 return true;
11807 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11808 return false;
11809 return true;
11810}
11811
11812void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11813 if (!D || D->isInvalidDecl())
11814 return;
11815 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11816 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11817 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11818 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11819 if (DSAStack->isThreadPrivate(VD)) {
11820 Diag(SL, diag::err_omp_threadprivate_in_target);
11821 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11822 return;
11823 }
11824 }
11825 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11826 // Problem if any with var declared with incomplete type will be reported
11827 // as normal, so no need to check it here.
11828 if ((E || !VD->getType()->isIncompleteType()) &&
11829 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11830 // Mark decl as declared target to prevent further diagnostic.
11831 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011832 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11833 Context, OMPDeclareTargetDeclAttr::MT_To);
11834 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011835 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011836 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011837 }
11838 return;
11839 }
11840 }
11841 if (!E) {
11842 // Checking declaration inside declare target region.
11843 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11844 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011845 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11846 Context, OMPDeclareTargetDeclAttr::MT_To);
11847 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011848 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011849 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011850 }
11851 return;
11852 }
11853 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11854}
Samuel Antao661c0902016-05-26 17:39:58 +000011855
11856OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11857 SourceLocation StartLoc,
11858 SourceLocation LParenLoc,
11859 SourceLocation EndLoc) {
11860 MappableVarListInfo MVLI(VarList);
11861 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11862 if (MVLI.ProcessedVarList.empty())
11863 return nullptr;
11864
11865 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11866 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11867 MVLI.VarComponents);
11868}
Samuel Antaoec172c62016-05-26 17:49:04 +000011869
11870OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11871 SourceLocation StartLoc,
11872 SourceLocation LParenLoc,
11873 SourceLocation EndLoc) {
11874 MappableVarListInfo MVLI(VarList);
11875 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11876 if (MVLI.ProcessedVarList.empty())
11877 return nullptr;
11878
11879 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11880 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11881 MVLI.VarComponents);
11882}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011883
11884OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11885 SourceLocation StartLoc,
11886 SourceLocation LParenLoc,
11887 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011888 MappableVarListInfo MVLI(VarList);
11889 SmallVector<Expr *, 8> PrivateCopies;
11890 SmallVector<Expr *, 8> Inits;
11891
Carlo Bertolli2404b172016-07-13 15:37:16 +000011892 for (auto &RefExpr : VarList) {
11893 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11894 SourceLocation ELoc;
11895 SourceRange ERange;
11896 Expr *SimpleRefExpr = RefExpr;
11897 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11898 if (Res.second) {
11899 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011900 MVLI.ProcessedVarList.push_back(RefExpr);
11901 PrivateCopies.push_back(nullptr);
11902 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011903 }
11904 ValueDecl *D = Res.first;
11905 if (!D)
11906 continue;
11907
11908 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011909 Type = Type.getNonReferenceType().getUnqualifiedType();
11910
11911 auto *VD = dyn_cast<VarDecl>(D);
11912
11913 // Item should be a pointer or reference to pointer.
11914 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011915 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11916 << 0 << RefExpr->getSourceRange();
11917 continue;
11918 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011919
11920 // Build the private variable and the expression that refers to it.
11921 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11922 D->hasAttrs() ? &D->getAttrs() : nullptr);
11923 if (VDPrivate->isInvalidDecl())
11924 continue;
11925
11926 CurContext->addDecl(VDPrivate);
11927 auto VDPrivateRefExpr = buildDeclRefExpr(
11928 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11929
11930 // Add temporary variable to initialize the private copy of the pointer.
11931 auto *VDInit =
11932 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11933 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11934 RefExpr->getExprLoc());
11935 AddInitializerToDecl(VDPrivate,
11936 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011937 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011938
11939 // If required, build a capture to implement the privatization initialized
11940 // with the current list item value.
11941 DeclRefExpr *Ref = nullptr;
11942 if (!VD)
11943 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11944 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11945 PrivateCopies.push_back(VDPrivateRefExpr);
11946 Inits.push_back(VDInitRefExpr);
11947
11948 // We need to add a data sharing attribute for this variable to make sure it
11949 // is correctly captured. A variable that shows up in a use_device_ptr has
11950 // similar properties of a first private variable.
11951 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11952
11953 // Create a mappable component for the list item. List items in this clause
11954 // only need a component.
11955 MVLI.VarBaseDeclarations.push_back(D);
11956 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11957 MVLI.VarComponents.back().push_back(
11958 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011959 }
11960
Samuel Antaocc10b852016-07-28 14:23:26 +000011961 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011962 return nullptr;
11963
Samuel Antaocc10b852016-07-28 14:23:26 +000011964 return OMPUseDevicePtrClause::Create(
11965 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11966 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011967}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011968
11969OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11970 SourceLocation StartLoc,
11971 SourceLocation LParenLoc,
11972 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011973 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011974 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011975 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011976 SourceLocation ELoc;
11977 SourceRange ERange;
11978 Expr *SimpleRefExpr = RefExpr;
11979 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11980 if (Res.second) {
11981 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011982 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011983 }
11984 ValueDecl *D = Res.first;
11985 if (!D)
11986 continue;
11987
11988 QualType Type = D->getType();
11989 // item should be a pointer or array or reference to pointer or array
11990 if (!Type.getNonReferenceType()->isPointerType() &&
11991 !Type.getNonReferenceType()->isArrayType()) {
11992 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11993 << 0 << RefExpr->getSourceRange();
11994 continue;
11995 }
Samuel Antao6890b092016-07-28 14:25:09 +000011996
11997 // Check if the declaration in the clause does not show up in any data
11998 // sharing attribute.
11999 auto DVar = DSAStack->getTopDSA(D, false);
12000 if (isOpenMPPrivate(DVar.CKind)) {
12001 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12002 << getOpenMPClauseName(DVar.CKind)
12003 << getOpenMPClauseName(OMPC_is_device_ptr)
12004 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12005 ReportOriginalDSA(*this, DSAStack, D, DVar);
12006 continue;
12007 }
12008
12009 Expr *ConflictExpr;
12010 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012011 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012012 [&ConflictExpr](
12013 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12014 OpenMPClauseKind) -> bool {
12015 ConflictExpr = R.front().getAssociatedExpression();
12016 return true;
12017 })) {
12018 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12019 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12020 << ConflictExpr->getSourceRange();
12021 continue;
12022 }
12023
12024 // Store the components in the stack so that they can be used to check
12025 // against other clauses later on.
12026 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12027 DSAStack->addMappableExpressionComponents(
12028 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12029
12030 // Record the expression we've just processed.
12031 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12032
12033 // Create a mappable component for the list item. List items in this clause
12034 // only need a component. We use a null declaration to signal fields in
12035 // 'this'.
12036 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12037 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12038 "Unexpected device pointer expression!");
12039 MVLI.VarBaseDeclarations.push_back(
12040 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12041 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12042 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012043 }
12044
Samuel Antao6890b092016-07-28 14:25:09 +000012045 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012046 return nullptr;
12047
Samuel Antao6890b092016-07-28 14:25:09 +000012048 return OMPIsDevicePtrClause::Create(
12049 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12050 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012051}