blob: 76141afd595a9fb875c1272d3d5a0b183609f4f7 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
142 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000143 bool NowaitRegion = false;
144 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000145 bool LoopStart = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000146 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000147 /// Reference to the taskgroup task_reduction reference expression.
148 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000149 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeved09d242014-05-28 05:53:51 +0000150 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000151 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000152 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
153 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000154 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000155 };
156
Alexey Bataeve3727102018-04-18 15:57:46 +0000157 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000159 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000160 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000161 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
162 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000163 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000164 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000165 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000166 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000167 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000168 /// true if all the vaiables in the target executable directives must be
169 /// captured by reference.
170 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000171 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000172
Alexey Bataeve3727102018-04-18 15:57:46 +0000173 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000174
Alexey Bataeve3727102018-04-18 15:57:46 +0000175 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000178 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000179
Alexey Bataev4b465392017-04-26 15:06:24 +0000180 bool isStackEmpty() const {
181 return Stack.empty() ||
182 Stack.back().second != CurrentNonCapturingFunctionScope ||
183 Stack.back().first.empty();
184 }
185
Kelvin Li1408f912018-09-26 04:28:39 +0000186 /// Vector of previously declared requires directives
187 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
188
Alexey Bataev758e55e2013-09-06 18:03:48 +0000189public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000190 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000191
Alexey Bataevaac108a2015-06-23 04:51:00 +0000192 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000193 OpenMPClauseKind getClauseParsingMode() const {
194 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
195 return ClauseKindMode;
196 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000197 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000199 bool isForceVarCapturing() const { return ForceCapturing; }
200 void setForceVarCapturing(bool V) { ForceCapturing = V; }
201
Alexey Bataev60705422018-10-30 15:50:12 +0000202 void setForceCaptureByReferenceInTargetExecutable(bool V) {
203 ForceCaptureByReferenceInTargetExecutable = V;
204 }
205 bool isForceCaptureByReferenceInTargetExecutable() const {
206 return ForceCaptureByReferenceInTargetExecutable;
207 }
208
Alexey Bataev758e55e2013-09-06 18:03:48 +0000209 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000210 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000211 if (Stack.empty() ||
212 Stack.back().second != CurrentNonCapturingFunctionScope)
213 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
214 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
215 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000216 }
217
218 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000219 assert(!Stack.back().first.empty() &&
220 "Data-sharing attributes stack is empty!");
221 Stack.back().first.pop_back();
222 }
223
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000224 /// Marks that we're started loop parsing.
225 void loopInit() {
226 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
227 "Expected loop-based directive.");
228 Stack.back().first.back().LoopStart = true;
229 }
230 /// Start capturing of the variables in the loop context.
231 void loopStart() {
232 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
233 "Expected loop-based directive.");
234 Stack.back().first.back().LoopStart = false;
235 }
236 /// true, if variables are captured, false otherwise.
237 bool isLoopStarted() const {
238 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
239 "Expected loop-based directive.");
240 return !Stack.back().first.back().LoopStart;
241 }
242 /// Marks (or clears) declaration as possibly loop counter.
243 void resetPossibleLoopCounter(const Decl *D = nullptr) {
244 Stack.back().first.back().PossiblyLoopCounter =
245 D ? D->getCanonicalDecl() : D;
246 }
247 /// Gets the possible loop counter decl.
248 const Decl *getPossiblyLoopCunter() const {
249 return Stack.back().first.back().PossiblyLoopCounter;
250 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000251 /// Start new OpenMP region stack in new non-capturing function.
252 void pushFunction() {
253 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
254 assert(!isa<CapturingScopeInfo>(CurFnScope));
255 CurrentNonCapturingFunctionScope = CurFnScope;
256 }
257 /// Pop region stack for non-capturing function.
258 void popFunction(const FunctionScopeInfo *OldFSI) {
259 if (!Stack.empty() && Stack.back().second == OldFSI) {
260 assert(Stack.back().first.empty());
261 Stack.pop_back();
262 }
263 CurrentNonCapturingFunctionScope = nullptr;
264 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
265 if (!isa<CapturingScopeInfo>(FSI)) {
266 CurrentNonCapturingFunctionScope = FSI;
267 break;
268 }
269 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000270 }
271
Alexey Bataeve3727102018-04-18 15:57:46 +0000272 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000273 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000274 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000275 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000276 getCriticalWithHint(const DeclarationNameInfo &Name) const {
277 auto I = Criticals.find(Name.getAsString());
278 if (I != Criticals.end())
279 return I->second;
280 return std::make_pair(nullptr, llvm::APSInt());
281 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000282 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000283 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000284 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000285 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000287 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000288 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000289 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000290 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000291 /// \return The index of the loop control variable in the list of associated
292 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000293 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000294 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000295 /// parent region.
296 /// \return The index of the loop control variable in the list of associated
297 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000298 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000300 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000301 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000303 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000304 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000305 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000306
Alexey Bataevfa312f32017-07-21 18:48:21 +0000307 /// Adds additional information for the reduction items with the reduction id
308 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000309 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000310 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000311 /// Adds additional information for the reduction items with the reduction id
312 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000313 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000314 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000315 /// Returns the location and reduction operation from the innermost parent
316 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000317 const DSAVarData
318 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
319 BinaryOperatorKind &BOK,
320 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000321 /// Returns the location and reduction operation from the innermost parent
322 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000323 const DSAVarData
324 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
325 const Expr *&ReductionRef,
326 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000327 /// Return reduction reference expression for the current taskgroup.
328 Expr *getTaskgroupReductionRef() const {
329 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
330 "taskgroup reference expression requested for non taskgroup "
331 "directive.");
332 return Stack.back().first.back().TaskgroupReductionRef;
333 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000334 /// Checks if the given \p VD declaration is actually a taskgroup reduction
335 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000336 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000337 return Stack.back().first[Level].TaskgroupReductionRef &&
338 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
339 ->getDecl() == VD;
340 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000341
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000342 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000344 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000345 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000346 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000347 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000348 /// match specified \a CPred predicate in any directive which matches \a DPred
349 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000350 const DSAVarData
351 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
352 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
353 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000354 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000355 /// match specified \a CPred predicate in any innermost directive which
356 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000357 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000358 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000359 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
360 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000361 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000362 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000363 /// attributes which match specified \a CPred predicate at the specified
364 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000365 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000366 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000367 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000369 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000370 /// specified \a DPred predicate.
371 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000372 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000373 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000375 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000376 bool hasDirective(
377 const llvm::function_ref<bool(
378 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
379 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000380 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000383 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000385 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000386 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000387 OpenMPDirectiveKind getDirective(unsigned Level) const {
388 assert(!isStackEmpty() && "No directive at specified level.");
389 return Stack.back().first[Level].Directive;
390 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000391 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000392 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000393 if (isStackEmpty() || Stack.back().first.size() == 1)
394 return OMPD_unknown;
395 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000396 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000397
Kelvin Li1408f912018-09-26 04:28:39 +0000398 /// Add requires decl to internal vector
399 void addRequiresDecl(OMPRequiresDecl *RD) {
400 RequiresDecls.push_back(RD);
401 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402
Kelvin Li1408f912018-09-26 04:28:39 +0000403 /// Checks for a duplicate clause amongst previously declared requires
404 /// directives
405 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
406 bool IsDuplicate = false;
407 for (OMPClause *CNew : ClauseList) {
408 for (const OMPRequiresDecl *D : RequiresDecls) {
409 for (const OMPClause *CPrev : D->clauselists()) {
410 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
411 SemaRef.Diag(CNew->getBeginLoc(),
412 diag::err_omp_requires_clause_redeclaration)
413 << getOpenMPClauseName(CNew->getClauseKind());
414 SemaRef.Diag(CPrev->getBeginLoc(),
415 diag::note_omp_requires_previous_clause)
416 << getOpenMPClauseName(CPrev->getClauseKind());
417 IsDuplicate = true;
418 }
419 }
420 }
421 }
422 return IsDuplicate;
423 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000425 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000426 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 assert(!isStackEmpty());
428 Stack.back().first.back().DefaultAttr = DSA_none;
429 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000430 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000432 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000433 assert(!isStackEmpty());
434 Stack.back().first.back().DefaultAttr = DSA_shared;
435 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000436 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000437 /// Set default data mapping attribute to 'tofrom:scalar'.
438 void setDefaultDMAToFromScalar(SourceLocation Loc) {
439 assert(!isStackEmpty());
440 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
441 Stack.back().first.back().DefaultMapAttrLoc = Loc;
442 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000443
444 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000445 return isStackEmpty() ? DSA_unspecified
446 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000448 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000449 return isStackEmpty() ? SourceLocation()
450 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000451 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000452 DefaultMapAttributes getDefaultDMA() const {
453 return isStackEmpty() ? DMA_unspecified
454 : Stack.back().first.back().DefaultMapAttr;
455 }
456 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
457 return Stack.back().first[Level].DefaultMapAttr;
458 }
459 SourceLocation getDefaultDMALocation() const {
460 return isStackEmpty() ? SourceLocation()
461 : Stack.back().first.back().DefaultMapAttrLoc;
462 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000463
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000464 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000465 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000466 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000467 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000468 }
469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000470 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000471 void setOrderedRegion(bool IsOrdered, const Expr *Param,
472 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000473 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000474 if (IsOrdered)
475 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
476 else
477 Stack.back().first.back().OrderedRegion.reset();
478 }
479 /// Returns true, if region is ordered (has associated 'ordered' clause),
480 /// false - otherwise.
481 bool isOrderedRegion() const {
482 if (isStackEmpty())
483 return false;
484 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
485 }
486 /// Returns optional parameter for the ordered region.
487 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
488 if (isStackEmpty() ||
489 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
490 return std::make_pair(nullptr, nullptr);
491 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000492 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000494 /// 'ordered' clause), false - otherwise.
495 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000496 if (isStackEmpty() || Stack.back().first.size() == 1)
497 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000498 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000499 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000500 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000501 std::pair<const Expr *, OMPOrderedClause *>
502 getParentOrderedRegionParam() const {
503 if (isStackEmpty() || Stack.back().first.size() == 1 ||
504 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
505 return std::make_pair(nullptr, nullptr);
506 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000507 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000509 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000510 assert(!isStackEmpty());
511 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000512 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000513 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000514 /// 'nowait' clause), false - otherwise.
515 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000516 if (isStackEmpty() || Stack.back().first.size() == 1)
517 return false;
518 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000521 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000522 if (!isStackEmpty() && Stack.back().first.size() > 1) {
523 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
524 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
525 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000526 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000527 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000528 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000529 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000530 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000531
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000533 void setAssociatedLoops(unsigned Val) {
534 assert(!isStackEmpty());
535 Stack.back().first.back().AssociatedLoops = Val;
536 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000538 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000539 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000540 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000541
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000543 /// region.
544 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000545 if (!isStackEmpty() && Stack.back().first.size() > 1) {
546 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
547 TeamsRegionLoc;
548 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000549 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000550 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000551 bool hasInnerTeamsRegion() const {
552 return getInnerTeamsRegionLoc().isValid();
553 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000554 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000555 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000556 return isStackEmpty() ? SourceLocation()
557 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000558 }
559
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000562 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000563 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000564 return isStackEmpty() ? SourceLocation()
565 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000566 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000567
Samuel Antao4c8035b2016-12-12 18:00:20 +0000568 /// Do the check specified in \a Check to all component lists and return true
569 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000570 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000571 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000572 const llvm::function_ref<
573 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000574 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000575 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000576 if (isStackEmpty())
577 return false;
578 auto SI = Stack.back().first.rbegin();
579 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000580
581 if (SI == SE)
582 return false;
583
Alexey Bataeve3727102018-04-18 15:57:46 +0000584 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000585 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000586 else
587 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000588
589 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000590 auto MI = SI->MappedExprComponents.find(VD);
591 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000592 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
593 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000594 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000595 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000596 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000597 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000598 }
599
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000600 /// Do the check specified in \a Check to all component lists at a given level
601 /// and return true if any issue is found.
602 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000603 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000604 const llvm::function_ref<
605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000606 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000607 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000608 if (isStackEmpty())
609 return false;
610
611 auto StartI = Stack.back().first.begin();
612 auto EndI = Stack.back().first.end();
613 if (std::distance(StartI, EndI) <= (int)Level)
614 return false;
615 std::advance(StartI, Level);
616
617 auto MI = StartI->MappedExprComponents.find(VD);
618 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000619 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
620 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000621 if (Check(L, MI->second.Kind))
622 return true;
623 return false;
624 }
625
Samuel Antao4c8035b2016-12-12 18:00:20 +0000626 /// Create a new mappable expression component list associated with a given
627 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000628 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000629 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
631 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000632 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000633 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000634 MappedExprComponentTy &MEC =
635 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000636 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000637 MEC.Components.resize(MEC.Components.size() + 1);
638 MEC.Components.back().append(Components.begin(), Components.end());
639 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000640 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000641
642 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000643 assert(!isStackEmpty());
644 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000645 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000646 void addDoacrossDependClause(OMPDependClause *C,
647 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000648 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000649 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000650 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000652 }
653 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
654 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000655 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000656 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000657 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000658 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000659 return llvm::make_range(Ref.begin(), Ref.end());
660 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000661 return llvm::make_range(StackElem.DoacrossDepends.end(),
662 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000663 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000664
665 // Store types of classes which have been explicitly mapped
666 void addMappedClassesQualTypes(QualType QT) {
667 SharingMapTy &StackElem = Stack.back().first.back();
668 StackElem.MappedClassesQualTypes.insert(QT);
669 }
670
671 // Return set of mapped classes types
672 bool isClassPreviouslyMapped(QualType QT) const {
673 const SharingMapTy &StackElem = Stack.back().first.back();
674 return StackElem.MappedClassesQualTypes.count(QT) != 0;
675 }
676
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000678
679bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
680 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
681}
682
683bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
684 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000685}
Alexey Bataeve3727102018-04-18 15:57:46 +0000686
Alexey Bataeved09d242014-05-28 05:53:51 +0000687} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000688
Alexey Bataeve3727102018-04-18 15:57:46 +0000689static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000690 if (const auto *FE = dyn_cast<FullExpr>(E))
691 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000692
Alexey Bataeve3727102018-04-18 15:57:46 +0000693 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000694 E = MTE->GetTemporaryExpr();
695
Alexey Bataeve3727102018-04-18 15:57:46 +0000696 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000697 E = Binder->getSubExpr();
698
Alexey Bataeve3727102018-04-18 15:57:46 +0000699 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000700 E = ICE->getSubExprAsWritten();
701 return E->IgnoreParens();
702}
703
Alexey Bataeve3727102018-04-18 15:57:46 +0000704static Expr *getExprAsWritten(Expr *E) {
705 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
706}
707
708static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
709 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
710 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000711 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000712 const auto *VD = dyn_cast<VarDecl>(D);
713 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000714 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000715 VD = VD->getCanonicalDecl();
716 D = VD;
717 } else {
718 assert(FD);
719 FD = FD->getCanonicalDecl();
720 D = FD;
721 }
722 return D;
723}
724
Alexey Bataeve3727102018-04-18 15:57:46 +0000725static ValueDecl *getCanonicalDecl(ValueDecl *D) {
726 return const_cast<ValueDecl *>(
727 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
728}
729
730DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
731 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000732 D = getCanonicalDecl(D);
733 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000734 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000735 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000737 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
738 // in a region but not in construct]
739 // File-scope or namespace-scope variables referenced in called routines
740 // in the region are shared unless they appear in a threadprivate
741 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000742 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000743 DVar.CKind = OMPC_shared;
744
745 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
746 // in a region but not in construct]
747 // Variables with static storage duration that are declared in called
748 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000749 if (VD && VD->hasGlobalStorage())
750 DVar.CKind = OMPC_shared;
751
752 // Non-static data members are shared by default.
753 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000754 DVar.CKind = OMPC_shared;
755
Alexey Bataev758e55e2013-09-06 18:03:48 +0000756 return DVar;
757 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000758
Alexey Bataevec3da872014-01-31 05:15:34 +0000759 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
760 // in a Construct, C/C++, predetermined, p.1]
761 // Variables with automatic storage duration that are declared in a scope
762 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000763 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
764 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000765 DVar.CKind = OMPC_private;
766 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000767 }
768
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000769 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 // Explicitly specified attributes and local variables with predetermined
771 // attributes.
772 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000773 const DSAInfo &Data = Iter->SharingMap.lookup(D);
774 DVar.RefExpr = Data.RefExpr.getPointer();
775 DVar.PrivateCopy = Data.PrivateCopy;
776 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000777 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000778 return DVar;
779 }
780
781 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
782 // in a Construct, C/C++, implicitly determined, p.1]
783 // In a parallel or task construct, the data-sharing attributes of these
784 // variables are determined by the default clause, if present.
785 switch (Iter->DefaultAttr) {
786 case DSA_shared:
787 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000788 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000789 return DVar;
790 case DSA_none:
791 return DVar;
792 case DSA_unspecified:
793 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
794 // in a Construct, implicitly determined, p.2]
795 // In a parallel construct, if no default clause is present, these
796 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000797 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000798 if (isOpenMPParallelDirective(DVar.DKind) ||
799 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000800 DVar.CKind = OMPC_shared;
801 return DVar;
802 }
803
804 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
805 // in a Construct, implicitly determined, p.4]
806 // In a task construct, if no default clause is present, a variable that in
807 // the enclosing context is determined to be shared by all implicit tasks
808 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000809 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000810 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000811 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000812 do {
813 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000814 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000815 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000816 // In a task construct, if no default clause is present, a variable
817 // whose data-sharing attribute is not determined by the rules above is
818 // firstprivate.
819 DVarTemp = getDSA(I, D);
820 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000821 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000822 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000823 return DVar;
824 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000825 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000826 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000827 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000828 return DVar;
829 }
830 }
831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
832 // in a Construct, implicitly determined, p.3]
833 // For constructs other than task, if no default clause is present, these
834 // variables inherit their data-sharing attributes from the enclosing
835 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000836 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000837}
838
Alexey Bataeve3727102018-04-18 15:57:46 +0000839const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
840 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000841 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000842 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000843 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000844 auto It = StackElem.AlignedMap.find(D);
845 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000846 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000847 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000848 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000849 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000850 assert(It->second && "Unexpected nullptr expr in the aligned map");
851 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000852}
853
Alexey Bataeve3727102018-04-18 15:57:46 +0000854void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000855 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000856 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000857 SharingMapTy &StackElem = Stack.back().first.back();
858 StackElem.LCVMap.try_emplace(
859 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000860}
861
Alexey Bataeve3727102018-04-18 15:57:46 +0000862const DSAStackTy::LCDeclInfo
863DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000864 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000865 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000866 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000867 auto It = StackElem.LCVMap.find(D);
868 if (It != StackElem.LCVMap.end())
869 return It->second;
870 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000871}
872
Alexey Bataeve3727102018-04-18 15:57:46 +0000873const DSAStackTy::LCDeclInfo
874DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000875 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
876 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000877 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000878 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000879 auto It = StackElem.LCVMap.find(D);
880 if (It != StackElem.LCVMap.end())
881 return It->second;
882 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000883}
884
Alexey Bataeve3727102018-04-18 15:57:46 +0000885const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000886 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
887 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000888 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000889 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000890 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000891 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000892 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000893 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000894 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000895}
896
Alexey Bataeve3727102018-04-18 15:57:46 +0000897void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000898 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000899 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000900 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000901 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000902 Data.Attributes = A;
903 Data.RefExpr.setPointer(E);
904 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000905 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000906 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000907 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000908 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
909 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
910 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
911 (isLoopControlVariable(D).first && A == OMPC_private));
912 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
913 Data.RefExpr.setInt(/*IntVal=*/true);
914 return;
915 }
916 const bool IsLastprivate =
917 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
918 Data.Attributes = A;
919 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
920 Data.PrivateCopy = PrivateCopy;
921 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000922 DSAInfo &Data =
923 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000924 Data.Attributes = A;
925 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
926 Data.PrivateCopy = nullptr;
927 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000928 }
929}
930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000931/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000932static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000933 StringRef Name, const AttrVec *Attrs = nullptr,
934 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000935 DeclContext *DC = SemaRef.CurContext;
936 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
937 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000938 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000939 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
940 if (Attrs) {
941 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
942 I != E; ++I)
943 Decl->addAttr(*I);
944 }
945 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000946 if (OrigRef) {
947 Decl->addAttr(
948 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
949 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000950 return Decl;
951}
952
953static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
954 SourceLocation Loc,
955 bool RefersToCapture = false) {
956 D->setReferenced();
957 D->markUsed(S.Context);
958 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
959 SourceLocation(), D, RefersToCapture, Loc, Ty,
960 VK_LValue);
961}
962
Alexey Bataeve3727102018-04-18 15:57:46 +0000963void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000964 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000965 D = getCanonicalDecl(D);
966 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000967 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000968 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000969 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000970 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000971 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000972 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000973 "Additional reduction info may be specified only once for reduction "
974 "items.");
975 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000976 Expr *&TaskgroupReductionRef =
977 Stack.back().first.back().TaskgroupReductionRef;
978 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000979 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
980 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000981 TaskgroupReductionRef =
982 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000983 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000984}
985
Alexey Bataeve3727102018-04-18 15:57:46 +0000986void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000987 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000988 D = getCanonicalDecl(D);
989 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000990 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000991 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000992 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000993 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000994 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000995 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000996 "Additional reduction info may be specified only once for reduction "
997 "items.");
998 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000999 Expr *&TaskgroupReductionRef =
1000 Stack.back().first.back().TaskgroupReductionRef;
1001 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001002 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1003 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001004 TaskgroupReductionRef =
1005 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001006 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001007}
1008
Alexey Bataeve3727102018-04-18 15:57:46 +00001009const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1010 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1011 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001012 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1014 if (Stack.back().first.empty())
1015 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001016 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1017 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001018 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001019 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001020 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001021 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001022 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001023 if (!ReductionData.ReductionOp ||
1024 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001025 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001026 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001027 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001028 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1029 "expression for the descriptor is not "
1030 "set.");
1031 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001032 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1033 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001034 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001035 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001036}
1037
Alexey Bataeve3727102018-04-18 15:57:46 +00001038const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1039 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1040 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001041 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001042 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1043 if (Stack.back().first.empty())
1044 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001045 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1046 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001047 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001048 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001049 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001050 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001051 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001052 if (!ReductionData.ReductionOp ||
1053 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001054 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001055 SR = ReductionData.ReductionRange;
1056 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001057 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1058 "expression for the descriptor is not "
1059 "set.");
1060 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001061 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1062 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001063 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001064 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001065}
1066
Alexey Bataeve3727102018-04-18 15:57:46 +00001067bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001068 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001069 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001070 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001071 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001072 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001073 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001074 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001075 if (I == E)
1076 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001077 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001078 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001079 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001080 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001081 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001082 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001083 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001084}
1085
Joel E. Dennyd2649292019-01-04 22:11:56 +00001086static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1087 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001088 bool *IsClassType = nullptr) {
1089 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001090 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001091 bool IsConstant = Type.isConstant(Context);
1092 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001093 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1094 ? Type->getAsCXXRecordDecl()
1095 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001096 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1097 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1098 RD = CTD->getTemplatedDecl();
1099 if (IsClassType)
1100 *IsClassType = RD;
1101 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1102 RD->hasDefinition() && RD->hasMutableFields());
1103}
1104
Joel E. Dennyd2649292019-01-04 22:11:56 +00001105static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1106 QualType Type, OpenMPClauseKind CKind,
1107 SourceLocation ELoc,
1108 bool AcceptIfMutable = true,
1109 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001110 ASTContext &Context = SemaRef.getASTContext();
1111 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001112 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1113 unsigned Diag = ListItemNotVar
1114 ? diag::err_omp_const_list_item
1115 : IsClassType ? diag::err_omp_const_not_mutable_variable
1116 : diag::err_omp_const_variable;
1117 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1118 if (!ListItemNotVar && D) {
1119 const VarDecl *VD = dyn_cast<VarDecl>(D);
1120 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1121 VarDecl::DeclarationOnly;
1122 SemaRef.Diag(D->getLocation(),
1123 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1124 << D;
1125 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001126 return true;
1127 }
1128 return false;
1129}
1130
Alexey Bataeve3727102018-04-18 15:57:46 +00001131const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1132 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001133 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001134 DSAVarData DVar;
1135
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001136 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001137 auto TI = Threadprivates.find(D);
1138 if (TI != Threadprivates.end()) {
1139 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001140 DVar.CKind = OMPC_threadprivate;
1141 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001142 }
1143 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001144 DVar.RefExpr = buildDeclRefExpr(
1145 SemaRef, VD, D->getType().getNonReferenceType(),
1146 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1147 DVar.CKind = OMPC_threadprivate;
1148 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001149 return DVar;
1150 }
1151 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1152 // in a Construct, C/C++, predetermined, p.1]
1153 // Variables appearing in threadprivate directives are threadprivate.
1154 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1155 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1156 SemaRef.getLangOpts().OpenMPUseTLS &&
1157 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1158 (VD && VD->getStorageClass() == SC_Register &&
1159 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1160 DVar.RefExpr = buildDeclRefExpr(
1161 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1162 DVar.CKind = OMPC_threadprivate;
1163 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1164 return DVar;
1165 }
1166 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1167 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1168 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001169 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001170 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1171 [](const SharingMapTy &Data) {
1172 return isOpenMPTargetExecutionDirective(Data.Directive);
1173 });
1174 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001175 iterator ParentIterTarget = std::next(IterTarget, 1);
1176 for (iterator Iter = Stack.back().first.rbegin();
1177 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001178 if (isOpenMPLocal(VD, Iter)) {
1179 DVar.RefExpr =
1180 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1181 D->getLocation());
1182 DVar.CKind = OMPC_threadprivate;
1183 return DVar;
1184 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001185 }
1186 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1187 auto DSAIter = IterTarget->SharingMap.find(D);
1188 if (DSAIter != IterTarget->SharingMap.end() &&
1189 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1190 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1191 DVar.CKind = OMPC_threadprivate;
1192 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001193 }
1194 iterator End = Stack.back().first.rend();
1195 if (!SemaRef.isOpenMPCapturedByRef(
1196 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001197 DVar.RefExpr =
1198 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1199 IterTarget->ConstructLoc);
1200 DVar.CKind = OMPC_threadprivate;
1201 return DVar;
1202 }
1203 }
1204 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001205 }
1206
Alexey Bataev4b465392017-04-26 15:06:24 +00001207 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001208 // Not in OpenMP execution region and top scope was already checked.
1209 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001210
Alexey Bataev758e55e2013-09-06 18:03:48 +00001211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001212 // in a Construct, C/C++, predetermined, p.4]
1213 // Static data members are shared.
1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1215 // in a Construct, C/C++, predetermined, p.7]
1216 // Variables with static storage duration that are declared in a scope
1217 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001218 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001219 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001220 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001221 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001222 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001223
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001224 DVar.CKind = OMPC_shared;
1225 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001226 }
1227
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001228 // The predetermined shared attribute for const-qualified types having no
1229 // mutable members was removed after OpenMP 3.1.
1230 if (SemaRef.LangOpts.OpenMP <= 31) {
1231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1232 // in a Construct, C/C++, predetermined, p.6]
1233 // Variables with const qualified type having no mutable member are
1234 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001235 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001236 // Variables with const-qualified type having no mutable member may be
1237 // listed in a firstprivate clause, even if they are static data members.
1238 DSAVarData DVarTemp = hasInnermostDSA(
1239 D,
1240 [](OpenMPClauseKind C) {
1241 return C == OMPC_firstprivate || C == OMPC_shared;
1242 },
1243 MatchesAlways, FromParent);
1244 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1245 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001246
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001247 DVar.CKind = OMPC_shared;
1248 return DVar;
1249 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001250 }
1251
Alexey Bataev758e55e2013-09-06 18:03:48 +00001252 // Explicitly specified attributes and local variables with predetermined
1253 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001254 iterator I = Stack.back().first.rbegin();
1255 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001256 if (FromParent && I != EndI)
1257 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001258 auto It = I->SharingMap.find(D);
1259 if (It != I->SharingMap.end()) {
1260 const DSAInfo &Data = It->getSecond();
1261 DVar.RefExpr = Data.RefExpr.getPointer();
1262 DVar.PrivateCopy = Data.PrivateCopy;
1263 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001264 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001265 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001266 }
1267
1268 return DVar;
1269}
1270
Alexey Bataeve3727102018-04-18 15:57:46 +00001271const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1272 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001273 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001274 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001275 return getDSA(I, D);
1276 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001277 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001278 iterator StartI = Stack.back().first.rbegin();
1279 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001280 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001281 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001282 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001283}
1284
Alexey Bataeve3727102018-04-18 15:57:46 +00001285const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001286DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001287 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1288 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001289 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001290 if (isStackEmpty())
1291 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001292 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001293 iterator I = Stack.back().first.rbegin();
1294 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001295 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001296 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001297 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001298 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001299 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001300 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001301 DSAVarData DVar = getDSA(NewI, D);
1302 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001303 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001304 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001305 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001306}
1307
Alexey Bataeve3727102018-04-18 15:57:46 +00001308const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001309 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1310 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001311 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001312 if (isStackEmpty())
1313 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001314 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001315 iterator StartI = Stack.back().first.rbegin();
1316 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001317 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001318 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001319 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001320 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001321 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001322 DSAVarData DVar = getDSA(NewI, D);
1323 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001324}
1325
Alexey Bataevaac108a2015-06-23 04:51:00 +00001326bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001327 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1328 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001329 if (isStackEmpty())
1330 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001331 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001332 auto StartI = Stack.back().first.begin();
1333 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001334 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001335 return false;
1336 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001337 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001338 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001339 I->getSecond().RefExpr.getPointer() &&
1340 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001341 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1342 return true;
1343 // Check predetermined rules for the loop control variables.
1344 auto LI = StartI->LCVMap.find(D);
1345 if (LI != StartI->LCVMap.end())
1346 return CPred(OMPC_private);
1347 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001348}
1349
Samuel Antao4be30e92015-10-02 17:14:03 +00001350bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001351 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1352 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001353 if (isStackEmpty())
1354 return false;
1355 auto StartI = Stack.back().first.begin();
1356 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001357 if (std::distance(StartI, EndI) <= (int)Level)
1358 return false;
1359 std::advance(StartI, Level);
1360 return DPred(StartI->Directive);
1361}
1362
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001363bool DSAStackTy::hasDirective(
1364 const llvm::function_ref<bool(OpenMPDirectiveKind,
1365 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001366 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001367 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001368 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001369 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001370 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001371 auto StartI = std::next(Stack.back().first.rbegin());
1372 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001373 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001374 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001375 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1376 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1377 return true;
1378 }
1379 return false;
1380}
1381
Alexey Bataev758e55e2013-09-06 18:03:48 +00001382void Sema::InitDataSharingAttributesStack() {
1383 VarDataSharingAttributesStack = new DSAStackTy(*this);
1384}
1385
1386#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1387
Alexey Bataev4b465392017-04-26 15:06:24 +00001388void Sema::pushOpenMPFunctionRegion() {
1389 DSAStack->pushFunction();
1390}
1391
1392void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1393 DSAStack->popFunction(OldFSI);
1394}
1395
Alexey Bataevc416e642019-02-08 18:02:25 +00001396static bool isOpenMPDeviceDelayedContext(Sema &S) {
1397 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1398 "Expected OpenMP device compilation.");
1399 return !S.isInOpenMPTargetExecutionDirective() &&
1400 !S.isInOpenMPDeclareTargetContext();
1401}
1402
1403/// Do we know that we will eventually codegen the given function?
1404static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1405 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1406 "Expected OpenMP device compilation.");
1407 // Templates are emitted when they're instantiated.
1408 if (FD->isDependentContext())
1409 return false;
1410
1411 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1412 FD->getCanonicalDecl()))
1413 return true;
1414
1415 // Otherwise, the function is known-emitted if it's in our set of
1416 // known-emitted functions.
1417 return S.DeviceKnownEmittedFns.count(FD) > 0;
1418}
1419
1420Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1421 unsigned DiagID) {
1422 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1423 "Expected OpenMP device compilation.");
1424 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1425 !isKnownEmitted(*this, getCurFunctionDecl()))
1426 ? DeviceDiagBuilder::K_Deferred
1427 : DeviceDiagBuilder::K_Immediate,
1428 Loc, DiagID, getCurFunctionDecl(), *this);
1429}
1430
1431void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1432 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1433 "Expected OpenMP device compilation.");
1434 assert(Callee && "Callee may not be null.");
1435 FunctionDecl *Caller = getCurFunctionDecl();
1436
1437 // If the caller is known-emitted, mark the callee as known-emitted.
1438 // Otherwise, mark the call in our call graph so we can traverse it later.
1439 if (!isOpenMPDeviceDelayedContext(*this) ||
1440 (Caller && isKnownEmitted(*this, Caller)))
1441 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1442 else if (Caller)
1443 DeviceCallGraph[Caller].insert({Callee, Loc});
1444}
1445
Alexey Bataeve3727102018-04-18 15:57:46 +00001446bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001447 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1448
Alexey Bataeve3727102018-04-18 15:57:46 +00001449 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001450 bool IsByRef = true;
1451
1452 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001453 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001454 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001455
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001456 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001457 // This table summarizes how a given variable should be passed to the device
1458 // given its type and the clauses where it appears. This table is based on
1459 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1460 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1461 //
1462 // =========================================================================
1463 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1464 // | |(tofrom:scalar)| | pvt | | | |
1465 // =========================================================================
1466 // | scl | | | | - | | bycopy|
1467 // | scl | | - | x | - | - | bycopy|
1468 // | scl | | x | - | - | - | null |
1469 // | scl | x | | | - | | byref |
1470 // | scl | x | - | x | - | - | bycopy|
1471 // | scl | x | x | - | - | - | null |
1472 // | scl | | - | - | - | x | byref |
1473 // | scl | x | - | - | - | x | byref |
1474 //
1475 // | agg | n.a. | | | - | | byref |
1476 // | agg | n.a. | - | x | - | - | byref |
1477 // | agg | n.a. | x | - | - | - | null |
1478 // | agg | n.a. | - | - | - | x | byref |
1479 // | agg | n.a. | - | - | - | x[] | byref |
1480 //
1481 // | ptr | n.a. | | | - | | bycopy|
1482 // | ptr | n.a. | - | x | - | - | bycopy|
1483 // | ptr | n.a. | x | - | - | - | null |
1484 // | ptr | n.a. | - | - | - | x | byref |
1485 // | ptr | n.a. | - | - | - | x[] | bycopy|
1486 // | ptr | n.a. | - | - | x | | bycopy|
1487 // | ptr | n.a. | - | - | x | x | bycopy|
1488 // | ptr | n.a. | - | - | x | x[] | bycopy|
1489 // =========================================================================
1490 // Legend:
1491 // scl - scalar
1492 // ptr - pointer
1493 // agg - aggregate
1494 // x - applies
1495 // - - invalid in this combination
1496 // [] - mapped with an array section
1497 // byref - should be mapped by reference
1498 // byval - should be mapped by value
1499 // null - initialize a local variable to null on the device
1500 //
1501 // Observations:
1502 // - All scalar declarations that show up in a map clause have to be passed
1503 // by reference, because they may have been mapped in the enclosing data
1504 // environment.
1505 // - If the scalar value does not fit the size of uintptr, it has to be
1506 // passed by reference, regardless the result in the table above.
1507 // - For pointers mapped by value that have either an implicit map or an
1508 // array section, the runtime library may pass the NULL value to the
1509 // device instead of the value passed to it by the compiler.
1510
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001511 if (Ty->isReferenceType())
1512 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001513
1514 // Locate map clauses and see if the variable being captured is referred to
1515 // in any of those clauses. Here we only care about variables, not fields,
1516 // because fields are part of aggregates.
1517 bool IsVariableUsedInMapClause = false;
1518 bool IsVariableAssociatedWithSection = false;
1519
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001520 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001521 D, Level,
1522 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1523 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001524 MapExprComponents,
1525 OpenMPClauseKind WhereFoundClauseKind) {
1526 // Only the map clause information influences how a variable is
1527 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001528 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001529 if (WhereFoundClauseKind != OMPC_map)
1530 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001531
1532 auto EI = MapExprComponents.rbegin();
1533 auto EE = MapExprComponents.rend();
1534
1535 assert(EI != EE && "Invalid map expression!");
1536
1537 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1538 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1539
1540 ++EI;
1541 if (EI == EE)
1542 return false;
1543
1544 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1545 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1546 isa<MemberExpr>(EI->getAssociatedExpression())) {
1547 IsVariableAssociatedWithSection = true;
1548 // There is nothing more we need to know about this variable.
1549 return true;
1550 }
1551
1552 // Keep looking for more map info.
1553 return false;
1554 });
1555
1556 if (IsVariableUsedInMapClause) {
1557 // If variable is identified in a map clause it is always captured by
1558 // reference except if it is a pointer that is dereferenced somehow.
1559 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1560 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001561 // By default, all the data that has a scalar type is mapped by copy
1562 // (except for reduction variables).
1563 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001564 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1565 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001566 !Ty->isScalarType() ||
1567 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1568 DSAStack->hasExplicitDSA(
1569 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001570 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001571 }
1572
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001573 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001574 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001575 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1576 !Ty->isAnyPointerType()) ||
1577 !DSAStack->hasExplicitDSA(
1578 D,
1579 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1580 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001581 // If the variable is artificial and must be captured by value - try to
1582 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001583 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1584 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001585 }
1586
Samuel Antao86ace552016-04-27 22:40:57 +00001587 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001588 // and alignment, because the runtime library only deals with uintptr types.
1589 // If it does not fit the uintptr size, we need to pass the data by reference
1590 // instead.
1591 if (!IsByRef &&
1592 (Ctx.getTypeSizeInChars(Ty) >
1593 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001594 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001595 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001596 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001597
1598 return IsByRef;
1599}
1600
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001601unsigned Sema::getOpenMPNestingLevel() const {
1602 assert(getLangOpts().OpenMP);
1603 return DSAStack->getNestingLevel();
1604}
1605
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001606bool Sema::isInOpenMPTargetExecutionDirective() const {
1607 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1608 !DSAStack->isClauseParsingMode()) ||
1609 DSAStack->hasDirective(
1610 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1611 SourceLocation) -> bool {
1612 return isOpenMPTargetExecutionDirective(K);
1613 },
1614 false);
1615}
1616
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001617VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001618 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001619 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001620
1621 // If we are attempting to capture a global variable in a directive with
1622 // 'target' we return true so that this global is also mapped to the device.
1623 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001624 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001625 if (VD && !VD->hasLocalStorage()) {
1626 if (isInOpenMPDeclareTargetContext() &&
1627 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1628 // Try to mark variable as declare target if it is used in capturing
1629 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001630 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001631 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001632 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001633 } else if (isInOpenMPTargetExecutionDirective()) {
1634 // If the declaration is enclosed in a 'declare target' directive,
1635 // then it should not be captured.
1636 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001637 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001638 return nullptr;
1639 return VD;
1640 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001641 }
Alexey Bataev60705422018-10-30 15:50:12 +00001642 // Capture variables captured by reference in lambdas for target-based
1643 // directives.
1644 if (VD && !DSAStack->isClauseParsingMode()) {
1645 if (const auto *RD = VD->getType()
1646 .getCanonicalType()
1647 .getNonReferenceType()
1648 ->getAsCXXRecordDecl()) {
1649 bool SavedForceCaptureByReferenceInTargetExecutable =
1650 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1651 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001652 if (RD->isLambda()) {
1653 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1654 FieldDecl *ThisCapture;
1655 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001656 for (const LambdaCapture &LC : RD->captures()) {
1657 if (LC.getCaptureKind() == LCK_ByRef) {
1658 VarDecl *VD = LC.getCapturedVar();
1659 DeclContext *VDC = VD->getDeclContext();
1660 if (!VDC->Encloses(CurContext))
1661 continue;
1662 DSAStackTy::DSAVarData DVarPrivate =
1663 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1664 // Do not capture already captured variables.
1665 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1666 DVarPrivate.CKind == OMPC_unknown &&
1667 !DSAStack->checkMappableExprComponentListsForDecl(
1668 D, /*CurrentRegionOnly=*/true,
1669 [](OMPClauseMappableExprCommon::
1670 MappableExprComponentListRef,
1671 OpenMPClauseKind) { return true; }))
1672 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1673 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001674 QualType ThisTy = getCurrentThisType();
1675 if (!ThisTy.isNull() &&
1676 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1677 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001678 }
1679 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001680 }
Alexey Bataev60705422018-10-30 15:50:12 +00001681 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1682 SavedForceCaptureByReferenceInTargetExecutable);
1683 }
1684 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001685
Alexey Bataev48977c32015-08-04 08:10:48 +00001686 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1687 (!DSAStack->isClauseParsingMode() ||
1688 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001689 auto &&Info = DSAStack->isLoopControlVariable(D);
1690 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001691 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001692 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001693 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001694 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001695 DSAStackTy::DSAVarData DVarPrivate =
1696 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001697 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001698 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001699 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1700 [](OpenMPDirectiveKind) { return true; },
1701 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001702 if (DVarPrivate.CKind != OMPC_unknown)
1703 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001704 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001705 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001706}
1707
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001708void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1709 unsigned Level) const {
1710 SmallVector<OpenMPDirectiveKind, 4> Regions;
1711 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1712 FunctionScopesIndex -= Regions.size();
1713}
1714
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001715void Sema::startOpenMPLoop() {
1716 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1717 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1718 DSAStack->loopInit();
1719}
1720
Alexey Bataeve3727102018-04-18 15:57:46 +00001721bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001722 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001723 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1724 if (DSAStack->getAssociatedLoops() > 0 &&
1725 !DSAStack->isLoopStarted()) {
1726 DSAStack->resetPossibleLoopCounter(D);
1727 DSAStack->loopStart();
1728 return true;
1729 }
1730 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1731 DSAStack->isLoopControlVariable(D).first) &&
1732 !DSAStack->hasExplicitDSA(
1733 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1734 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1735 return true;
1736 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001737 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001738 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001739 (DSAStack->isClauseParsingMode() &&
1740 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001741 // Consider taskgroup reduction descriptor variable a private to avoid
1742 // possible capture in the region.
1743 (DSAStack->hasExplicitDirective(
1744 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1745 Level) &&
1746 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001747}
1748
Alexey Bataeve3727102018-04-18 15:57:46 +00001749void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1750 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001751 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1752 D = getCanonicalDecl(D);
1753 OpenMPClauseKind OMPC = OMPC_unknown;
1754 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1755 const unsigned NewLevel = I - 1;
1756 if (DSAStack->hasExplicitDSA(D,
1757 [&OMPC](const OpenMPClauseKind K) {
1758 if (isOpenMPPrivate(K)) {
1759 OMPC = K;
1760 return true;
1761 }
1762 return false;
1763 },
1764 NewLevel))
1765 break;
1766 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1767 D, NewLevel,
1768 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1769 OpenMPClauseKind) { return true; })) {
1770 OMPC = OMPC_map;
1771 break;
1772 }
1773 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1774 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001775 OMPC = OMPC_map;
1776 if (D->getType()->isScalarType() &&
1777 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1778 DefaultMapAttributes::DMA_tofrom_scalar)
1779 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001780 break;
1781 }
1782 }
1783 if (OMPC != OMPC_unknown)
1784 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1785}
1786
Alexey Bataeve3727102018-04-18 15:57:46 +00001787bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1788 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001789 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1790 // Return true if the current level is no longer enclosed in a target region.
1791
Alexey Bataeve3727102018-04-18 15:57:46 +00001792 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001793 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001794 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1795 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001796}
1797
Alexey Bataeved09d242014-05-28 05:53:51 +00001798void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001799
1800void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1801 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001802 Scope *CurScope, SourceLocation Loc) {
1803 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001804 PushExpressionEvaluationContext(
1805 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001806}
1807
Alexey Bataevaac108a2015-06-23 04:51:00 +00001808void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1809 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001810}
1811
Alexey Bataevaac108a2015-06-23 04:51:00 +00001812void Sema::EndOpenMPClause() {
1813 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001814}
1815
Alexey Bataev758e55e2013-09-06 18:03:48 +00001816void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001817 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1818 // A variable of class type (or array thereof) that appears in a lastprivate
1819 // clause requires an accessible, unambiguous default constructor for the
1820 // class type, unless the list item is also specified in a firstprivate
1821 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001822 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1823 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001824 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1825 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001826 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001827 if (DE->isValueDependent() || DE->isTypeDependent()) {
1828 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001829 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001830 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001831 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001832 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001833 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001834 const DSAStackTy::DSAVarData DVar =
1835 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001836 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001837 // Generate helper private variable and initialize it with the
1838 // default value. The address of the original variable is replaced
1839 // by the address of the new private variable in CodeGen. This new
1840 // variable is not added to IdResolver, so the code in the OpenMP
1841 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001842 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001843 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001844 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001845 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001846 if (VDPrivate->isInvalidDecl())
1847 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001848 PrivateCopies.push_back(buildDeclRefExpr(
1849 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001850 } else {
1851 // The variable is also a firstprivate, so initialization sequence
1852 // for private copy is generated already.
1853 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001854 }
1855 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001856 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001857 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001858 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001859 }
1860 }
1861 }
1862
Alexey Bataev758e55e2013-09-06 18:03:48 +00001863 DSAStack->pop();
1864 DiscardCleanupsInEvaluationContext();
1865 PopExpressionEvaluationContext();
1866}
1867
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001868static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1869 Expr *NumIterations, Sema &SemaRef,
1870 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001871
Alexey Bataeva769e072013-03-22 06:34:35 +00001872namespace {
1873
Alexey Bataeve3727102018-04-18 15:57:46 +00001874class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001875private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001876 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001877
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001878public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001879 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001880 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001881 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001882 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001883 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001884 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1885 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001886 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001887 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001888 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001889};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001890
Alexey Bataeve3727102018-04-18 15:57:46 +00001891class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001892private:
1893 Sema &SemaRef;
1894
1895public:
1896 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1897 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1898 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001899 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001900 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1901 SemaRef.getCurScope());
1902 }
1903 return false;
1904 }
1905};
1906
Alexey Bataeved09d242014-05-28 05:53:51 +00001907} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001908
1909ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1910 CXXScopeSpec &ScopeSpec,
1911 const DeclarationNameInfo &Id) {
1912 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1913 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1914
1915 if (Lookup.isAmbiguous())
1916 return ExprError();
1917
1918 VarDecl *VD;
1919 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001920 if (TypoCorrection Corrected = CorrectTypo(
1921 Id, LookupOrdinaryName, CurScope, nullptr,
1922 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001923 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001924 PDiag(Lookup.empty()
1925 ? diag::err_undeclared_var_use_suggest
1926 : diag::err_omp_expected_var_arg_suggest)
1927 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001928 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001929 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001930 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1931 : diag::err_omp_expected_var_arg)
1932 << Id.getName();
1933 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001934 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001935 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1936 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1937 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1938 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001939 }
1940 Lookup.suppressDiagnostics();
1941
1942 // OpenMP [2.9.2, Syntax, C/C++]
1943 // Variables must be file-scope, namespace-scope, or static block-scope.
1944 if (!VD->hasGlobalStorage()) {
1945 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001946 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1947 bool IsDecl =
1948 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001949 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001950 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1951 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001952 return ExprError();
1953 }
1954
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001955 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001956 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001957 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1958 // A threadprivate directive for file-scope variables must appear outside
1959 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001960 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1961 !getCurLexicalContext()->isTranslationUnit()) {
1962 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001963 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1964 bool IsDecl =
1965 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1966 Diag(VD->getLocation(),
1967 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1968 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001969 return ExprError();
1970 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001971 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1972 // A threadprivate directive for static class member variables must appear
1973 // in the class definition, in the same scope in which the member
1974 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001975 if (CanonicalVD->isStaticDataMember() &&
1976 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1977 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001978 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1979 bool IsDecl =
1980 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1981 Diag(VD->getLocation(),
1982 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1983 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001984 return ExprError();
1985 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001986 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1987 // A threadprivate directive for namespace-scope variables must appear
1988 // outside any definition or declaration other than the namespace
1989 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001990 if (CanonicalVD->getDeclContext()->isNamespace() &&
1991 (!getCurLexicalContext()->isFileContext() ||
1992 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1993 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001994 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1995 bool IsDecl =
1996 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1997 Diag(VD->getLocation(),
1998 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1999 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002000 return ExprError();
2001 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002002 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2003 // A threadprivate directive for static block-scope variables must appear
2004 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002005 if (CanonicalVD->isStaticLocal() && CurScope &&
2006 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002007 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00002008 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
2009 bool IsDecl =
2010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2011 Diag(VD->getLocation(),
2012 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2013 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002014 return ExprError();
2015 }
2016
2017 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2018 // A threadprivate directive must lexically precede all references to any
2019 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00002020 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002021 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00002022 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002023 return ExprError();
2024 }
2025
2026 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002027 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2028 SourceLocation(), VD,
2029 /*RefersToEnclosingVariableOrCapture=*/false,
2030 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002031}
2032
Alexey Bataeved09d242014-05-28 05:53:51 +00002033Sema::DeclGroupPtrTy
2034Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2035 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002036 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002037 CurContext->addDecl(D);
2038 return DeclGroupPtrTy::make(DeclGroupRef(D));
2039 }
David Blaikie0403cb12016-01-15 23:43:25 +00002040 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002041}
2042
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002043namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002044class LocalVarRefChecker final
2045 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002046 Sema &SemaRef;
2047
2048public:
2049 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002050 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002051 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002052 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002053 diag::err_omp_local_var_in_threadprivate_init)
2054 << E->getSourceRange();
2055 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2056 << VD << VD->getSourceRange();
2057 return true;
2058 }
2059 }
2060 return false;
2061 }
2062 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002063 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002064 if (Child && Visit(Child))
2065 return true;
2066 }
2067 return false;
2068 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002069 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002070};
2071} // namespace
2072
Alexey Bataeved09d242014-05-28 05:53:51 +00002073OMPThreadPrivateDecl *
2074Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002075 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002076 for (Expr *RefExpr : VarList) {
2077 auto *DE = cast<DeclRefExpr>(RefExpr);
2078 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002079 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002080
Alexey Bataev376b4a42016-02-09 09:41:09 +00002081 // Mark variable as used.
2082 VD->setReferenced();
2083 VD->markUsed(Context);
2084
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002085 QualType QType = VD->getType();
2086 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2087 // It will be analyzed later.
2088 Vars.push_back(DE);
2089 continue;
2090 }
2091
Alexey Bataeva769e072013-03-22 06:34:35 +00002092 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2093 // A threadprivate variable must not have an incomplete type.
2094 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002095 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002096 continue;
2097 }
2098
2099 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2100 // A threadprivate variable must not have a reference type.
2101 if (VD->getType()->isReferenceType()) {
2102 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002103 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2104 bool IsDecl =
2105 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2106 Diag(VD->getLocation(),
2107 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2108 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002109 continue;
2110 }
2111
Samuel Antaof8b50122015-07-13 22:54:53 +00002112 // Check if this is a TLS variable. If TLS is not being supported, produce
2113 // the corresponding diagnostic.
2114 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2115 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2116 getLangOpts().OpenMPUseTLS &&
2117 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002118 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2119 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002120 Diag(ILoc, diag::err_omp_var_thread_local)
2121 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002122 bool IsDecl =
2123 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2124 Diag(VD->getLocation(),
2125 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2126 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002127 continue;
2128 }
2129
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002130 // Check if initial value of threadprivate variable reference variable with
2131 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002132 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002133 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002134 if (Checker.Visit(Init))
2135 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002136 }
2137
Alexey Bataeved09d242014-05-28 05:53:51 +00002138 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002139 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002140 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2141 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002142 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002143 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002144 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002145 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002146 if (!Vars.empty()) {
2147 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2148 Vars);
2149 D->setAccess(AS_public);
2150 }
2151 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002152}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002153
Kelvin Li1408f912018-09-26 04:28:39 +00002154Sema::DeclGroupPtrTy
2155Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2156 ArrayRef<OMPClause *> ClauseList) {
2157 OMPRequiresDecl *D = nullptr;
2158 if (!CurContext->isFileContext()) {
2159 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2160 } else {
2161 D = CheckOMPRequiresDecl(Loc, ClauseList);
2162 if (D) {
2163 CurContext->addDecl(D);
2164 DSAStack->addRequiresDecl(D);
2165 }
2166 }
2167 return DeclGroupPtrTy::make(DeclGroupRef(D));
2168}
2169
2170OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2171 ArrayRef<OMPClause *> ClauseList) {
2172 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2173 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2174 ClauseList);
2175 return nullptr;
2176}
2177
Alexey Bataeve3727102018-04-18 15:57:46 +00002178static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2179 const ValueDecl *D,
2180 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002181 bool IsLoopIterVar = false) {
2182 if (DVar.RefExpr) {
2183 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2184 << getOpenMPClauseName(DVar.CKind);
2185 return;
2186 }
2187 enum {
2188 PDSA_StaticMemberShared,
2189 PDSA_StaticLocalVarShared,
2190 PDSA_LoopIterVarPrivate,
2191 PDSA_LoopIterVarLinear,
2192 PDSA_LoopIterVarLastprivate,
2193 PDSA_ConstVarShared,
2194 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002195 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002196 PDSA_LocalVarPrivate,
2197 PDSA_Implicit
2198 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002199 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002200 auto ReportLoc = D->getLocation();
2201 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002202 if (IsLoopIterVar) {
2203 if (DVar.CKind == OMPC_private)
2204 Reason = PDSA_LoopIterVarPrivate;
2205 else if (DVar.CKind == OMPC_lastprivate)
2206 Reason = PDSA_LoopIterVarLastprivate;
2207 else
2208 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002209 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2210 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002211 Reason = PDSA_TaskVarFirstprivate;
2212 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002213 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002214 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002215 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002216 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002217 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002218 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002219 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002220 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002221 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002222 ReportHint = true;
2223 Reason = PDSA_LocalVarPrivate;
2224 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002225 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002226 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002227 << Reason << ReportHint
2228 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2229 } else if (DVar.ImplicitDSALoc.isValid()) {
2230 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2231 << getOpenMPClauseName(DVar.CKind);
2232 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002233}
2234
Alexey Bataev758e55e2013-09-06 18:03:48 +00002235namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002236class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002237 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002238 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002239 bool ErrorFound = false;
2240 CapturedStmt *CS = nullptr;
2241 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2242 llvm::SmallVector<Expr *, 4> ImplicitMap;
2243 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2244 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002245
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002246 void VisitSubCaptures(OMPExecutableDirective *S) {
2247 // Check implicitly captured variables.
2248 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2249 return;
2250 for (const CapturedStmt::Capture &Cap :
2251 S->getInnermostCapturedStmt()->captures()) {
2252 if (!Cap.capturesVariable())
2253 continue;
2254 VarDecl *VD = Cap.getCapturedVar();
2255 // Do not try to map the variable if it or its sub-component was mapped
2256 // already.
2257 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2258 Stack->checkMappableExprComponentListsForDecl(
2259 VD, /*CurrentRegionOnly=*/true,
2260 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2261 OpenMPClauseKind) { return true; }))
2262 continue;
2263 DeclRefExpr *DRE = buildDeclRefExpr(
2264 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2265 Cap.getLocation(), /*RefersToCapture=*/true);
2266 Visit(DRE);
2267 }
2268 }
2269
Alexey Bataev758e55e2013-09-06 18:03:48 +00002270public:
2271 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002272 if (E->isTypeDependent() || E->isValueDependent() ||
2273 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2274 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002275 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002276 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002277 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002278 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002279 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002280
Alexey Bataeve3727102018-04-18 15:57:46 +00002281 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002282 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002283 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002284 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002285
Alexey Bataevafe50572017-10-06 17:00:28 +00002286 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002287 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002288 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002289 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2290 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002291 return;
2292
Alexey Bataeve3727102018-04-18 15:57:46 +00002293 SourceLocation ELoc = E->getExprLoc();
2294 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002295 // The default(none) clause requires that each variable that is referenced
2296 // in the construct, and does not have a predetermined data-sharing
2297 // attribute, must have its data-sharing attribute explicitly determined
2298 // by being listed in a data-sharing attribute clause.
2299 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002300 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002301 VarsWithInheritedDSA.count(VD) == 0) {
2302 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002303 return;
2304 }
2305
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002306 if (isOpenMPTargetExecutionDirective(DKind) &&
2307 !Stack->isLoopControlVariable(VD).first) {
2308 if (!Stack->checkMappableExprComponentListsForDecl(
2309 VD, /*CurrentRegionOnly=*/true,
2310 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2311 StackComponents,
2312 OpenMPClauseKind) {
2313 // Variable is used if it has been marked as an array, array
2314 // section or the variable iself.
2315 return StackComponents.size() == 1 ||
2316 std::all_of(
2317 std::next(StackComponents.rbegin()),
2318 StackComponents.rend(),
2319 [](const OMPClauseMappableExprCommon::
2320 MappableComponent &MC) {
2321 return MC.getAssociatedDeclaration() ==
2322 nullptr &&
2323 (isa<OMPArraySectionExpr>(
2324 MC.getAssociatedExpression()) ||
2325 isa<ArraySubscriptExpr>(
2326 MC.getAssociatedExpression()));
2327 });
2328 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002329 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002330 // By default lambdas are captured as firstprivates.
2331 if (const auto *RD =
2332 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002333 IsFirstprivate = RD->isLambda();
2334 IsFirstprivate =
2335 IsFirstprivate ||
2336 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002337 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002338 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002339 ImplicitFirstprivate.emplace_back(E);
2340 else
2341 ImplicitMap.emplace_back(E);
2342 return;
2343 }
2344 }
2345
Alexey Bataev758e55e2013-09-06 18:03:48 +00002346 // OpenMP [2.9.3.6, Restrictions, p.2]
2347 // A list item that appears in a reduction clause of the innermost
2348 // enclosing worksharing or parallel construct may not be accessed in an
2349 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002350 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002351 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2352 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002353 return isOpenMPParallelDirective(K) ||
2354 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2355 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002356 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002357 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002358 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002359 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002360 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002361 return;
2362 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002363
2364 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002365 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002366 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2367 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002368 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002369 }
2370 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002371 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002372 if (E->isTypeDependent() || E->isValueDependent() ||
2373 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2374 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002375 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002376 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002377 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002378 if (!FD)
2379 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002380 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002381 // Check if the variable has explicit DSA set and stop analysis if it
2382 // so.
2383 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2384 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002385
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002386 if (isOpenMPTargetExecutionDirective(DKind) &&
2387 !Stack->isLoopControlVariable(FD).first &&
2388 !Stack->checkMappableExprComponentListsForDecl(
2389 FD, /*CurrentRegionOnly=*/true,
2390 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2391 StackComponents,
2392 OpenMPClauseKind) {
2393 return isa<CXXThisExpr>(
2394 cast<MemberExpr>(
2395 StackComponents.back().getAssociatedExpression())
2396 ->getBase()
2397 ->IgnoreParens());
2398 })) {
2399 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2400 // A bit-field cannot appear in a map clause.
2401 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002402 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002403 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002404
2405 // Check to see if the member expression is referencing a class that
2406 // has already been explicitly mapped
2407 if (Stack->isClassPreviouslyMapped(TE->getType()))
2408 return;
2409
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002410 ImplicitMap.emplace_back(E);
2411 return;
2412 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002413
Alexey Bataeve3727102018-04-18 15:57:46 +00002414 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002415 // OpenMP [2.9.3.6, Restrictions, p.2]
2416 // A list item that appears in a reduction clause of the innermost
2417 // enclosing worksharing or parallel construct may not be accessed in
2418 // an explicit task.
2419 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002420 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2421 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002422 return isOpenMPParallelDirective(K) ||
2423 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2424 },
2425 /*FromParent=*/true);
2426 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2427 ErrorFound = true;
2428 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002429 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002430 return;
2431 }
2432
2433 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002434 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002435 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002436 !Stack->isLoopControlVariable(FD).first) {
2437 // Check if there is a captured expression for the current field in the
2438 // region. Do not mark it as firstprivate unless there is no captured
2439 // expression.
2440 // TODO: try to make it firstprivate.
2441 if (DVar.CKind != OMPC_unknown)
2442 ImplicitFirstprivate.push_back(E);
2443 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002444 return;
2445 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002446 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002447 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002448 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002449 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002450 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002451 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002452 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2453 if (!Stack->checkMappableExprComponentListsForDecl(
2454 VD, /*CurrentRegionOnly=*/true,
2455 [&CurComponents](
2456 OMPClauseMappableExprCommon::MappableExprComponentListRef
2457 StackComponents,
2458 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002459 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002460 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002461 for (const auto &SC : llvm::reverse(StackComponents)) {
2462 // Do both expressions have the same kind?
2463 if (CCI->getAssociatedExpression()->getStmtClass() !=
2464 SC.getAssociatedExpression()->getStmtClass())
2465 if (!(isa<OMPArraySectionExpr>(
2466 SC.getAssociatedExpression()) &&
2467 isa<ArraySubscriptExpr>(
2468 CCI->getAssociatedExpression())))
2469 return false;
2470
Alexey Bataeve3727102018-04-18 15:57:46 +00002471 const Decl *CCD = CCI->getAssociatedDeclaration();
2472 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002473 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2474 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2475 if (SCD != CCD)
2476 return false;
2477 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002478 if (CCI == CCE)
2479 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002480 }
2481 return true;
2482 })) {
2483 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002484 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002485 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002486 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002487 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002488 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002489 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002490 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002491 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002492 // for task|target directives.
2493 // Skip analysis of arguments of implicitly defined map clause for target
2494 // directives.
2495 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2496 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002497 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002498 if (CC)
2499 Visit(CC);
2500 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002501 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002502 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002503 // Check implicitly captured variables.
2504 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002505 }
2506 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002507 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002508 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002509 // Check implicitly captured variables in the task-based directives to
2510 // check if they must be firstprivatized.
2511 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002512 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002513 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002514 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002515
Alexey Bataeve3727102018-04-18 15:57:46 +00002516 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002517 ArrayRef<Expr *> getImplicitFirstprivate() const {
2518 return ImplicitFirstprivate;
2519 }
2520 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002521 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002522 return VarsWithInheritedDSA;
2523 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002524
Alexey Bataev7ff55242014-06-19 09:13:45 +00002525 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2526 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002527};
Alexey Bataeved09d242014-05-28 05:53:51 +00002528} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002529
Alexey Bataevbae9a792014-06-27 10:37:06 +00002530void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002531 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002532 case OMPD_parallel:
2533 case OMPD_parallel_for:
2534 case OMPD_parallel_for_simd:
2535 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002536 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002537 case OMPD_teams_distribute:
2538 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002539 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002540 QualType KmpInt32PtrTy =
2541 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002542 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002543 std::make_pair(".global_tid.", KmpInt32PtrTy),
2544 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2545 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002546 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002547 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2548 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002549 break;
2550 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002551 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002552 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002553 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002554 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002555 case OMPD_target_teams_distribute:
2556 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002557 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2558 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2559 QualType KmpInt32PtrTy =
2560 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2561 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002562 FunctionProtoType::ExtProtoInfo EPI;
2563 EPI.Variadic = true;
2564 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2565 Sema::CapturedParamNameType Params[] = {
2566 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002567 std::make_pair(".part_id.", KmpInt32PtrTy),
2568 std::make_pair(".privates.", VoidPtrTy),
2569 std::make_pair(
2570 ".copy_fn.",
2571 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002572 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2573 std::make_pair(StringRef(), QualType()) // __context with shared vars
2574 };
2575 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2576 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002577 // Mark this captured region as inlined, because we don't use outlined
2578 // function directly.
2579 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2580 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002581 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002582 Sema::CapturedParamNameType ParamsTarget[] = {
2583 std::make_pair(StringRef(), QualType()) // __context with shared vars
2584 };
2585 // Start a captured region for 'target' with no implicit parameters.
2586 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2587 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002588 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002589 std::make_pair(".global_tid.", KmpInt32PtrTy),
2590 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2591 std::make_pair(StringRef(), QualType()) // __context with shared vars
2592 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002593 // Start a captured region for 'teams' or 'parallel'. Both regions have
2594 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002595 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002596 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002597 break;
2598 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002599 case OMPD_target:
2600 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002601 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2602 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2603 QualType KmpInt32PtrTy =
2604 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2605 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002606 FunctionProtoType::ExtProtoInfo EPI;
2607 EPI.Variadic = true;
2608 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2609 Sema::CapturedParamNameType Params[] = {
2610 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002611 std::make_pair(".part_id.", KmpInt32PtrTy),
2612 std::make_pair(".privates.", VoidPtrTy),
2613 std::make_pair(
2614 ".copy_fn.",
2615 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002616 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2617 std::make_pair(StringRef(), QualType()) // __context with shared vars
2618 };
2619 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2620 Params);
2621 // Mark this captured region as inlined, because we don't use outlined
2622 // function directly.
2623 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2624 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002625 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002626 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2627 std::make_pair(StringRef(), QualType()));
2628 break;
2629 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002630 case OMPD_simd:
2631 case OMPD_for:
2632 case OMPD_for_simd:
2633 case OMPD_sections:
2634 case OMPD_section:
2635 case OMPD_single:
2636 case OMPD_master:
2637 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002638 case OMPD_taskgroup:
2639 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002640 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002641 case OMPD_ordered:
2642 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002643 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002644 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002645 std::make_pair(StringRef(), QualType()) // __context with shared vars
2646 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002647 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2648 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002649 break;
2650 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002651 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002652 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2653 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2654 QualType KmpInt32PtrTy =
2655 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2656 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002657 FunctionProtoType::ExtProtoInfo EPI;
2658 EPI.Variadic = true;
2659 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002660 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002661 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002662 std::make_pair(".part_id.", KmpInt32PtrTy),
2663 std::make_pair(".privates.", VoidPtrTy),
2664 std::make_pair(
2665 ".copy_fn.",
2666 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002668 std::make_pair(StringRef(), QualType()) // __context with shared vars
2669 };
2670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2671 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002672 // Mark this captured region as inlined, because we don't use outlined
2673 // function directly.
2674 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2675 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002676 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002677 break;
2678 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002679 case OMPD_taskloop:
2680 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002681 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2683 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002684 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2686 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002687 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002688 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2689 .withConst();
2690 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2691 QualType KmpInt32PtrTy =
2692 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2693 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002694 FunctionProtoType::ExtProtoInfo EPI;
2695 EPI.Variadic = true;
2696 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002697 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002698 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002699 std::make_pair(".part_id.", KmpInt32PtrTy),
2700 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002701 std::make_pair(
2702 ".copy_fn.",
2703 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2704 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2705 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002706 std::make_pair(".ub.", KmpUInt64Ty),
2707 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002708 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002709 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002710 std::make_pair(StringRef(), QualType()) // __context with shared vars
2711 };
2712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2713 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002714 // Mark this captured region as inlined, because we don't use outlined
2715 // function directly.
2716 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2717 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002718 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002719 break;
2720 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002721 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002722 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002723 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002724 QualType KmpInt32PtrTy =
2725 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2726 Sema::CapturedParamNameType Params[] = {
2727 std::make_pair(".global_tid.", KmpInt32PtrTy),
2728 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002729 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2730 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002731 std::make_pair(StringRef(), QualType()) // __context with shared vars
2732 };
2733 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2734 Params);
2735 break;
2736 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002737 case OMPD_target_teams_distribute_parallel_for:
2738 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002739 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002740 QualType KmpInt32PtrTy =
2741 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002742 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002743
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002744 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002745 FunctionProtoType::ExtProtoInfo EPI;
2746 EPI.Variadic = true;
2747 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2748 Sema::CapturedParamNameType Params[] = {
2749 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002750 std::make_pair(".part_id.", KmpInt32PtrTy),
2751 std::make_pair(".privates.", VoidPtrTy),
2752 std::make_pair(
2753 ".copy_fn.",
2754 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002755 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2756 std::make_pair(StringRef(), QualType()) // __context with shared vars
2757 };
2758 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2759 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002760 // Mark this captured region as inlined, because we don't use outlined
2761 // function directly.
2762 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2763 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002764 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002765 Sema::CapturedParamNameType ParamsTarget[] = {
2766 std::make_pair(StringRef(), QualType()) // __context with shared vars
2767 };
2768 // Start a captured region for 'target' with no implicit parameters.
2769 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2770 ParamsTarget);
2771
2772 Sema::CapturedParamNameType ParamsTeams[] = {
2773 std::make_pair(".global_tid.", KmpInt32PtrTy),
2774 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2775 std::make_pair(StringRef(), QualType()) // __context with shared vars
2776 };
2777 // Start a captured region for 'target' with no implicit parameters.
2778 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2779 ParamsTeams);
2780
2781 Sema::CapturedParamNameType ParamsParallel[] = {
2782 std::make_pair(".global_tid.", KmpInt32PtrTy),
2783 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002784 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2785 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002786 std::make_pair(StringRef(), QualType()) // __context with shared vars
2787 };
2788 // Start a captured region for 'teams' or 'parallel'. Both regions have
2789 // the same implicit parameters.
2790 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2791 ParamsParallel);
2792 break;
2793 }
2794
Alexey Bataev46506272017-12-05 17:41:34 +00002795 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002796 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002797 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002798 QualType KmpInt32PtrTy =
2799 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2800
2801 Sema::CapturedParamNameType ParamsTeams[] = {
2802 std::make_pair(".global_tid.", KmpInt32PtrTy),
2803 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2804 std::make_pair(StringRef(), QualType()) // __context with shared vars
2805 };
2806 // Start a captured region for 'target' with no implicit parameters.
2807 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2808 ParamsTeams);
2809
2810 Sema::CapturedParamNameType ParamsParallel[] = {
2811 std::make_pair(".global_tid.", KmpInt32PtrTy),
2812 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002813 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2814 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00002815 std::make_pair(StringRef(), QualType()) // __context with shared vars
2816 };
2817 // Start a captured region for 'teams' or 'parallel'. Both regions have
2818 // the same implicit parameters.
2819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2820 ParamsParallel);
2821 break;
2822 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002823 case OMPD_target_update:
2824 case OMPD_target_enter_data:
2825 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002826 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2827 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2828 QualType KmpInt32PtrTy =
2829 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2830 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00002831 FunctionProtoType::ExtProtoInfo EPI;
2832 EPI.Variadic = true;
2833 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2834 Sema::CapturedParamNameType Params[] = {
2835 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002836 std::make_pair(".part_id.", KmpInt32PtrTy),
2837 std::make_pair(".privates.", VoidPtrTy),
2838 std::make_pair(
2839 ".copy_fn.",
2840 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00002841 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2842 std::make_pair(StringRef(), QualType()) // __context with shared vars
2843 };
2844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2845 Params);
2846 // Mark this captured region as inlined, because we don't use outlined
2847 // function directly.
2848 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2849 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002850 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00002851 break;
2852 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002853 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002854 case OMPD_taskyield:
2855 case OMPD_barrier:
2856 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002857 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002858 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002859 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002860 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00002861 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002862 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002863 case OMPD_declare_target:
2864 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00002865 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00002866 llvm_unreachable("OpenMP Directive is not allowed");
2867 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002868 llvm_unreachable("Unknown OpenMP directive");
2869 }
2870}
2871
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002872int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2873 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2874 getOpenMPCaptureRegions(CaptureRegions, DKind);
2875 return CaptureRegions.size();
2876}
2877
Alexey Bataev3392d762016-02-16 11:18:12 +00002878static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002879 Expr *CaptureExpr, bool WithInit,
2880 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002881 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002882 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002883 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002884 QualType Ty = Init->getType();
2885 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002886 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002887 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002888 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002889 Ty = C.getPointerType(Ty);
2890 ExprResult Res =
2891 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2892 if (!Res.isUsable())
2893 return nullptr;
2894 Init = Res.get();
2895 }
Alexey Bataev61205072016-03-02 04:57:40 +00002896 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002897 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002898 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002899 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002900 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00002901 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00002902 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002903 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002904 return CED;
2905}
2906
Alexey Bataev61205072016-03-02 04:57:40 +00002907static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2908 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002909 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00002910 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002911 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00002912 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002913 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2914 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002915 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002916 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002917}
2918
Alexey Bataev5a3af132016-03-29 08:58:54 +00002919static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002920 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002921 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002922 OMPCapturedExprDecl *CD = buildCaptureDecl(
2923 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2924 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002925 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2926 CaptureExpr->getExprLoc());
2927 }
2928 ExprResult Res = Ref;
2929 if (!S.getLangOpts().CPlusPlus &&
2930 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002931 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002932 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002933 if (!Res.isUsable())
2934 return ExprError();
2935 }
2936 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002937}
2938
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002939namespace {
2940// OpenMP directives parsed in this section are represented as a
2941// CapturedStatement with an associated statement. If a syntax error
2942// is detected during the parsing of the associated statement, the
2943// compiler must abort processing and close the CapturedStatement.
2944//
2945// Combined directives such as 'target parallel' have more than one
2946// nested CapturedStatements. This RAII ensures that we unwind out
2947// of all the nested CapturedStatements when an error is found.
2948class CaptureRegionUnwinderRAII {
2949private:
2950 Sema &S;
2951 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00002952 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002953
2954public:
2955 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2956 OpenMPDirectiveKind DKind)
2957 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2958 ~CaptureRegionUnwinderRAII() {
2959 if (ErrorFound) {
2960 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2961 while (--ThisCaptureLevel >= 0)
2962 S.ActOnCapturedRegionError();
2963 }
2964 }
2965};
2966} // namespace
2967
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002968StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2969 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002970 bool ErrorFound = false;
2971 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2972 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002973 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002974 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002975 return StmtError();
2976 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002977
Alexey Bataev2ba67042017-11-28 21:11:44 +00002978 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2979 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002980 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002981 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00002982 SmallVector<const OMPLinearClause *, 4> LCs;
2983 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002984 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00002985 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002986 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2987 Clause->getClauseKind() == OMPC_in_reduction) {
2988 // Capture taskgroup task_reduction descriptors inside the tasking regions
2989 // with the corresponding in_reduction items.
2990 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00002991 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00002992 if (E)
2993 MarkDeclarationsReferencedInExpr(E);
2994 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002995 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002996 Clause->getClauseKind() == OMPC_copyprivate ||
2997 (getLangOpts().OpenMPUseTLS &&
2998 getASTContext().getTargetInfo().isTLSSupported() &&
2999 Clause->getClauseKind() == OMPC_copyin)) {
3000 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003001 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003002 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003003 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003004 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003005 }
3006 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003007 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003008 } else if (CaptureRegions.size() > 1 ||
3009 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003010 if (auto *C = OMPClauseWithPreInit::get(Clause))
3011 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003012 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003013 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003014 MarkDeclarationsReferencedInExpr(E);
3015 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003016 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003017 if (Clause->getClauseKind() == OMPC_schedule)
3018 SC = cast<OMPScheduleClause>(Clause);
3019 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003020 OC = cast<OMPOrderedClause>(Clause);
3021 else if (Clause->getClauseKind() == OMPC_linear)
3022 LCs.push_back(cast<OMPLinearClause>(Clause));
3023 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003024 // OpenMP, 2.7.1 Loop Construct, Restrictions
3025 // The nonmonotonic modifier cannot be specified if an ordered clause is
3026 // specified.
3027 if (SC &&
3028 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3029 SC->getSecondScheduleModifier() ==
3030 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3031 OC) {
3032 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3033 ? SC->getFirstScheduleModifierLoc()
3034 : SC->getSecondScheduleModifierLoc(),
3035 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003036 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003037 ErrorFound = true;
3038 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003039 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003040 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003041 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003042 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003043 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003044 ErrorFound = true;
3045 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003046 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3047 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3048 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003049 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003050 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3051 ErrorFound = true;
3052 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003053 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003054 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003055 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003056 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003057 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003058 // Mark all variables in private list clauses as used in inner region.
3059 // Required for proper codegen of combined directives.
3060 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003061 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003062 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003063 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3064 // Find the particular capture region for the clause if the
3065 // directive is a combined one with multiple capture regions.
3066 // If the directive is not a combined one, the capture region
3067 // associated with the clause is OMPD_unknown and is generated
3068 // only once.
3069 if (CaptureRegion == ThisCaptureRegion ||
3070 CaptureRegion == OMPD_unknown) {
3071 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003072 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003073 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3074 }
3075 }
3076 }
3077 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003078 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003079 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003080 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003081}
3082
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003083static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3084 OpenMPDirectiveKind CancelRegion,
3085 SourceLocation StartLoc) {
3086 // CancelRegion is only needed for cancel and cancellation_point.
3087 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3088 return false;
3089
3090 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3091 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3092 return false;
3093
3094 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3095 << getOpenMPDirectiveName(CancelRegion);
3096 return true;
3097}
3098
Alexey Bataeve3727102018-04-18 15:57:46 +00003099static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003100 OpenMPDirectiveKind CurrentRegion,
3101 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003102 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003103 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003104 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003105 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3106 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003107 bool NestingProhibited = false;
3108 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003109 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003110 enum {
3111 NoRecommend,
3112 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003113 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003114 ShouldBeInTargetRegion,
3115 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003116 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003117 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003118 // OpenMP [2.16, Nesting of Regions]
3119 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003120 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003121 // An ordered construct with the simd clause is the only OpenMP
3122 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003123 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003124 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3125 // message.
3126 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3127 ? diag::err_omp_prohibited_region_simd
3128 : diag::warn_omp_nesting_simd);
3129 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003130 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003131 if (ParentRegion == OMPD_atomic) {
3132 // OpenMP [2.16, Nesting of Regions]
3133 // OpenMP constructs may not be nested inside an atomic region.
3134 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3135 return true;
3136 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003137 if (CurrentRegion == OMPD_section) {
3138 // OpenMP [2.7.2, sections Construct, Restrictions]
3139 // Orphaned section directives are prohibited. That is, the section
3140 // directives must appear within the sections construct and must not be
3141 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003142 if (ParentRegion != OMPD_sections &&
3143 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003144 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3145 << (ParentRegion != OMPD_unknown)
3146 << getOpenMPDirectiveName(ParentRegion);
3147 return true;
3148 }
3149 return false;
3150 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003151 // Allow some constructs (except teams and cancellation constructs) to be
3152 // orphaned (they could be used in functions, called from OpenMP regions
3153 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003154 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003155 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3156 CurrentRegion != OMPD_cancellation_point &&
3157 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003158 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003159 if (CurrentRegion == OMPD_cancellation_point ||
3160 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003161 // OpenMP [2.16, Nesting of Regions]
3162 // A cancellation point construct for which construct-type-clause is
3163 // taskgroup must be nested inside a task construct. A cancellation
3164 // point construct for which construct-type-clause is not taskgroup must
3165 // be closely nested inside an OpenMP construct that matches the type
3166 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003167 // A cancel construct for which construct-type-clause is taskgroup must be
3168 // nested inside a task construct. A cancel construct for which
3169 // construct-type-clause is not taskgroup must be closely nested inside an
3170 // OpenMP construct that matches the type specified in
3171 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003172 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003173 !((CancelRegion == OMPD_parallel &&
3174 (ParentRegion == OMPD_parallel ||
3175 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003176 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003177 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003178 ParentRegion == OMPD_target_parallel_for ||
3179 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003180 ParentRegion == OMPD_teams_distribute_parallel_for ||
3181 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003182 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3183 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003184 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3185 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003186 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003187 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003188 // OpenMP [2.16, Nesting of Regions]
3189 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003190 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003191 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003192 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003193 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3194 // OpenMP [2.16, Nesting of Regions]
3195 // A critical region may not be nested (closely or otherwise) inside a
3196 // critical region with the same name. Note that this restriction is not
3197 // sufficient to prevent deadlock.
3198 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003199 bool DeadLock = Stack->hasDirective(
3200 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3201 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003202 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003203 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3204 PreviousCriticalLoc = Loc;
3205 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003206 }
3207 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003208 },
3209 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003210 if (DeadLock) {
3211 SemaRef.Diag(StartLoc,
3212 diag::err_omp_prohibited_region_critical_same_name)
3213 << CurrentName.getName();
3214 if (PreviousCriticalLoc.isValid())
3215 SemaRef.Diag(PreviousCriticalLoc,
3216 diag::note_omp_previous_critical_region);
3217 return true;
3218 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003219 } else if (CurrentRegion == OMPD_barrier) {
3220 // OpenMP [2.16, Nesting of Regions]
3221 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003222 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003223 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3224 isOpenMPTaskingDirective(ParentRegion) ||
3225 ParentRegion == OMPD_master ||
3226 ParentRegion == OMPD_critical ||
3227 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003228 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003229 !isOpenMPParallelDirective(CurrentRegion) &&
3230 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003231 // OpenMP [2.16, Nesting of Regions]
3232 // A worksharing region may not be closely nested inside a worksharing,
3233 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003234 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3235 isOpenMPTaskingDirective(ParentRegion) ||
3236 ParentRegion == OMPD_master ||
3237 ParentRegion == OMPD_critical ||
3238 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003239 Recommend = ShouldBeInParallelRegion;
3240 } else if (CurrentRegion == OMPD_ordered) {
3241 // OpenMP [2.16, Nesting of Regions]
3242 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003243 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003244 // An ordered region must be closely nested inside a loop region (or
3245 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003246 // OpenMP [2.8.1,simd Construct, Restrictions]
3247 // An ordered construct with the simd clause is the only OpenMP construct
3248 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003249 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003250 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003251 !(isOpenMPSimdDirective(ParentRegion) ||
3252 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003253 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003254 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003255 // OpenMP [2.16, Nesting of Regions]
3256 // If specified, a teams construct must be contained within a target
3257 // construct.
3258 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003259 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003260 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003261 }
Kelvin Libf594a52016-12-17 05:48:59 +00003262 if (!NestingProhibited &&
3263 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3264 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3265 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003266 // OpenMP [2.16, Nesting of Regions]
3267 // distribute, parallel, parallel sections, parallel workshare, and the
3268 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3269 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003270 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3271 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003272 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003273 }
David Majnemer9d168222016-08-05 17:44:54 +00003274 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003275 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003276 // OpenMP 4.5 [2.17 Nesting of Regions]
3277 // The region associated with the distribute construct must be strictly
3278 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003279 NestingProhibited =
3280 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003281 Recommend = ShouldBeInTeamsRegion;
3282 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003283 if (!NestingProhibited &&
3284 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3285 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3286 // OpenMP 4.5 [2.17 Nesting of Regions]
3287 // If a target, target update, target data, target enter data, or
3288 // target exit data construct is encountered during execution of a
3289 // target region, the behavior is unspecified.
3290 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003291 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003292 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003293 if (isOpenMPTargetExecutionDirective(K)) {
3294 OffendingRegion = K;
3295 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003296 }
3297 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003298 },
3299 false /* don't skip top directive */);
3300 CloseNesting = false;
3301 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003302 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003303 if (OrphanSeen) {
3304 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3305 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3306 } else {
3307 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3308 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3309 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3310 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003311 return true;
3312 }
3313 }
3314 return false;
3315}
3316
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003317static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3318 ArrayRef<OMPClause *> Clauses,
3319 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3320 bool ErrorFound = false;
3321 unsigned NamedModifiersNumber = 0;
3322 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3323 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003324 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003325 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003326 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3327 // At most one if clause without a directive-name-modifier can appear on
3328 // the directive.
3329 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3330 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003331 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003332 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3333 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3334 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003335 } else if (CurNM != OMPD_unknown) {
3336 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003337 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003338 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003339 FoundNameModifiers[CurNM] = IC;
3340 if (CurNM == OMPD_unknown)
3341 continue;
3342 // Check if the specified name modifier is allowed for the current
3343 // directive.
3344 // At most one if clause with the particular directive-name-modifier can
3345 // appear on the directive.
3346 bool MatchFound = false;
3347 for (auto NM : AllowedNameModifiers) {
3348 if (CurNM == NM) {
3349 MatchFound = true;
3350 break;
3351 }
3352 }
3353 if (!MatchFound) {
3354 S.Diag(IC->getNameModifierLoc(),
3355 diag::err_omp_wrong_if_directive_name_modifier)
3356 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3357 ErrorFound = true;
3358 }
3359 }
3360 }
3361 // If any if clause on the directive includes a directive-name-modifier then
3362 // all if clauses on the directive must include a directive-name-modifier.
3363 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3364 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003365 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003366 diag::err_omp_no_more_if_clause);
3367 } else {
3368 std::string Values;
3369 std::string Sep(", ");
3370 unsigned AllowedCnt = 0;
3371 unsigned TotalAllowedNum =
3372 AllowedNameModifiers.size() - NamedModifiersNumber;
3373 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3374 ++Cnt) {
3375 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3376 if (!FoundNameModifiers[NM]) {
3377 Values += "'";
3378 Values += getOpenMPDirectiveName(NM);
3379 Values += "'";
3380 if (AllowedCnt + 2 == TotalAllowedNum)
3381 Values += " or ";
3382 else if (AllowedCnt + 1 != TotalAllowedNum)
3383 Values += Sep;
3384 ++AllowedCnt;
3385 }
3386 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003387 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003388 diag::err_omp_unnamed_if_clause)
3389 << (TotalAllowedNum > 1) << Values;
3390 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003391 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003392 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3393 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003394 ErrorFound = true;
3395 }
3396 return ErrorFound;
3397}
3398
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003399StmtResult Sema::ActOnOpenMPExecutableDirective(
3400 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3401 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3402 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003403 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003404 // First check CancelRegion which is then used in checkNestingOfRegions.
3405 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3406 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003407 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003408 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003409
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003410 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003411 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003412 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003413 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003414 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003415 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3416
3417 // Check default data sharing attributes for referenced variables.
3418 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003419 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3420 Stmt *S = AStmt;
3421 while (--ThisCaptureLevel >= 0)
3422 S = cast<CapturedStmt>(S)->getCapturedStmt();
3423 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003424 if (DSAChecker.isErrorFound())
3425 return StmtError();
3426 // Generate list of implicitly defined firstprivate variables.
3427 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003428
Alexey Bataev88202be2017-07-27 13:20:36 +00003429 SmallVector<Expr *, 4> ImplicitFirstprivates(
3430 DSAChecker.getImplicitFirstprivate().begin(),
3431 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003432 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3433 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003434 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003435 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003436 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003437 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003438 if (E)
3439 ImplicitFirstprivates.emplace_back(E);
3440 }
3441 }
3442 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003443 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003444 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3445 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003446 ClausesWithImplicit.push_back(Implicit);
3447 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003448 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003449 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003450 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003451 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003452 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003453 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003454 CXXScopeSpec MapperIdScopeSpec;
3455 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003456 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003457 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3458 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3459 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003460 ClausesWithImplicit.emplace_back(Implicit);
3461 ErrorFound |=
3462 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003463 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003464 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003465 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003466 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003467 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003468
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003469 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003470 switch (Kind) {
3471 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003472 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3473 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003474 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003475 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003476 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003477 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3478 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003479 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003480 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003481 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3482 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003483 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003484 case OMPD_for_simd:
3485 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3486 EndLoc, VarsWithInheritedDSA);
3487 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003488 case OMPD_sections:
3489 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3490 EndLoc);
3491 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003492 case OMPD_section:
3493 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003494 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003495 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3496 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003497 case OMPD_single:
3498 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3499 EndLoc);
3500 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003501 case OMPD_master:
3502 assert(ClausesWithImplicit.empty() &&
3503 "No clauses are allowed for 'omp master' directive");
3504 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3505 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003506 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003507 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3508 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003509 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003510 case OMPD_parallel_for:
3511 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3512 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003513 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003514 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003515 case OMPD_parallel_for_simd:
3516 Res = ActOnOpenMPParallelForSimdDirective(
3517 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003518 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003519 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003520 case OMPD_parallel_sections:
3521 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3522 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003523 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003524 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003525 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003526 Res =
3527 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003528 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003529 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003530 case OMPD_taskyield:
3531 assert(ClausesWithImplicit.empty() &&
3532 "No clauses are allowed for 'omp taskyield' directive");
3533 assert(AStmt == nullptr &&
3534 "No associated statement allowed for 'omp taskyield' directive");
3535 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3536 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003537 case OMPD_barrier:
3538 assert(ClausesWithImplicit.empty() &&
3539 "No clauses are allowed for 'omp barrier' directive");
3540 assert(AStmt == nullptr &&
3541 "No associated statement allowed for 'omp barrier' directive");
3542 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3543 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003544 case OMPD_taskwait:
3545 assert(ClausesWithImplicit.empty() &&
3546 "No clauses are allowed for 'omp taskwait' directive");
3547 assert(AStmt == nullptr &&
3548 "No associated statement allowed for 'omp taskwait' directive");
3549 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3550 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003551 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003552 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3553 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003554 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003555 case OMPD_flush:
3556 assert(AStmt == nullptr &&
3557 "No associated statement allowed for 'omp flush' directive");
3558 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3559 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003560 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003561 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3562 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003563 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003564 case OMPD_atomic:
3565 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3566 EndLoc);
3567 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003568 case OMPD_teams:
3569 Res =
3570 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3571 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003572 case OMPD_target:
3573 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3574 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003575 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003576 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003577 case OMPD_target_parallel:
3578 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3579 StartLoc, EndLoc);
3580 AllowedNameModifiers.push_back(OMPD_target);
3581 AllowedNameModifiers.push_back(OMPD_parallel);
3582 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003583 case OMPD_target_parallel_for:
3584 Res = ActOnOpenMPTargetParallelForDirective(
3585 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3586 AllowedNameModifiers.push_back(OMPD_target);
3587 AllowedNameModifiers.push_back(OMPD_parallel);
3588 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003589 case OMPD_cancellation_point:
3590 assert(ClausesWithImplicit.empty() &&
3591 "No clauses are allowed for 'omp cancellation point' directive");
3592 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3593 "cancellation point' directive");
3594 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3595 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003596 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003597 assert(AStmt == nullptr &&
3598 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003599 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3600 CancelRegion);
3601 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003602 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003603 case OMPD_target_data:
3604 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3605 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003606 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003607 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003608 case OMPD_target_enter_data:
3609 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003610 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003611 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3612 break;
Samuel Antao72590762016-01-19 20:04:50 +00003613 case OMPD_target_exit_data:
3614 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003615 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003616 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3617 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003618 case OMPD_taskloop:
3619 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3620 EndLoc, VarsWithInheritedDSA);
3621 AllowedNameModifiers.push_back(OMPD_taskloop);
3622 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003623 case OMPD_taskloop_simd:
3624 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3625 EndLoc, VarsWithInheritedDSA);
3626 AllowedNameModifiers.push_back(OMPD_taskloop);
3627 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003628 case OMPD_distribute:
3629 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3630 EndLoc, VarsWithInheritedDSA);
3631 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003632 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003633 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3634 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003635 AllowedNameModifiers.push_back(OMPD_target_update);
3636 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003637 case OMPD_distribute_parallel_for:
3638 Res = ActOnOpenMPDistributeParallelForDirective(
3639 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3640 AllowedNameModifiers.push_back(OMPD_parallel);
3641 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003642 case OMPD_distribute_parallel_for_simd:
3643 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3644 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3645 AllowedNameModifiers.push_back(OMPD_parallel);
3646 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003647 case OMPD_distribute_simd:
3648 Res = ActOnOpenMPDistributeSimdDirective(
3649 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3650 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003651 case OMPD_target_parallel_for_simd:
3652 Res = ActOnOpenMPTargetParallelForSimdDirective(
3653 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3654 AllowedNameModifiers.push_back(OMPD_target);
3655 AllowedNameModifiers.push_back(OMPD_parallel);
3656 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003657 case OMPD_target_simd:
3658 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3659 EndLoc, VarsWithInheritedDSA);
3660 AllowedNameModifiers.push_back(OMPD_target);
3661 break;
Kelvin Li02532872016-08-05 14:37:37 +00003662 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003663 Res = ActOnOpenMPTeamsDistributeDirective(
3664 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003665 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003666 case OMPD_teams_distribute_simd:
3667 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3668 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3669 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003670 case OMPD_teams_distribute_parallel_for_simd:
3671 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3672 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3673 AllowedNameModifiers.push_back(OMPD_parallel);
3674 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003675 case OMPD_teams_distribute_parallel_for:
3676 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3677 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3678 AllowedNameModifiers.push_back(OMPD_parallel);
3679 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003680 case OMPD_target_teams:
3681 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3682 EndLoc);
3683 AllowedNameModifiers.push_back(OMPD_target);
3684 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003685 case OMPD_target_teams_distribute:
3686 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3687 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3688 AllowedNameModifiers.push_back(OMPD_target);
3689 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003690 case OMPD_target_teams_distribute_parallel_for:
3691 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3692 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3693 AllowedNameModifiers.push_back(OMPD_target);
3694 AllowedNameModifiers.push_back(OMPD_parallel);
3695 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003696 case OMPD_target_teams_distribute_parallel_for_simd:
3697 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3698 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3699 AllowedNameModifiers.push_back(OMPD_target);
3700 AllowedNameModifiers.push_back(OMPD_parallel);
3701 break;
Kelvin Lida681182017-01-10 18:08:18 +00003702 case OMPD_target_teams_distribute_simd:
3703 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3704 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3705 AllowedNameModifiers.push_back(OMPD_target);
3706 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003707 case OMPD_declare_target:
3708 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003709 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003710 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003711 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003712 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003713 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003714 llvm_unreachable("OpenMP Directive is not allowed");
3715 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003716 llvm_unreachable("Unknown OpenMP directive");
3717 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003718
Alexey Bataeve3727102018-04-18 15:57:46 +00003719 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003720 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3721 << P.first << P.second->getSourceRange();
3722 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003723 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3724
3725 if (!AllowedNameModifiers.empty())
3726 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3727 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003728
Alexey Bataeved09d242014-05-28 05:53:51 +00003729 if (ErrorFound)
3730 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003731 return Res;
3732}
3733
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003734Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3735 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003736 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003737 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3738 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003739 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003740 assert(Linears.size() == LinModifiers.size());
3741 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003742 if (!DG || DG.get().isNull())
3743 return DeclGroupPtrTy();
3744
3745 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003746 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003747 return DG;
3748 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003749 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003750 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3751 ADecl = FTD->getTemplatedDecl();
3752
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003753 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3754 if (!FD) {
3755 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003756 return DeclGroupPtrTy();
3757 }
3758
Alexey Bataev2af33e32016-04-07 12:45:37 +00003759 // OpenMP [2.8.2, declare simd construct, Description]
3760 // The parameter of the simdlen clause must be a constant positive integer
3761 // expression.
3762 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003763 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003764 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003765 // OpenMP [2.8.2, declare simd construct, Description]
3766 // The special this pointer can be used as if was one of the arguments to the
3767 // function in any of the linear, aligned, or uniform clauses.
3768 // The uniform clause declares one or more arguments to have an invariant
3769 // value for all concurrent invocations of the function in the execution of a
3770 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003771 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3772 const Expr *UniformedLinearThis = nullptr;
3773 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003774 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003775 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3776 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003777 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3778 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003779 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00003780 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003781 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003782 }
3783 if (isa<CXXThisExpr>(E)) {
3784 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003785 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003786 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003787 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3788 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003789 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003790 // OpenMP [2.8.2, declare simd construct, Description]
3791 // The aligned clause declares that the object to which each list item points
3792 // is aligned to the number of bytes expressed in the optional parameter of
3793 // the aligned clause.
3794 // The special this pointer can be used as if was one of the arguments to the
3795 // function in any of the linear, aligned, or uniform clauses.
3796 // The type of list items appearing in the aligned clause must be array,
3797 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00003798 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3799 const Expr *AlignedThis = nullptr;
3800 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003801 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003802 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3803 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3804 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00003805 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3806 FD->getParamDecl(PVD->getFunctionScopeIndex())
3807 ->getCanonicalDecl() == CanonPVD) {
3808 // OpenMP [2.8.1, simd construct, Restrictions]
3809 // A list-item cannot appear in more than one aligned clause.
3810 if (AlignedArgs.count(CanonPVD) > 0) {
3811 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3812 << 1 << E->getSourceRange();
3813 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3814 diag::note_omp_explicit_dsa)
3815 << getOpenMPClauseName(OMPC_aligned);
3816 continue;
3817 }
3818 AlignedArgs[CanonPVD] = E;
3819 QualType QTy = PVD->getType()
3820 .getNonReferenceType()
3821 .getUnqualifiedType()
3822 .getCanonicalType();
3823 const Type *Ty = QTy.getTypePtrOrNull();
3824 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3825 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3826 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3827 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3828 }
3829 continue;
3830 }
3831 }
3832 if (isa<CXXThisExpr>(E)) {
3833 if (AlignedThis) {
3834 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3835 << 2 << E->getSourceRange();
3836 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3837 << getOpenMPClauseName(OMPC_aligned);
3838 }
3839 AlignedThis = E;
3840 continue;
3841 }
3842 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3843 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3844 }
3845 // The optional parameter of the aligned clause, alignment, must be a constant
3846 // positive integer expression. If no optional parameter is specified,
3847 // implementation-defined default alignments for SIMD instructions on the
3848 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00003849 SmallVector<const Expr *, 4> NewAligns;
3850 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003851 ExprResult Align;
3852 if (E)
3853 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3854 NewAligns.push_back(Align.get());
3855 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003856 // OpenMP [2.8.2, declare simd construct, Description]
3857 // The linear clause declares one or more list items to be private to a SIMD
3858 // lane and to have a linear relationship with respect to the iteration space
3859 // of a loop.
3860 // The special this pointer can be used as if was one of the arguments to the
3861 // function in any of the linear, aligned, or uniform clauses.
3862 // When a linear-step expression is specified in a linear clause it must be
3863 // either a constant integer expression or an integer-typed parameter that is
3864 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00003865 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003866 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3867 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00003868 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003869 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3870 ++MI;
3871 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003872 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3873 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3874 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003875 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3876 FD->getParamDecl(PVD->getFunctionScopeIndex())
3877 ->getCanonicalDecl() == CanonPVD) {
3878 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3879 // A list-item cannot appear in more than one linear clause.
3880 if (LinearArgs.count(CanonPVD) > 0) {
3881 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3882 << getOpenMPClauseName(OMPC_linear)
3883 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3884 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3885 diag::note_omp_explicit_dsa)
3886 << getOpenMPClauseName(OMPC_linear);
3887 continue;
3888 }
3889 // Each argument can appear in at most one uniform or linear clause.
3890 if (UniformedArgs.count(CanonPVD) > 0) {
3891 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3892 << getOpenMPClauseName(OMPC_linear)
3893 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3894 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3895 diag::note_omp_explicit_dsa)
3896 << getOpenMPClauseName(OMPC_uniform);
3897 continue;
3898 }
3899 LinearArgs[CanonPVD] = E;
3900 if (E->isValueDependent() || E->isTypeDependent() ||
3901 E->isInstantiationDependent() ||
3902 E->containsUnexpandedParameterPack())
3903 continue;
3904 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3905 PVD->getOriginalType());
3906 continue;
3907 }
3908 }
3909 if (isa<CXXThisExpr>(E)) {
3910 if (UniformedLinearThis) {
3911 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3912 << getOpenMPClauseName(OMPC_linear)
3913 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3914 << E->getSourceRange();
3915 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3916 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3917 : OMPC_linear);
3918 continue;
3919 }
3920 UniformedLinearThis = E;
3921 if (E->isValueDependent() || E->isTypeDependent() ||
3922 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3923 continue;
3924 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3925 E->getType());
3926 continue;
3927 }
3928 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3929 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3930 }
3931 Expr *Step = nullptr;
3932 Expr *NewStep = nullptr;
3933 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00003934 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003935 // Skip the same step expression, it was checked already.
3936 if (Step == E || !E) {
3937 NewSteps.push_back(E ? NewStep : nullptr);
3938 continue;
3939 }
3940 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00003941 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3942 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3943 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003944 if (UniformedArgs.count(CanonPVD) == 0) {
3945 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3946 << Step->getSourceRange();
3947 } else if (E->isValueDependent() || E->isTypeDependent() ||
3948 E->isInstantiationDependent() ||
3949 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00003950 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003951 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00003952 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003953 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3954 << Step->getSourceRange();
3955 }
3956 continue;
3957 }
3958 NewStep = Step;
3959 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3960 !Step->isInstantiationDependent() &&
3961 !Step->containsUnexpandedParameterPack()) {
3962 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3963 .get();
3964 if (NewStep)
3965 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3966 }
3967 NewSteps.push_back(NewStep);
3968 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003969 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3970 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003971 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003972 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3973 const_cast<Expr **>(Linears.data()), Linears.size(),
3974 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3975 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003976 ADecl->addAttr(NewAttr);
3977 return ConvertDeclToDeclGroup(ADecl);
3978}
3979
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003980StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3981 Stmt *AStmt,
3982 SourceLocation StartLoc,
3983 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003984 if (!AStmt)
3985 return StmtError();
3986
Alexey Bataeve3727102018-04-18 15:57:46 +00003987 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00003988 // 1.2.2 OpenMP Language Terminology
3989 // Structured block - An executable statement with a single entry at the
3990 // top and a single exit at the bottom.
3991 // The point of exit cannot be a branch out of the structured block.
3992 // longjmp() and throw() must not violate the entry/exit criteria.
3993 CS->getCapturedDecl()->setNothrow();
3994
Reid Kleckner87a31802018-03-12 21:43:02 +00003995 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003996
Alexey Bataev25e5b442015-09-15 12:52:43 +00003997 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3998 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003999}
4000
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004001namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004002/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004003/// extracting iteration space of each loop in the loop nest, that will be used
4004/// for IR generation.
4005class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004006 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004007 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004008 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004009 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004010 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004011 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004012 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004013 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004014 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004015 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004016 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004017 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004018 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004019 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004020 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004021 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004022 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004023 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004024 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004025 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004026 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004027 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004028 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004029 /// Var < UB
4030 /// Var <= UB
4031 /// UB > Var
4032 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004033 /// This will have no value when the condition is !=
4034 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004035 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004036 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004037 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004038 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004039
4040public:
4041 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004042 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004043 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004044 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004045 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004046 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004047 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004048 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004049 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004050 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004051 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004052 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004053 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004054 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004055 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004056 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004057 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004058 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004059 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004060 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004061 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004062 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004063 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004064 /// True, if the compare operator is strict (<, > or !=).
4065 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004066 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004067 Expr *buildNumIterations(
4068 Scope *S, const bool LimitedType,
4069 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004070 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004071 Expr *
4072 buildPreCond(Scope *S, Expr *Cond,
4073 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004074 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004075 DeclRefExpr *
4076 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4077 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004078 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004079 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004080 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004081 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004082 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004083 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004084 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004085 /// Build loop data with counter value for depend clauses in ordered
4086 /// directives.
4087 Expr *
4088 buildOrderedLoopData(Scope *S, Expr *Counter,
4089 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4090 SourceLocation Loc, Expr *Inc = nullptr,
4091 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004092 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004093 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004094
4095private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004096 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004097 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004098 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004099 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004100 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004101 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004102 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4103 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004104 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004105 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004106};
4107
Alexey Bataeve3727102018-04-18 15:57:46 +00004108bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004109 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004110 assert(!LB && !UB && !Step);
4111 return false;
4112 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004113 return LCDecl->getType()->isDependentType() ||
4114 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4115 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004116}
4117
Alexey Bataeve3727102018-04-18 15:57:46 +00004118bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004119 Expr *NewLCRefExpr,
4120 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004121 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004122 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004123 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004124 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004125 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004126 LCDecl = getCanonicalDecl(NewLCDecl);
4127 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004128 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4129 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004130 if ((Ctor->isCopyOrMoveConstructor() ||
4131 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4132 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004133 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004134 LB = NewLB;
4135 return false;
4136}
4137
Alexey Bataev316ccf62019-01-29 18:51:58 +00004138bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4139 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004140 bool StrictOp, SourceRange SR,
4141 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004142 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004143 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4144 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004145 if (!NewUB)
4146 return true;
4147 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004148 if (LessOp)
4149 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004150 TestIsStrictOp = StrictOp;
4151 ConditionSrcRange = SR;
4152 ConditionLoc = SL;
4153 return false;
4154}
4155
Alexey Bataeve3727102018-04-18 15:57:46 +00004156bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004157 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004158 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004159 if (!NewStep)
4160 return true;
4161 if (!NewStep->isValueDependent()) {
4162 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004163 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004164 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4165 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004166 if (Val.isInvalid())
4167 return true;
4168 NewStep = Val.get();
4169
4170 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4171 // If test-expr is of form var relational-op b and relational-op is < or
4172 // <= then incr-expr must cause var to increase on each iteration of the
4173 // loop. If test-expr is of form var relational-op b and relational-op is
4174 // > or >= then incr-expr must cause var to decrease on each iteration of
4175 // the loop.
4176 // If test-expr is of form b relational-op var and relational-op is < or
4177 // <= then incr-expr must cause var to decrease on each iteration of the
4178 // loop. If test-expr is of form b relational-op var and relational-op is
4179 // > or >= then incr-expr must cause var to increase on each iteration of
4180 // the loop.
4181 llvm::APSInt Result;
4182 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4183 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4184 bool IsConstNeg =
4185 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004186 bool IsConstPos =
4187 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004188 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004189
4190 // != with increment is treated as <; != with decrement is treated as >
4191 if (!TestIsLessOp.hasValue())
4192 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004193 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004194 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004195 (IsConstNeg || (IsUnsigned && Subtract)) :
4196 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004197 SemaRef.Diag(NewStep->getExprLoc(),
4198 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004199 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004200 SemaRef.Diag(ConditionLoc,
4201 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004202 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004203 return true;
4204 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004205 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004206 NewStep =
4207 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4208 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004209 Subtract = !Subtract;
4210 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004211 }
4212
4213 Step = NewStep;
4214 SubtractStep = Subtract;
4215 return false;
4216}
4217
Alexey Bataeve3727102018-04-18 15:57:46 +00004218bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004219 // Check init-expr for canonical loop form and save loop counter
4220 // variable - #Var and its initialization value - #LB.
4221 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4222 // var = lb
4223 // integer-type var = lb
4224 // random-access-iterator-type var = lb
4225 // pointer-type var = lb
4226 //
4227 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004228 if (EmitDiags) {
4229 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4230 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004231 return true;
4232 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004233 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4234 if (!ExprTemp->cleanupsHaveSideEffects())
4235 S = ExprTemp->getSubExpr();
4236
Alexander Musmana5f070a2014-10-01 06:03:56 +00004237 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004238 if (Expr *E = dyn_cast<Expr>(S))
4239 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004240 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004241 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004242 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004243 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4244 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4245 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004246 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4247 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004248 }
4249 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4250 if (ME->isArrow() &&
4251 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004252 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004253 }
4254 }
David Majnemer9d168222016-08-05 17:44:54 +00004255 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004256 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004257 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004258 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004259 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004260 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004261 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004262 diag::ext_omp_loop_not_canonical_init)
4263 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004264 return setLCDeclAndLB(
4265 Var,
4266 buildDeclRefExpr(SemaRef, Var,
4267 Var->getType().getNonReferenceType(),
4268 DS->getBeginLoc()),
4269 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004270 }
4271 }
4272 }
David Majnemer9d168222016-08-05 17:44:54 +00004273 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004274 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004275 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004276 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004277 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4278 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004279 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4280 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004281 }
4282 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4283 if (ME->isArrow() &&
4284 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004285 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004286 }
4287 }
4288 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004289
Alexey Bataeve3727102018-04-18 15:57:46 +00004290 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004291 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004292 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004293 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004294 << S->getSourceRange();
4295 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004296 return true;
4297}
4298
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004299/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004300/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004301static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004302 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004303 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004304 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004305 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004306 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004307 if ((Ctor->isCopyOrMoveConstructor() ||
4308 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4309 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004310 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004311 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4312 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004313 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004314 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004315 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004316 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4317 return getCanonicalDecl(ME->getMemberDecl());
4318 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004319}
4320
Alexey Bataeve3727102018-04-18 15:57:46 +00004321bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004322 // Check test-expr for canonical form, save upper-bound UB, flags for
4323 // less/greater and for strict/non-strict comparison.
4324 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4325 // var relational-op b
4326 // b relational-op var
4327 //
4328 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004329 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004330 return true;
4331 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004332 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004333 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004334 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004335 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004336 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4337 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004338 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4339 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4340 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004341 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4342 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004343 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4344 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4345 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004346 } else if (BO->getOpcode() == BO_NE)
4347 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4348 BO->getRHS() : BO->getLHS(),
4349 /*LessOp=*/llvm::None,
4350 /*StrictOp=*/true,
4351 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004352 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004353 if (CE->getNumArgs() == 2) {
4354 auto Op = CE->getOperator();
4355 switch (Op) {
4356 case OO_Greater:
4357 case OO_GreaterEqual:
4358 case OO_Less:
4359 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004360 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4361 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004362 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4363 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004364 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4365 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004366 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4367 CE->getOperatorLoc());
4368 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004369 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004370 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4371 CE->getArg(1) : CE->getArg(0),
4372 /*LessOp=*/llvm::None,
4373 /*StrictOp=*/true,
4374 CE->getSourceRange(),
4375 CE->getOperatorLoc());
4376 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004377 default:
4378 break;
4379 }
4380 }
4381 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004382 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004383 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004384 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004385 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004386 return true;
4387}
4388
Alexey Bataeve3727102018-04-18 15:57:46 +00004389bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004390 // RHS of canonical loop form increment can be:
4391 // var + incr
4392 // incr + var
4393 // var - incr
4394 //
4395 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004396 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004397 if (BO->isAdditiveOp()) {
4398 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004399 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4400 return setStep(BO->getRHS(), !IsAdd);
4401 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4402 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004403 }
David Majnemer9d168222016-08-05 17:44:54 +00004404 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004405 bool IsAdd = CE->getOperator() == OO_Plus;
4406 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004407 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4408 return setStep(CE->getArg(1), !IsAdd);
4409 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4410 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004411 }
4412 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004413 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004414 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004415 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004416 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004417 return true;
4418}
4419
Alexey Bataeve3727102018-04-18 15:57:46 +00004420bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004421 // Check incr-expr for canonical loop form and return true if it
4422 // does not conform.
4423 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4424 // ++var
4425 // var++
4426 // --var
4427 // var--
4428 // var += incr
4429 // var -= incr
4430 // var = var + incr
4431 // var = incr + var
4432 // var = var - incr
4433 //
4434 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004435 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004436 return true;
4437 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004438 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4439 if (!ExprTemp->cleanupsHaveSideEffects())
4440 S = ExprTemp->getSubExpr();
4441
Alexander Musmana5f070a2014-10-01 06:03:56 +00004442 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004443 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004444 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004445 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004446 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4447 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004448 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004449 (UO->isDecrementOp() ? -1 : 1))
4450 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004451 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004452 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004453 switch (BO->getOpcode()) {
4454 case BO_AddAssign:
4455 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004456 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4457 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004458 break;
4459 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004460 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4461 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004462 break;
4463 default:
4464 break;
4465 }
David Majnemer9d168222016-08-05 17:44:54 +00004466 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004467 switch (CE->getOperator()) {
4468 case OO_PlusPlus:
4469 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004470 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4471 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004472 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004473 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004474 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4475 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004476 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004477 break;
4478 case OO_PlusEqual:
4479 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004480 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4481 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004482 break;
4483 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004484 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4485 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004486 break;
4487 default:
4488 break;
4489 }
4490 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004491 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004492 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004493 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004494 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004495 return true;
4496}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004497
Alexey Bataev5a3af132016-03-29 08:58:54 +00004498static ExprResult
4499tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004500 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004501 if (SemaRef.CurContext->isDependentContext())
4502 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004503 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4504 return SemaRef.PerformImplicitConversion(
4505 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4506 /*AllowExplicit=*/true);
4507 auto I = Captures.find(Capture);
4508 if (I != Captures.end())
4509 return buildCapture(SemaRef, Capture, I->second);
4510 DeclRefExpr *Ref = nullptr;
4511 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4512 Captures[Capture] = Ref;
4513 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004514}
4515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004516/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004517Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004518 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004520 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004521 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004522 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004523 SemaRef.getLangOpts().CPlusPlus) {
4524 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004525 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4526 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004527 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4528 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004529 if (!Upper || !Lower)
4530 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004531
4532 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4533
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004534 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004535 // BuildBinOp already emitted error, this one is to point user to upper
4536 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004537 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004538 << Upper->getSourceRange() << Lower->getSourceRange();
4539 return nullptr;
4540 }
4541 }
4542
4543 if (!Diff.isUsable())
4544 return nullptr;
4545
4546 // Upper - Lower [- 1]
4547 if (TestIsStrictOp)
4548 Diff = SemaRef.BuildBinOp(
4549 S, DefaultLoc, BO_Sub, Diff.get(),
4550 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4551 if (!Diff.isUsable())
4552 return nullptr;
4553
4554 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004555 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004556 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004557 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004558 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004559 if (!Diff.isUsable())
4560 return nullptr;
4561
4562 // Parentheses (for dumping/debugging purposes only).
4563 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4564 if (!Diff.isUsable())
4565 return nullptr;
4566
4567 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004568 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004569 if (!Diff.isUsable())
4570 return nullptr;
4571
Alexander Musman174b3ca2014-10-06 11:16:29 +00004572 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004573 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004574 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004575 bool UseVarType = VarType->hasIntegerRepresentation() &&
4576 C.getTypeSize(Type) > C.getTypeSize(VarType);
4577 if (!Type->isIntegerType() || UseVarType) {
4578 unsigned NewSize =
4579 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4580 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4581 : Type->hasSignedIntegerRepresentation();
4582 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004583 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4584 Diff = SemaRef.PerformImplicitConversion(
4585 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4586 if (!Diff.isUsable())
4587 return nullptr;
4588 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004589 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004590 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004591 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4592 if (NewSize != C.getTypeSize(Type)) {
4593 if (NewSize < C.getTypeSize(Type)) {
4594 assert(NewSize == 64 && "incorrect loop var size");
4595 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4596 << InitSrcRange << ConditionSrcRange;
4597 }
4598 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004599 NewSize, Type->hasSignedIntegerRepresentation() ||
4600 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004601 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4602 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4603 Sema::AA_Converting, true);
4604 if (!Diff.isUsable())
4605 return nullptr;
4606 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004607 }
4608 }
4609
Alexander Musmana5f070a2014-10-01 06:03:56 +00004610 return Diff.get();
4611}
4612
Alexey Bataeve3727102018-04-18 15:57:46 +00004613Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004614 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004615 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004616 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4617 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4618 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004619
Alexey Bataeve3727102018-04-18 15:57:46 +00004620 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4621 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004622 if (!NewLB.isUsable() || !NewUB.isUsable())
4623 return nullptr;
4624
Alexey Bataeve3727102018-04-18 15:57:46 +00004625 ExprResult CondExpr =
4626 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004627 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004628 (TestIsStrictOp ? BO_LT : BO_LE) :
4629 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004630 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004631 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004632 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4633 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004634 CondExpr = SemaRef.PerformImplicitConversion(
4635 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4636 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004637 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004638 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004639 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004640 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4641}
4642
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004643/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004644DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004645 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4646 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004647 auto *VD = dyn_cast<VarDecl>(LCDecl);
4648 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004649 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4650 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004651 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004652 const DSAStackTy::DSAVarData Data =
4653 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004654 // If the loop control decl is explicitly marked as private, do not mark it
4655 // as captured again.
4656 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4657 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004658 return Ref;
4659 }
4660 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004661 DefaultLoc);
4662}
4663
Alexey Bataeve3727102018-04-18 15:57:46 +00004664Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004665 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004666 QualType Type = LCDecl->getType().getNonReferenceType();
4667 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004668 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4669 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4670 isa<VarDecl>(LCDecl)
4671 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4672 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004673 if (PrivateVar->isInvalidDecl())
4674 return nullptr;
4675 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4676 }
4677 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004678}
4679
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004680/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004681Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004682
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004683/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004684Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004685
Alexey Bataevf138fda2018-08-13 19:04:24 +00004686Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4687 Scope *S, Expr *Counter,
4688 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4689 Expr *Inc, OverloadedOperatorKind OOK) {
4690 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4691 if (!Cnt)
4692 return nullptr;
4693 if (Inc) {
4694 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4695 "Expected only + or - operations for depend clauses.");
4696 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4697 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4698 if (!Cnt)
4699 return nullptr;
4700 }
4701 ExprResult Diff;
4702 QualType VarType = LCDecl->getType().getNonReferenceType();
4703 if (VarType->isIntegerType() || VarType->isPointerType() ||
4704 SemaRef.getLangOpts().CPlusPlus) {
4705 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004706 Expr *Upper = TestIsLessOp.getValue()
4707 ? Cnt
4708 : tryBuildCapture(SemaRef, UB, Captures).get();
4709 Expr *Lower = TestIsLessOp.getValue()
4710 ? tryBuildCapture(SemaRef, LB, Captures).get()
4711 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004712 if (!Upper || !Lower)
4713 return nullptr;
4714
4715 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4716
4717 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4718 // BuildBinOp already emitted error, this one is to point user to upper
4719 // and lower bound, and to tell what is passed to 'operator-'.
4720 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4721 << Upper->getSourceRange() << Lower->getSourceRange();
4722 return nullptr;
4723 }
4724 }
4725
4726 if (!Diff.isUsable())
4727 return nullptr;
4728
4729 // Parentheses (for dumping/debugging purposes only).
4730 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4731 if (!Diff.isUsable())
4732 return nullptr;
4733
4734 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4735 if (!NewStep.isUsable())
4736 return nullptr;
4737 // (Upper - Lower) / Step
4738 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4739 if (!Diff.isUsable())
4740 return nullptr;
4741
4742 return Diff.get();
4743}
4744
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004745/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004746struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004747 /// True if the condition operator is the strict compare operator (<, > or
4748 /// !=).
4749 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004750 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004751 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004752 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004753 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004754 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004755 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004756 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004757 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004758 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004759 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004760 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004761 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004762 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004763 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004764 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004765 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004766 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004767 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004768 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004769 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004770 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004771 SourceRange IncSrcRange;
4772};
4773
Alexey Bataev23b69422014-06-18 07:08:49 +00004774} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004775
Alexey Bataev9c821032015-04-30 04:23:23 +00004776void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4777 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4778 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004779 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4780 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004781 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00004782 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00004783 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004784 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4785 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004786 auto *VD = dyn_cast<VarDecl>(D);
4787 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004788 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004789 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00004790 } else {
4791 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4792 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004793 VD = cast<VarDecl>(Ref->getDecl());
4794 }
4795 }
4796 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00004797 const Decl *LD = DSAStack->getPossiblyLoopCunter();
4798 if (LD != D->getCanonicalDecl()) {
4799 DSAStack->resetPossibleLoopCounter();
4800 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4801 MarkDeclarationsReferencedInExpr(
4802 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4803 Var->getType().getNonLValueExprType(Context),
4804 ForLoc, /*RefersToCapture=*/true));
4805 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004806 }
4807 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004808 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004809 }
4810}
4811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004812/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004813/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00004814static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00004815 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4816 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00004817 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4818 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00004819 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004820 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00004821 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004822 // OpenMP [2.6, Canonical Loop Form]
4823 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004824 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004825 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004826 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004827 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00004828 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00004829 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004830 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00004831 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4832 SemaRef.Diag(DSA.getConstructLoc(),
4833 diag::note_omp_collapse_ordered_expr)
4834 << 2 << CollapseLoopCountExpr->getSourceRange()
4835 << OrderedLoopCountExpr->getSourceRange();
4836 else if (CollapseLoopCountExpr)
4837 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4838 diag::note_omp_collapse_ordered_expr)
4839 << 0 << CollapseLoopCountExpr->getSourceRange();
4840 else
4841 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4842 diag::note_omp_collapse_ordered_expr)
4843 << 1 << OrderedLoopCountExpr->getSourceRange();
4844 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004845 return true;
4846 }
4847 assert(For->getBody());
4848
4849 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4850
4851 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004852 Stmt *Init = For->getInit();
4853 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004854 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004855
4856 bool HasErrors = false;
4857
4858 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004859 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4860 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004861
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004862 // OpenMP [2.6, Canonical Loop Form]
4863 // Var is one of the following:
4864 // A variable of signed or unsigned integer type.
4865 // For C++, a variable of a random access iterator type.
4866 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004867 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004868 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4869 !VarType->isPointerType() &&
4870 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004871 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004872 << SemaRef.getLangOpts().CPlusPlus;
4873 HasErrors = true;
4874 }
4875
4876 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4877 // a Construct
4878 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4879 // parallel for construct is (are) private.
4880 // The loop iteration variable in the associated for-loop of a simd
4881 // construct with just one associated for-loop is linear with a
4882 // constant-linear-step that is the increment of the associated for-loop.
4883 // Exclude loop var from the list of variables with implicitly defined data
4884 // sharing attributes.
4885 VarsWithImplicitDSA.erase(LCDecl);
4886
4887 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4888 // in a Construct, C/C++].
4889 // The loop iteration variable in the associated for-loop of a simd
4890 // construct with just one associated for-loop may be listed in a linear
4891 // clause with a constant-linear-step that is the increment of the
4892 // associated for-loop.
4893 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4894 // parallel for construct may be listed in a private or lastprivate clause.
4895 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4896 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4897 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00004898 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004899 isOpenMPSimdDirective(DKind)
4900 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4901 : OMPC_private;
4902 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4903 DVar.CKind != PredeterminedCKind) ||
4904 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4905 isOpenMPDistributeDirective(DKind)) &&
4906 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4907 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4908 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004909 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004910 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4911 << getOpenMPClauseName(PredeterminedCKind);
4912 if (DVar.RefExpr == nullptr)
4913 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00004914 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004915 HasErrors = true;
4916 } else if (LoopDeclRefExpr != nullptr) {
4917 // Make the loop iteration variable private (for worksharing constructs),
4918 // linear (for simd directives with the only one associated loop) or
4919 // lastprivate (for simd directives with several collapsed or ordered
4920 // loops).
4921 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00004922 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004923 }
4924
4925 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4926
4927 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004928 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004929
4930 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004931 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004932 }
4933
Alexey Bataeve3727102018-04-18 15:57:46 +00004934 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004935 return HasErrors;
4936
Alexander Musmana5f070a2014-10-01 06:03:56 +00004937 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004938 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00004939 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4940 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004941 DSA.getCurScope(),
4942 (isOpenMPWorksharingDirective(DKind) ||
4943 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4944 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00004945 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4946 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4947 ResultIterSpace.CounterInit = ISC.buildCounterInit();
4948 ResultIterSpace.CounterStep = ISC.buildCounterStep();
4949 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4950 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4951 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4952 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00004953 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004954
Alexey Bataev62dbb972015-04-22 11:59:37 +00004955 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4956 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004957 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004958 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004959 ResultIterSpace.CounterInit == nullptr ||
4960 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00004961 if (!HasErrors && DSA.isOrderedRegion()) {
4962 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4963 if (CurrentNestedLoopCount <
4964 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4965 DSA.getOrderedRegionParam().second->setLoopNumIterations(
4966 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4967 DSA.getOrderedRegionParam().second->setLoopCounter(
4968 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4969 }
4970 }
4971 for (auto &Pair : DSA.getDoacrossDependClauses()) {
4972 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4973 // Erroneous case - clause has some problems.
4974 continue;
4975 }
4976 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4977 Pair.second.size() <= CurrentNestedLoopCount) {
4978 // Erroneous case - clause has some problems.
4979 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4980 continue;
4981 }
4982 Expr *CntValue;
4983 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4984 CntValue = ISC.buildOrderedLoopData(
4985 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4986 Pair.first->getDependencyLoc());
4987 else
4988 CntValue = ISC.buildOrderedLoopData(
4989 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4990 Pair.first->getDependencyLoc(),
4991 Pair.second[CurrentNestedLoopCount].first,
4992 Pair.second[CurrentNestedLoopCount].second);
4993 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
4994 }
4995 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004996
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004997 return HasErrors;
4998}
4999
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005000/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005001static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005002buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005003 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005004 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005005 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005006 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005007 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005008 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005009 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005010 VarRef.get()->getType())) {
5011 NewStart = SemaRef.PerformImplicitConversion(
5012 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5013 /*AllowExplicit=*/true);
5014 if (!NewStart.isUsable())
5015 return ExprError();
5016 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005017
Alexey Bataeve3727102018-04-18 15:57:46 +00005018 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005019 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5020 return Init;
5021}
5022
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005023/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005024static ExprResult buildCounterUpdate(
5025 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5026 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5027 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005028 // Add parentheses (for debugging purposes only).
5029 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5030 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5031 !Step.isUsable())
5032 return ExprError();
5033
Alexey Bataev5a3af132016-03-29 08:58:54 +00005034 ExprResult NewStep = Step;
5035 if (Captures)
5036 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005037 if (NewStep.isInvalid())
5038 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005039 ExprResult Update =
5040 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005041 if (!Update.isUsable())
5042 return ExprError();
5043
Alexey Bataevc0214e02016-02-16 12:13:49 +00005044 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5045 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005046 ExprResult NewStart = Start;
5047 if (Captures)
5048 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005049 if (NewStart.isInvalid())
5050 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005051
Alexey Bataevc0214e02016-02-16 12:13:49 +00005052 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5053 ExprResult SavedUpdate = Update;
5054 ExprResult UpdateVal;
5055 if (VarRef.get()->getType()->isOverloadableType() ||
5056 NewStart.get()->getType()->isOverloadableType() ||
5057 Update.get()->getType()->isOverloadableType()) {
5058 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5059 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5060 Update =
5061 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5062 if (Update.isUsable()) {
5063 UpdateVal =
5064 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5065 VarRef.get(), SavedUpdate.get());
5066 if (UpdateVal.isUsable()) {
5067 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5068 UpdateVal.get());
5069 }
5070 }
5071 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5072 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005073
Alexey Bataevc0214e02016-02-16 12:13:49 +00005074 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5075 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5076 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5077 NewStart.get(), SavedUpdate.get());
5078 if (!Update.isUsable())
5079 return ExprError();
5080
Alexey Bataev11481f52016-02-17 10:29:05 +00005081 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5082 VarRef.get()->getType())) {
5083 Update = SemaRef.PerformImplicitConversion(
5084 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5085 if (!Update.isUsable())
5086 return ExprError();
5087 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005088
5089 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5090 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005091 return Update;
5092}
5093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005094/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005095/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005096static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005097 if (E == nullptr)
5098 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005099 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005100 QualType OldType = E->getType();
5101 unsigned HasBits = C.getTypeSize(OldType);
5102 if (HasBits >= Bits)
5103 return ExprResult(E);
5104 // OK to convert to signed, because new type has more bits than old.
5105 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5106 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5107 true);
5108}
5109
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005110/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005111/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005112static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005113 if (E == nullptr)
5114 return false;
5115 llvm::APSInt Result;
5116 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5117 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5118 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005119}
5120
Alexey Bataev5a3af132016-03-29 08:58:54 +00005121/// Build preinits statement for the given declarations.
5122static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005123 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005124 if (!PreInits.empty()) {
5125 return new (Context) DeclStmt(
5126 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5127 SourceLocation(), SourceLocation());
5128 }
5129 return nullptr;
5130}
5131
5132/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005133static Stmt *
5134buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005135 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005136 if (!Captures.empty()) {
5137 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005138 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005139 PreInits.push_back(Pair.second->getDecl());
5140 return buildPreInits(Context, PreInits);
5141 }
5142 return nullptr;
5143}
5144
5145/// Build postupdate expression for the given list of postupdates expressions.
5146static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5147 Expr *PostUpdate = nullptr;
5148 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005149 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005150 Expr *ConvE = S.BuildCStyleCastExpr(
5151 E->getExprLoc(),
5152 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5153 E->getExprLoc(), E)
5154 .get();
5155 PostUpdate = PostUpdate
5156 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5157 PostUpdate, ConvE)
5158 .get()
5159 : ConvE;
5160 }
5161 }
5162 return PostUpdate;
5163}
5164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005165/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005166/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5167/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005168static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005169checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005170 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5171 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005172 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005173 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005174 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005175 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005176 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005177 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005178 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005179 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005180 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005181 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005182 if (OrderedLoopCountExpr) {
5183 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005184 Expr::EvalResult EVResult;
5185 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5186 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005187 if (Result.getLimitedValue() < NestedLoopCount) {
5188 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5189 diag::err_omp_wrong_ordered_loop_count)
5190 << OrderedLoopCountExpr->getSourceRange();
5191 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5192 diag::note_collapse_loop_count)
5193 << CollapseLoopCountExpr->getSourceRange();
5194 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005195 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005196 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005197 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005198 // This is helper routine for loop directives (e.g., 'for', 'simd',
5199 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005200 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005201 SmallVector<LoopIterationSpace, 4> IterSpaces(
5202 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005203 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005204 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005205 if (checkOpenMPIterationSpace(
5206 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5207 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5208 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5209 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005210 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005211 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005212 // OpenMP [2.8.1, simd construct, Restrictions]
5213 // All loops associated with the construct must be perfectly nested; that
5214 // is, there must be no intervening code nor any OpenMP directive between
5215 // any two loops.
5216 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005217 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005218 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5219 if (checkOpenMPIterationSpace(
5220 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5221 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5222 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5223 Captures))
5224 return 0;
5225 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5226 // Handle initialization of captured loop iterator variables.
5227 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5228 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5229 Captures[DRE] = DRE;
5230 }
5231 }
5232 // Move on to the next nested for loop, or to the loop body.
5233 // OpenMP [2.8.1, simd construct, Restrictions]
5234 // All loops associated with the construct must be perfectly nested; that
5235 // is, there must be no intervening code nor any OpenMP directive between
5236 // any two loops.
5237 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5238 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005239
Alexander Musmana5f070a2014-10-01 06:03:56 +00005240 Built.clear(/* size */ NestedLoopCount);
5241
5242 if (SemaRef.CurContext->isDependentContext())
5243 return NestedLoopCount;
5244
5245 // An example of what is generated for the following code:
5246 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005247 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005248 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005249 // for (k = 0; k < NK; ++k)
5250 // for (j = J0; j < NJ; j+=2) {
5251 // <loop body>
5252 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005253 //
5254 // We generate the code below.
5255 // Note: the loop body may be outlined in CodeGen.
5256 // Note: some counters may be C++ classes, operator- is used to find number of
5257 // iterations and operator+= to calculate counter value.
5258 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5259 // or i64 is currently supported).
5260 //
5261 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5262 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5263 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5264 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5265 // // similar updates for vars in clauses (e.g. 'linear')
5266 // <loop body (using local i and j)>
5267 // }
5268 // i = NI; // assign final values of counters
5269 // j = NJ;
5270 //
5271
5272 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5273 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005274 // Precondition tests if there is at least one iteration (all conditions are
5275 // true).
5276 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005277 Expr *N0 = IterSpaces[0].NumIterations;
5278 ExprResult LastIteration32 =
5279 widenIterationCount(/*Bits=*/32,
5280 SemaRef
5281 .PerformImplicitConversion(
5282 N0->IgnoreImpCasts(), N0->getType(),
5283 Sema::AA_Converting, /*AllowExplicit=*/true)
5284 .get(),
5285 SemaRef);
5286 ExprResult LastIteration64 = widenIterationCount(
5287 /*Bits=*/64,
5288 SemaRef
5289 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5290 Sema::AA_Converting,
5291 /*AllowExplicit=*/true)
5292 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005293 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005294
5295 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5296 return NestedLoopCount;
5297
Alexey Bataeve3727102018-04-18 15:57:46 +00005298 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005299 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5300
5301 Scope *CurScope = DSA.getCurScope();
5302 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005303 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005304 PreCond =
5305 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5306 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005307 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005308 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005309 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005310 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5311 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005312 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005313 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005314 SemaRef
5315 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5316 Sema::AA_Converting,
5317 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005318 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005319 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005320 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005321 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005322 SemaRef
5323 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5324 Sema::AA_Converting,
5325 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005326 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005327 }
5328
5329 // Choose either the 32-bit or 64-bit version.
5330 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005331 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5332 (LastIteration32.isUsable() &&
5333 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5334 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5335 fitsInto(
5336 /*Bits=*/32,
5337 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5338 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005339 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005340 QualType VType = LastIteration.get()->getType();
5341 QualType RealVType = VType;
5342 QualType StrideVType = VType;
5343 if (isOpenMPTaskLoopDirective(DKind)) {
5344 VType =
5345 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5346 StrideVType =
5347 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5348 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005349
5350 if (!LastIteration.isUsable())
5351 return 0;
5352
5353 // Save the number of iterations.
5354 ExprResult NumIterations = LastIteration;
5355 {
5356 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005357 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5358 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005359 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5360 if (!LastIteration.isUsable())
5361 return 0;
5362 }
5363
5364 // Calculate the last iteration number beforehand instead of doing this on
5365 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5366 llvm::APSInt Result;
5367 bool IsConstant =
5368 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5369 ExprResult CalcLastIteration;
5370 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005371 ExprResult SaveRef =
5372 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005373 LastIteration = SaveRef;
5374
5375 // Prepare SaveRef + 1.
5376 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005377 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005378 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5379 if (!NumIterations.isUsable())
5380 return 0;
5381 }
5382
5383 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5384
David Majnemer9d168222016-08-05 17:44:54 +00005385 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005386 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005387 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5388 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005389 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005390 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5391 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005392 SemaRef.AddInitializerToDecl(LBDecl,
5393 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5394 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005395
5396 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005397 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5398 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005399 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005400 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005401
5402 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5403 // This will be used to implement clause 'lastprivate'.
5404 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005405 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5406 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005407 SemaRef.AddInitializerToDecl(ILDecl,
5408 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5409 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005410
5411 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005412 VarDecl *STDecl =
5413 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5414 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005415 SemaRef.AddInitializerToDecl(STDecl,
5416 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5417 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005418
5419 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005420 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005421 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5422 UB.get(), LastIteration.get());
5423 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005424 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5425 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005426 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5427 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005428 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005429
5430 // If we have a combined directive that combines 'distribute', 'for' or
5431 // 'simd' we need to be able to access the bounds of the schedule of the
5432 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5433 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5434 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005435 // Lower bound variable, initialized with zero.
5436 VarDecl *CombLBDecl =
5437 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5438 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5439 SemaRef.AddInitializerToDecl(
5440 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5441 /*DirectInit*/ false);
5442
5443 // Upper bound variable, initialized with last iteration number.
5444 VarDecl *CombUBDecl =
5445 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5446 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5447 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5448 /*DirectInit*/ false);
5449
5450 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5451 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5452 ExprResult CombCondOp =
5453 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5454 LastIteration.get(), CombUB.get());
5455 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5456 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005457 CombEUB =
5458 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005459
Alexey Bataeve3727102018-04-18 15:57:46 +00005460 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005461 // We expect to have at least 2 more parameters than the 'parallel'
5462 // directive does - the lower and upper bounds of the previous schedule.
5463 assert(CD->getNumParams() >= 4 &&
5464 "Unexpected number of parameters in loop combined directive");
5465
5466 // Set the proper type for the bounds given what we learned from the
5467 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005468 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5469 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005470
5471 // Previous lower and upper bounds are obtained from the region
5472 // parameters.
5473 PrevLB =
5474 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5475 PrevUB =
5476 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5477 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005478 }
5479
5480 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005481 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005482 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005483 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005484 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5485 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005486 Expr *RHS =
5487 (isOpenMPWorksharingDirective(DKind) ||
5488 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5489 ? LB.get()
5490 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005491 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005492 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005493
5494 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5495 Expr *CombRHS =
5496 (isOpenMPWorksharingDirective(DKind) ||
5497 isOpenMPTaskLoopDirective(DKind) ||
5498 isOpenMPDistributeDirective(DKind))
5499 ? CombLB.get()
5500 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5501 CombInit =
5502 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005503 CombInit =
5504 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005505 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005506 }
5507
Alexey Bataev316ccf62019-01-29 18:51:58 +00005508 bool UseStrictCompare =
5509 RealVType->hasUnsignedIntegerRepresentation() &&
5510 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5511 return LIS.IsStrictCompare;
5512 });
5513 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5514 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005515 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005516 Expr *BoundUB = UB.get();
5517 if (UseStrictCompare) {
5518 BoundUB =
5519 SemaRef
5520 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5521 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5522 .get();
5523 BoundUB =
5524 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5525 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005526 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005527 (isOpenMPWorksharingDirective(DKind) ||
5528 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005529 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5530 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5531 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005532 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5533 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005534 ExprResult CombDistCond;
5535 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005536 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5537 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005538 }
5539
Carlo Bertolliffafe102017-04-20 00:39:39 +00005540 ExprResult CombCond;
5541 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005542 Expr *BoundCombUB = CombUB.get();
5543 if (UseStrictCompare) {
5544 BoundCombUB =
5545 SemaRef
5546 .BuildBinOp(
5547 CurScope, CondLoc, BO_Add, BoundCombUB,
5548 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5549 .get();
5550 BoundCombUB =
5551 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5552 .get();
5553 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005554 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005555 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5556 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005557 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005558 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005559 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005560 ExprResult Inc =
5561 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5562 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5563 if (!Inc.isUsable())
5564 return 0;
5565 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005566 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005567 if (!Inc.isUsable())
5568 return 0;
5569
5570 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5571 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005572 // In combined construct, add combined version that use CombLB and CombUB
5573 // base variables for the update
5574 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005575 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5576 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005577 // LB + ST
5578 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5579 if (!NextLB.isUsable())
5580 return 0;
5581 // LB = LB + ST
5582 NextLB =
5583 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005584 NextLB =
5585 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005586 if (!NextLB.isUsable())
5587 return 0;
5588 // UB + ST
5589 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5590 if (!NextUB.isUsable())
5591 return 0;
5592 // UB = UB + ST
5593 NextUB =
5594 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005595 NextUB =
5596 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005597 if (!NextUB.isUsable())
5598 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005599 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5600 CombNextLB =
5601 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5602 if (!NextLB.isUsable())
5603 return 0;
5604 // LB = LB + ST
5605 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5606 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005607 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5608 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005609 if (!CombNextLB.isUsable())
5610 return 0;
5611 // UB + ST
5612 CombNextUB =
5613 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5614 if (!CombNextUB.isUsable())
5615 return 0;
5616 // UB = UB + ST
5617 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5618 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005619 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5620 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005621 if (!CombNextUB.isUsable())
5622 return 0;
5623 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005624 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005625
Carlo Bertolliffafe102017-04-20 00:39:39 +00005626 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005627 // directive with for as IV = IV + ST; ensure upper bound expression based
5628 // on PrevUB instead of NumIterations - used to implement 'for' when found
5629 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005630 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005631 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005632 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005633 DistCond = SemaRef.BuildBinOp(
5634 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005635 assert(DistCond.isUsable() && "distribute cond expr was not built");
5636
5637 DistInc =
5638 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5639 assert(DistInc.isUsable() && "distribute inc expr was not built");
5640 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5641 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005642 DistInc =
5643 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005644 assert(DistInc.isUsable() && "distribute inc expr was not built");
5645
5646 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5647 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005648 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005649 ExprResult IsUBGreater =
5650 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5651 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5652 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5653 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5654 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005655 PrevEUB =
5656 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005657
Alexey Bataev316ccf62019-01-29 18:51:58 +00005658 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5659 // parallel for is in combination with a distribute directive with
5660 // schedule(static, 1)
5661 Expr *BoundPrevUB = PrevUB.get();
5662 if (UseStrictCompare) {
5663 BoundPrevUB =
5664 SemaRef
5665 .BuildBinOp(
5666 CurScope, CondLoc, BO_Add, BoundPrevUB,
5667 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5668 .get();
5669 BoundPrevUB =
5670 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5671 .get();
5672 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005673 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005674 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5675 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005676 }
5677
Alexander Musmana5f070a2014-10-01 06:03:56 +00005678 // Build updates and final values of the loop counters.
5679 bool HasErrors = false;
5680 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005681 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005682 Built.Updates.resize(NestedLoopCount);
5683 Built.Finals.resize(NestedLoopCount);
5684 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005685 // We implement the following algorithm for obtaining the
5686 // original loop iteration variable values based on the
5687 // value of the collapsed loop iteration variable IV.
5688 //
5689 // Let n+1 be the number of collapsed loops in the nest.
5690 // Iteration variables (I0, I1, .... In)
5691 // Iteration counts (N0, N1, ... Nn)
5692 //
5693 // Acc = IV;
5694 //
5695 // To compute Ik for loop k, 0 <= k <= n, generate:
5696 // Prod = N(k+1) * N(k+2) * ... * Nn;
5697 // Ik = Acc / Prod;
5698 // Acc -= Ik * Prod;
5699 //
5700 ExprResult Acc = IV;
5701 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005702 LoopIterationSpace &IS = IterSpaces[Cnt];
5703 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005704 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005705
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005706 // Compute prod
5707 ExprResult Prod =
5708 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5709 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5710 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5711 IterSpaces[K].NumIterations);
5712
5713 // Iter = Acc / Prod
5714 // If there is at least one more inner loop to avoid
5715 // multiplication by 1.
5716 if (Cnt + 1 < NestedLoopCount)
5717 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5718 Acc.get(), Prod.get());
5719 else
5720 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005721 if (!Iter.isUsable()) {
5722 HasErrors = true;
5723 break;
5724 }
5725
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005726 // Update Acc:
5727 // Acc -= Iter * Prod
5728 // Check if there is at least one more inner loop to avoid
5729 // multiplication by 1.
5730 if (Cnt + 1 < NestedLoopCount)
5731 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5732 Iter.get(), Prod.get());
5733 else
5734 Prod = Iter;
5735 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5736 Acc.get(), Prod.get());
5737
Alexey Bataev39f915b82015-05-08 10:41:21 +00005738 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005739 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005740 DeclRefExpr *CounterVar = buildDeclRefExpr(
5741 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5742 /*RefersToCapture=*/true);
5743 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005744 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005745 if (!Init.isUsable()) {
5746 HasErrors = true;
5747 break;
5748 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005749 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005750 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5751 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005752 if (!Update.isUsable()) {
5753 HasErrors = true;
5754 break;
5755 }
5756
5757 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005758 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005759 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005760 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005761 if (!Final.isUsable()) {
5762 HasErrors = true;
5763 break;
5764 }
5765
Alexander Musmana5f070a2014-10-01 06:03:56 +00005766 if (!Update.isUsable() || !Final.isUsable()) {
5767 HasErrors = true;
5768 break;
5769 }
5770 // Save results
5771 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005772 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005773 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005774 Built.Updates[Cnt] = Update.get();
5775 Built.Finals[Cnt] = Final.get();
5776 }
5777 }
5778
5779 if (HasErrors)
5780 return 0;
5781
5782 // Save results
5783 Built.IterationVarRef = IV.get();
5784 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005785 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005786 Built.CalcLastIteration = SemaRef
5787 .ActOnFinishFullExpr(CalcLastIteration.get(),
5788 /*DiscardedValue*/ false)
5789 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005790 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005791 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005792 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005793 Built.Init = Init.get();
5794 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005795 Built.LB = LB.get();
5796 Built.UB = UB.get();
5797 Built.IL = IL.get();
5798 Built.ST = ST.get();
5799 Built.EUB = EUB.get();
5800 Built.NLB = NextLB.get();
5801 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005802 Built.PrevLB = PrevLB.get();
5803 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005804 Built.DistInc = DistInc.get();
5805 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005806 Built.DistCombinedFields.LB = CombLB.get();
5807 Built.DistCombinedFields.UB = CombUB.get();
5808 Built.DistCombinedFields.EUB = CombEUB.get();
5809 Built.DistCombinedFields.Init = CombInit.get();
5810 Built.DistCombinedFields.Cond = CombCond.get();
5811 Built.DistCombinedFields.NLB = CombNextLB.get();
5812 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005813 Built.DistCombinedFields.DistCond = CombDistCond.get();
5814 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005815
Alexey Bataevabfc0692014-06-25 06:52:00 +00005816 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005817}
5818
Alexey Bataev10e775f2015-07-30 11:36:16 +00005819static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005820 auto CollapseClauses =
5821 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5822 if (CollapseClauses.begin() != CollapseClauses.end())
5823 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005824 return nullptr;
5825}
5826
Alexey Bataev10e775f2015-07-30 11:36:16 +00005827static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005828 auto OrderedClauses =
5829 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5830 if (OrderedClauses.begin() != OrderedClauses.end())
5831 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005832 return nullptr;
5833}
5834
Kelvin Lic5609492016-07-15 04:39:07 +00005835static bool checkSimdlenSafelenSpecified(Sema &S,
5836 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005837 const OMPSafelenClause *Safelen = nullptr;
5838 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00005839
Alexey Bataeve3727102018-04-18 15:57:46 +00005840 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00005841 if (Clause->getClauseKind() == OMPC_safelen)
5842 Safelen = cast<OMPSafelenClause>(Clause);
5843 else if (Clause->getClauseKind() == OMPC_simdlen)
5844 Simdlen = cast<OMPSimdlenClause>(Clause);
5845 if (Safelen && Simdlen)
5846 break;
5847 }
5848
5849 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005850 const Expr *SimdlenLength = Simdlen->getSimdlen();
5851 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00005852 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5853 SimdlenLength->isInstantiationDependent() ||
5854 SimdlenLength->containsUnexpandedParameterPack())
5855 return false;
5856 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5857 SafelenLength->isInstantiationDependent() ||
5858 SafelenLength->containsUnexpandedParameterPack())
5859 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005860 Expr::EvalResult SimdlenResult, SafelenResult;
5861 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5862 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5863 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5864 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00005865 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5866 // If both simdlen and safelen clauses are specified, the value of the
5867 // simdlen parameter must be less than or equal to the value of the safelen
5868 // parameter.
5869 if (SimdlenRes > SafelenRes) {
5870 S.Diag(SimdlenLength->getExprLoc(),
5871 diag::err_omp_wrong_simdlen_safelen_values)
5872 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5873 return true;
5874 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005875 }
5876 return false;
5877}
5878
Alexey Bataeve3727102018-04-18 15:57:46 +00005879StmtResult
5880Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5881 SourceLocation StartLoc, SourceLocation EndLoc,
5882 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005883 if (!AStmt)
5884 return StmtError();
5885
5886 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005887 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005888 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5889 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005890 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005891 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5892 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005893 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005894 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005895
Alexander Musmana5f070a2014-10-01 06:03:56 +00005896 assert((CurContext->isDependentContext() || B.builtAll()) &&
5897 "omp simd loop exprs were not built");
5898
Alexander Musman3276a272015-03-21 10:12:56 +00005899 if (!CurContext->isDependentContext()) {
5900 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005901 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005902 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005903 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005904 B.NumIterations, *this, CurScope,
5905 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005906 return StmtError();
5907 }
5908 }
5909
Kelvin Lic5609492016-07-15 04:39:07 +00005910 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005911 return StmtError();
5912
Reid Kleckner87a31802018-03-12 21:43:02 +00005913 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005914 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5915 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005916}
5917
Alexey Bataeve3727102018-04-18 15:57:46 +00005918StmtResult
5919Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5920 SourceLocation StartLoc, SourceLocation EndLoc,
5921 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005922 if (!AStmt)
5923 return StmtError();
5924
5925 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005926 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005927 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5928 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005929 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005930 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5931 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005932 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005933 return StmtError();
5934
Alexander Musmana5f070a2014-10-01 06:03:56 +00005935 assert((CurContext->isDependentContext() || B.builtAll()) &&
5936 "omp for loop exprs were not built");
5937
Alexey Bataev54acd402015-08-04 11:18:19 +00005938 if (!CurContext->isDependentContext()) {
5939 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005940 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005941 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005942 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005943 B.NumIterations, *this, CurScope,
5944 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005945 return StmtError();
5946 }
5947 }
5948
Reid Kleckner87a31802018-03-12 21:43:02 +00005949 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005950 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005951 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005952}
5953
Alexander Musmanf82886e2014-09-18 05:12:34 +00005954StmtResult Sema::ActOnOpenMPForSimdDirective(
5955 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00005956 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005957 if (!AStmt)
5958 return StmtError();
5959
5960 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005961 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005962 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5963 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005964 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00005965 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00005966 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5967 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005968 if (NestedLoopCount == 0)
5969 return StmtError();
5970
Alexander Musmanc6388682014-12-15 07:07:06 +00005971 assert((CurContext->isDependentContext() || B.builtAll()) &&
5972 "omp for simd loop exprs were not built");
5973
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005974 if (!CurContext->isDependentContext()) {
5975 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005976 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005977 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005978 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005979 B.NumIterations, *this, CurScope,
5980 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005981 return StmtError();
5982 }
5983 }
5984
Kelvin Lic5609492016-07-15 04:39:07 +00005985 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005986 return StmtError();
5987
Reid Kleckner87a31802018-03-12 21:43:02 +00005988 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005989 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5990 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005991}
5992
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005993StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5994 Stmt *AStmt,
5995 SourceLocation StartLoc,
5996 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005997 if (!AStmt)
5998 return StmtError();
5999
6000 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006001 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006002 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006003 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006004 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006005 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006006 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006007 return StmtError();
6008 // All associated statements must be '#pragma omp section' except for
6009 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006010 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006011 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6012 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006013 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006014 diag::err_omp_sections_substmt_not_section);
6015 return StmtError();
6016 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006017 cast<OMPSectionDirective>(SectionStmt)
6018 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006019 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006020 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006021 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006022 return StmtError();
6023 }
6024
Reid Kleckner87a31802018-03-12 21:43:02 +00006025 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006026
Alexey Bataev25e5b442015-09-15 12:52:43 +00006027 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6028 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006029}
6030
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006031StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6032 SourceLocation StartLoc,
6033 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006034 if (!AStmt)
6035 return StmtError();
6036
6037 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006038
Reid Kleckner87a31802018-03-12 21:43:02 +00006039 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006040 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006041
Alexey Bataev25e5b442015-09-15 12:52:43 +00006042 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6043 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006044}
6045
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006046StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6047 Stmt *AStmt,
6048 SourceLocation StartLoc,
6049 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006050 if (!AStmt)
6051 return StmtError();
6052
6053 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006054
Reid Kleckner87a31802018-03-12 21:43:02 +00006055 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006056
Alexey Bataev3255bf32015-01-19 05:20:46 +00006057 // OpenMP [2.7.3, single Construct, Restrictions]
6058 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006059 const OMPClause *Nowait = nullptr;
6060 const OMPClause *Copyprivate = nullptr;
6061 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006062 if (Clause->getClauseKind() == OMPC_nowait)
6063 Nowait = Clause;
6064 else if (Clause->getClauseKind() == OMPC_copyprivate)
6065 Copyprivate = Clause;
6066 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006067 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006068 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006069 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006070 return StmtError();
6071 }
6072 }
6073
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006074 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6075}
6076
Alexander Musman80c22892014-07-17 08:54:58 +00006077StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6078 SourceLocation StartLoc,
6079 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006080 if (!AStmt)
6081 return StmtError();
6082
6083 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006084
Reid Kleckner87a31802018-03-12 21:43:02 +00006085 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006086
6087 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6088}
6089
Alexey Bataev28c75412015-12-15 08:19:24 +00006090StmtResult Sema::ActOnOpenMPCriticalDirective(
6091 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6092 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006093 if (!AStmt)
6094 return StmtError();
6095
6096 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006097
Alexey Bataev28c75412015-12-15 08:19:24 +00006098 bool ErrorFound = false;
6099 llvm::APSInt Hint;
6100 SourceLocation HintLoc;
6101 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006102 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006103 if (C->getClauseKind() == OMPC_hint) {
6104 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006105 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006106 ErrorFound = true;
6107 }
6108 Expr *E = cast<OMPHintClause>(C)->getHint();
6109 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006110 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006111 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006112 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006113 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006114 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006115 }
6116 }
6117 }
6118 if (ErrorFound)
6119 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006120 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006121 if (Pair.first && DirName.getName() && !DependentHint) {
6122 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6123 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006124 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006125 Diag(HintLoc, diag::note_omp_critical_hint_here)
6126 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006127 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006128 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006129 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006130 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006131 << 1
6132 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6133 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006134 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006135 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006136 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006137 }
6138 }
6139
Reid Kleckner87a31802018-03-12 21:43:02 +00006140 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006141
Alexey Bataev28c75412015-12-15 08:19:24 +00006142 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6143 Clauses, AStmt);
6144 if (!Pair.first && DirName.getName() && !DependentHint)
6145 DSAStack->addCriticalWithHint(Dir, Hint);
6146 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006147}
6148
Alexey Bataev4acb8592014-07-07 13:01:15 +00006149StmtResult Sema::ActOnOpenMPParallelForDirective(
6150 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006151 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006152 if (!AStmt)
6153 return StmtError();
6154
Alexey Bataeve3727102018-04-18 15:57:46 +00006155 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006156 // 1.2.2 OpenMP Language Terminology
6157 // Structured block - An executable statement with a single entry at the
6158 // top and a single exit at the bottom.
6159 // The point of exit cannot be a branch out of the structured block.
6160 // longjmp() and throw() must not violate the entry/exit criteria.
6161 CS->getCapturedDecl()->setNothrow();
6162
Alexander Musmanc6388682014-12-15 07:07:06 +00006163 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006164 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6165 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006166 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006167 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006168 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6169 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006170 if (NestedLoopCount == 0)
6171 return StmtError();
6172
Alexander Musmana5f070a2014-10-01 06:03:56 +00006173 assert((CurContext->isDependentContext() || B.builtAll()) &&
6174 "omp parallel for loop exprs were not built");
6175
Alexey Bataev54acd402015-08-04 11:18:19 +00006176 if (!CurContext->isDependentContext()) {
6177 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006178 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006179 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006180 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006181 B.NumIterations, *this, CurScope,
6182 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006183 return StmtError();
6184 }
6185 }
6186
Reid Kleckner87a31802018-03-12 21:43:02 +00006187 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006188 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006189 NestedLoopCount, Clauses, AStmt, B,
6190 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006191}
6192
Alexander Musmane4e893b2014-09-23 09:33:00 +00006193StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006195 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006196 if (!AStmt)
6197 return StmtError();
6198
Alexey Bataeve3727102018-04-18 15:57:46 +00006199 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006200 // 1.2.2 OpenMP Language Terminology
6201 // Structured block - An executable statement with a single entry at the
6202 // top and a single exit at the bottom.
6203 // The point of exit cannot be a branch out of the structured block.
6204 // longjmp() and throw() must not violate the entry/exit criteria.
6205 CS->getCapturedDecl()->setNothrow();
6206
Alexander Musmanc6388682014-12-15 07:07:06 +00006207 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006208 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6209 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006210 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006211 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006212 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6213 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006214 if (NestedLoopCount == 0)
6215 return StmtError();
6216
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006217 if (!CurContext->isDependentContext()) {
6218 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006219 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006220 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006221 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006222 B.NumIterations, *this, CurScope,
6223 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006224 return StmtError();
6225 }
6226 }
6227
Kelvin Lic5609492016-07-15 04:39:07 +00006228 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006229 return StmtError();
6230
Reid Kleckner87a31802018-03-12 21:43:02 +00006231 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006232 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006233 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006234}
6235
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006236StmtResult
6237Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6238 Stmt *AStmt, SourceLocation StartLoc,
6239 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006240 if (!AStmt)
6241 return StmtError();
6242
6243 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006244 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006245 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006246 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006247 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006248 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006249 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006250 return StmtError();
6251 // All associated statements must be '#pragma omp section' except for
6252 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006253 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006254 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6255 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006256 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006257 diag::err_omp_parallel_sections_substmt_not_section);
6258 return StmtError();
6259 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006260 cast<OMPSectionDirective>(SectionStmt)
6261 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006262 }
6263 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006264 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006265 diag::err_omp_parallel_sections_not_compound_stmt);
6266 return StmtError();
6267 }
6268
Reid Kleckner87a31802018-03-12 21:43:02 +00006269 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006270
Alexey Bataev25e5b442015-09-15 12:52:43 +00006271 return OMPParallelSectionsDirective::Create(
6272 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006273}
6274
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006275StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6276 Stmt *AStmt, SourceLocation StartLoc,
6277 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006278 if (!AStmt)
6279 return StmtError();
6280
David Majnemer9d168222016-08-05 17:44:54 +00006281 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006282 // 1.2.2 OpenMP Language Terminology
6283 // Structured block - An executable statement with a single entry at the
6284 // top and a single exit at the bottom.
6285 // The point of exit cannot be a branch out of the structured block.
6286 // longjmp() and throw() must not violate the entry/exit criteria.
6287 CS->getCapturedDecl()->setNothrow();
6288
Reid Kleckner87a31802018-03-12 21:43:02 +00006289 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006290
Alexey Bataev25e5b442015-09-15 12:52:43 +00006291 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6292 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006293}
6294
Alexey Bataev68446b72014-07-18 07:47:19 +00006295StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6296 SourceLocation EndLoc) {
6297 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6298}
6299
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006300StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6301 SourceLocation EndLoc) {
6302 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6303}
6304
Alexey Bataev2df347a2014-07-18 10:17:07 +00006305StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6306 SourceLocation EndLoc) {
6307 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6308}
6309
Alexey Bataev169d96a2017-07-18 20:17:46 +00006310StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6311 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006312 SourceLocation StartLoc,
6313 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006314 if (!AStmt)
6315 return StmtError();
6316
6317 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006318
Reid Kleckner87a31802018-03-12 21:43:02 +00006319 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006320
Alexey Bataev169d96a2017-07-18 20:17:46 +00006321 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006322 AStmt,
6323 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006324}
6325
Alexey Bataev6125da92014-07-21 11:26:11 +00006326StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6327 SourceLocation StartLoc,
6328 SourceLocation EndLoc) {
6329 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6330 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6331}
6332
Alexey Bataev346265e2015-09-25 10:37:12 +00006333StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6334 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006335 SourceLocation StartLoc,
6336 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006337 const OMPClause *DependFound = nullptr;
6338 const OMPClause *DependSourceClause = nullptr;
6339 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006340 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006341 const OMPThreadsClause *TC = nullptr;
6342 const OMPSIMDClause *SC = nullptr;
6343 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006344 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6345 DependFound = C;
6346 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6347 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006348 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006349 << getOpenMPDirectiveName(OMPD_ordered)
6350 << getOpenMPClauseName(OMPC_depend) << 2;
6351 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006352 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006353 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006354 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006355 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006356 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006357 << 0;
6358 ErrorFound = true;
6359 }
6360 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6361 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006362 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006363 << 1;
6364 ErrorFound = true;
6365 }
6366 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006367 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006368 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006369 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006370 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006371 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006372 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006373 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006374 if (!ErrorFound && !SC &&
6375 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006376 // OpenMP [2.8.1,simd Construct, Restrictions]
6377 // An ordered construct with the simd clause is the only OpenMP construct
6378 // that can appear in the simd region.
6379 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006380 ErrorFound = true;
6381 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006382 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006383 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6384 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006385 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006386 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006387 diag::err_omp_ordered_directive_without_param);
6388 ErrorFound = true;
6389 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006390 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006391 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006392 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6393 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006394 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006395 ErrorFound = true;
6396 }
6397 }
6398 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006399 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006400
6401 if (AStmt) {
6402 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6403
Reid Kleckner87a31802018-03-12 21:43:02 +00006404 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006405 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006406
6407 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006408}
6409
Alexey Bataev1d160b12015-03-13 12:27:31 +00006410namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006411/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006412/// construct.
6413class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006414 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006415 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006416 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006417 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006418 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006419 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006420 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006421 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006422 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006423 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006424 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006425 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006426 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006427 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006428 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006429 /// expression.
6430 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006431 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006432 /// part.
6433 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006434 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006435 NoError
6436 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006437 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006438 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006439 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006440 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006441 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006442 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006443 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006444 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006445 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006446 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6447 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6448 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006449 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006450 /// important for non-associative operations.
6451 bool IsXLHSInRHSPart;
6452 BinaryOperatorKind Op;
6453 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006454 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006455 /// if it is a prefix unary operation.
6456 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006457
6458public:
6459 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006460 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006461 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006462 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006463 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006464 /// expression. If DiagId and NoteId == 0, then only check is performed
6465 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006466 /// \param DiagId Diagnostic which should be emitted if error is found.
6467 /// \param NoteId Diagnostic note for the main error message.
6468 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006469 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006470 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006471 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006472 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006473 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006474 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006475 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6476 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6477 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006478 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006479 /// false otherwise.
6480 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6481
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006482 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006483 /// if it is a prefix unary operation.
6484 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6485
Alexey Bataev1d160b12015-03-13 12:27:31 +00006486private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006487 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6488 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006489};
6490} // namespace
6491
6492bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6493 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6494 ExprAnalysisErrorCode ErrorFound = NoError;
6495 SourceLocation ErrorLoc, NoteLoc;
6496 SourceRange ErrorRange, NoteRange;
6497 // Allowed constructs are:
6498 // x = x binop expr;
6499 // x = expr binop x;
6500 if (AtomicBinOp->getOpcode() == BO_Assign) {
6501 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006502 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006503 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6504 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6505 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6506 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006507 Op = AtomicInnerBinOp->getOpcode();
6508 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006509 Expr *LHS = AtomicInnerBinOp->getLHS();
6510 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006511 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6512 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6513 /*Canonical=*/true);
6514 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6515 /*Canonical=*/true);
6516 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6517 /*Canonical=*/true);
6518 if (XId == LHSId) {
6519 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006520 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006521 } else if (XId == RHSId) {
6522 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006523 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006524 } else {
6525 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6526 ErrorRange = AtomicInnerBinOp->getSourceRange();
6527 NoteLoc = X->getExprLoc();
6528 NoteRange = X->getSourceRange();
6529 ErrorFound = NotAnUpdateExpression;
6530 }
6531 } else {
6532 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6533 ErrorRange = AtomicInnerBinOp->getSourceRange();
6534 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6535 NoteRange = SourceRange(NoteLoc, NoteLoc);
6536 ErrorFound = NotABinaryOperator;
6537 }
6538 } else {
6539 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6540 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6541 ErrorFound = NotABinaryExpression;
6542 }
6543 } else {
6544 ErrorLoc = AtomicBinOp->getExprLoc();
6545 ErrorRange = AtomicBinOp->getSourceRange();
6546 NoteLoc = AtomicBinOp->getOperatorLoc();
6547 NoteRange = SourceRange(NoteLoc, NoteLoc);
6548 ErrorFound = NotAnAssignmentOp;
6549 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006550 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006551 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6552 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6553 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006554 }
6555 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006556 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006557 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006558}
6559
6560bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6561 unsigned NoteId) {
6562 ExprAnalysisErrorCode ErrorFound = NoError;
6563 SourceLocation ErrorLoc, NoteLoc;
6564 SourceRange ErrorRange, NoteRange;
6565 // Allowed constructs are:
6566 // x++;
6567 // x--;
6568 // ++x;
6569 // --x;
6570 // x binop= expr;
6571 // x = x binop expr;
6572 // x = expr binop x;
6573 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6574 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6575 if (AtomicBody->getType()->isScalarType() ||
6576 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006577 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006578 AtomicBody->IgnoreParenImpCasts())) {
6579 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006580 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006581 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006582 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006583 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006584 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006585 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006586 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6587 AtomicBody->IgnoreParenImpCasts())) {
6588 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006589 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006590 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006591 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006592 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006593 // Check for Unary Operation
6594 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006595 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006596 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6597 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006598 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006599 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6600 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006601 } else {
6602 ErrorFound = NotAnUnaryIncDecExpression;
6603 ErrorLoc = AtomicUnaryOp->getExprLoc();
6604 ErrorRange = AtomicUnaryOp->getSourceRange();
6605 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6606 NoteRange = SourceRange(NoteLoc, NoteLoc);
6607 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006608 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006609 ErrorFound = NotABinaryOrUnaryExpression;
6610 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6611 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6612 }
6613 } else {
6614 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006615 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006616 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6617 }
6618 } else {
6619 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006620 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006621 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6622 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006623 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006624 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6625 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6626 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006627 }
6628 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006629 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006630 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006631 // Build an update expression of form 'OpaqueValueExpr(x) binop
6632 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6633 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6634 auto *OVEX = new (SemaRef.getASTContext())
6635 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6636 auto *OVEExpr = new (SemaRef.getASTContext())
6637 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006638 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006639 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6640 IsXLHSInRHSPart ? OVEExpr : OVEX);
6641 if (Update.isInvalid())
6642 return true;
6643 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6644 Sema::AA_Casting);
6645 if (Update.isInvalid())
6646 return true;
6647 UpdateExpr = Update.get();
6648 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006649 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006650}
6651
Alexey Bataev0162e452014-07-22 10:10:35 +00006652StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6653 Stmt *AStmt,
6654 SourceLocation StartLoc,
6655 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006656 if (!AStmt)
6657 return StmtError();
6658
David Majnemer9d168222016-08-05 17:44:54 +00006659 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006660 // 1.2.2 OpenMP Language Terminology
6661 // Structured block - An executable statement with a single entry at the
6662 // top and a single exit at the bottom.
6663 // The point of exit cannot be a branch out of the structured block.
6664 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006665 OpenMPClauseKind AtomicKind = OMPC_unknown;
6666 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006667 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006668 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006669 C->getClauseKind() == OMPC_update ||
6670 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006671 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006672 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006673 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006674 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6675 << getOpenMPClauseName(AtomicKind);
6676 } else {
6677 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006678 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006679 }
6680 }
6681 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006682
Alexey Bataeve3727102018-04-18 15:57:46 +00006683 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006684 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6685 Body = EWC->getSubExpr();
6686
Alexey Bataev62cec442014-11-18 10:14:22 +00006687 Expr *X = nullptr;
6688 Expr *V = nullptr;
6689 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006690 Expr *UE = nullptr;
6691 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006692 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006693 // OpenMP [2.12.6, atomic Construct]
6694 // In the next expressions:
6695 // * x and v (as applicable) are both l-value expressions with scalar type.
6696 // * During the execution of an atomic region, multiple syntactic
6697 // occurrences of x must designate the same storage location.
6698 // * Neither of v and expr (as applicable) may access the storage location
6699 // designated by x.
6700 // * Neither of x and expr (as applicable) may access the storage location
6701 // designated by v.
6702 // * expr is an expression with scalar type.
6703 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6704 // * binop, binop=, ++, and -- are not overloaded operators.
6705 // * The expression x binop expr must be numerically equivalent to x binop
6706 // (expr). This requirement is satisfied if the operators in expr have
6707 // precedence greater than binop, or by using parentheses around expr or
6708 // subexpressions of expr.
6709 // * The expression expr binop x must be numerically equivalent to (expr)
6710 // binop x. This requirement is satisfied if the operators in expr have
6711 // precedence equal to or greater than binop, or by using parentheses around
6712 // expr or subexpressions of expr.
6713 // * For forms that allow multiple occurrences of x, the number of times
6714 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006715 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006716 enum {
6717 NotAnExpression,
6718 NotAnAssignmentOp,
6719 NotAScalarType,
6720 NotAnLValue,
6721 NoError
6722 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006723 SourceLocation ErrorLoc, NoteLoc;
6724 SourceRange ErrorRange, NoteRange;
6725 // If clause is read:
6726 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006727 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6728 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006729 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6730 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6731 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6732 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6733 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6734 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6735 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006736 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006737 ErrorFound = NotAnLValue;
6738 ErrorLoc = AtomicBinOp->getExprLoc();
6739 ErrorRange = AtomicBinOp->getSourceRange();
6740 NoteLoc = NotLValueExpr->getExprLoc();
6741 NoteRange = NotLValueExpr->getSourceRange();
6742 }
6743 } else if (!X->isInstantiationDependent() ||
6744 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006745 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006746 (X->isInstantiationDependent() || X->getType()->isScalarType())
6747 ? V
6748 : X;
6749 ErrorFound = NotAScalarType;
6750 ErrorLoc = AtomicBinOp->getExprLoc();
6751 ErrorRange = AtomicBinOp->getSourceRange();
6752 NoteLoc = NotScalarExpr->getExprLoc();
6753 NoteRange = NotScalarExpr->getSourceRange();
6754 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006755 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006756 ErrorFound = NotAnAssignmentOp;
6757 ErrorLoc = AtomicBody->getExprLoc();
6758 ErrorRange = AtomicBody->getSourceRange();
6759 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6760 : AtomicBody->getExprLoc();
6761 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6762 : AtomicBody->getSourceRange();
6763 }
6764 } else {
6765 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006766 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006767 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006768 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006769 if (ErrorFound != NoError) {
6770 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6771 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006772 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6773 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006774 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006775 }
6776 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00006777 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006778 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006779 enum {
6780 NotAnExpression,
6781 NotAnAssignmentOp,
6782 NotAScalarType,
6783 NotAnLValue,
6784 NoError
6785 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006786 SourceLocation ErrorLoc, NoteLoc;
6787 SourceRange ErrorRange, NoteRange;
6788 // If clause is write:
6789 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00006790 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6791 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006792 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6793 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006794 X = AtomicBinOp->getLHS();
6795 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006796 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6797 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6798 if (!X->isLValue()) {
6799 ErrorFound = NotAnLValue;
6800 ErrorLoc = AtomicBinOp->getExprLoc();
6801 ErrorRange = AtomicBinOp->getSourceRange();
6802 NoteLoc = X->getExprLoc();
6803 NoteRange = X->getSourceRange();
6804 }
6805 } else if (!X->isInstantiationDependent() ||
6806 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006807 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006808 (X->isInstantiationDependent() || X->getType()->isScalarType())
6809 ? E
6810 : X;
6811 ErrorFound = NotAScalarType;
6812 ErrorLoc = AtomicBinOp->getExprLoc();
6813 ErrorRange = AtomicBinOp->getSourceRange();
6814 NoteLoc = NotScalarExpr->getExprLoc();
6815 NoteRange = NotScalarExpr->getSourceRange();
6816 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006817 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006818 ErrorFound = NotAnAssignmentOp;
6819 ErrorLoc = AtomicBody->getExprLoc();
6820 ErrorRange = AtomicBody->getSourceRange();
6821 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6822 : AtomicBody->getExprLoc();
6823 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6824 : AtomicBody->getSourceRange();
6825 }
6826 } else {
6827 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006828 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006829 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006830 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006831 if (ErrorFound != NoError) {
6832 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6833 << ErrorRange;
6834 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6835 << NoteRange;
6836 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006837 }
6838 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00006839 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006840 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006841 // If clause is update:
6842 // x++;
6843 // x--;
6844 // ++x;
6845 // --x;
6846 // x binop= expr;
6847 // x = x binop expr;
6848 // x = expr binop x;
6849 OpenMPAtomicUpdateChecker Checker(*this);
6850 if (Checker.checkStatement(
6851 Body, (AtomicKind == OMPC_update)
6852 ? diag::err_omp_atomic_update_not_expression_statement
6853 : diag::err_omp_atomic_not_expression_statement,
6854 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006855 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006856 if (!CurContext->isDependentContext()) {
6857 E = Checker.getExpr();
6858 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006859 UE = Checker.getUpdateExpr();
6860 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006861 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006862 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006863 enum {
6864 NotAnAssignmentOp,
6865 NotACompoundStatement,
6866 NotTwoSubstatements,
6867 NotASpecificExpression,
6868 NoError
6869 } ErrorFound = NoError;
6870 SourceLocation ErrorLoc, NoteLoc;
6871 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00006872 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006873 // If clause is a capture:
6874 // v = x++;
6875 // v = x--;
6876 // v = ++x;
6877 // v = --x;
6878 // v = x binop= expr;
6879 // v = x = x binop expr;
6880 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006881 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00006882 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6883 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6884 V = AtomicBinOp->getLHS();
6885 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6886 OpenMPAtomicUpdateChecker Checker(*this);
6887 if (Checker.checkStatement(
6888 Body, diag::err_omp_atomic_capture_not_expression_statement,
6889 diag::note_omp_atomic_update))
6890 return StmtError();
6891 E = Checker.getExpr();
6892 X = Checker.getX();
6893 UE = Checker.getUpdateExpr();
6894 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6895 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006896 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006897 ErrorLoc = AtomicBody->getExprLoc();
6898 ErrorRange = AtomicBody->getSourceRange();
6899 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6900 : AtomicBody->getExprLoc();
6901 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6902 : AtomicBody->getSourceRange();
6903 ErrorFound = NotAnAssignmentOp;
6904 }
6905 if (ErrorFound != NoError) {
6906 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6907 << ErrorRange;
6908 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6909 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006910 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006911 if (CurContext->isDependentContext())
6912 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006913 } else {
6914 // If clause is a capture:
6915 // { v = x; x = expr; }
6916 // { v = x; x++; }
6917 // { v = x; x--; }
6918 // { v = x; ++x; }
6919 // { v = x; --x; }
6920 // { v = x; x binop= expr; }
6921 // { v = x; x = x binop expr; }
6922 // { v = x; x = expr binop x; }
6923 // { x++; v = x; }
6924 // { x--; v = x; }
6925 // { ++x; v = x; }
6926 // { --x; v = x; }
6927 // { x binop= expr; v = x; }
6928 // { x = x binop expr; v = x; }
6929 // { x = expr binop x; v = x; }
6930 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6931 // Check that this is { expr1; expr2; }
6932 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006933 Stmt *First = CS->body_front();
6934 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006935 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6936 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6937 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6938 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6939 // Need to find what subexpression is 'v' and what is 'x'.
6940 OpenMPAtomicUpdateChecker Checker(*this);
6941 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6942 BinaryOperator *BinOp = nullptr;
6943 if (IsUpdateExprFound) {
6944 BinOp = dyn_cast<BinaryOperator>(First);
6945 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6946 }
6947 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6948 // { v = x; x++; }
6949 // { v = x; x--; }
6950 // { v = x; ++x; }
6951 // { v = x; --x; }
6952 // { v = x; x binop= expr; }
6953 // { v = x; x = x binop expr; }
6954 // { v = x; x = expr binop x; }
6955 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006956 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006957 llvm::FoldingSetNodeID XId, PossibleXId;
6958 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6959 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6960 IsUpdateExprFound = XId == PossibleXId;
6961 if (IsUpdateExprFound) {
6962 V = BinOp->getLHS();
6963 X = Checker.getX();
6964 E = Checker.getExpr();
6965 UE = Checker.getUpdateExpr();
6966 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006967 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006968 }
6969 }
6970 if (!IsUpdateExprFound) {
6971 IsUpdateExprFound = !Checker.checkStatement(First);
6972 BinOp = nullptr;
6973 if (IsUpdateExprFound) {
6974 BinOp = dyn_cast<BinaryOperator>(Second);
6975 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6976 }
6977 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6978 // { x++; v = x; }
6979 // { x--; v = x; }
6980 // { ++x; v = x; }
6981 // { --x; v = x; }
6982 // { x binop= expr; v = x; }
6983 // { x = x binop expr; v = x; }
6984 // { x = expr binop x; v = x; }
6985 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006986 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006987 llvm::FoldingSetNodeID XId, PossibleXId;
6988 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6989 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6990 IsUpdateExprFound = XId == PossibleXId;
6991 if (IsUpdateExprFound) {
6992 V = BinOp->getLHS();
6993 X = Checker.getX();
6994 E = Checker.getExpr();
6995 UE = Checker.getUpdateExpr();
6996 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006997 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006998 }
6999 }
7000 }
7001 if (!IsUpdateExprFound) {
7002 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007003 auto *FirstExpr = dyn_cast<Expr>(First);
7004 auto *SecondExpr = dyn_cast<Expr>(Second);
7005 if (!FirstExpr || !SecondExpr ||
7006 !(FirstExpr->isInstantiationDependent() ||
7007 SecondExpr->isInstantiationDependent())) {
7008 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7009 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007010 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007011 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007012 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007013 NoteRange = ErrorRange = FirstBinOp
7014 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007015 : SourceRange(ErrorLoc, ErrorLoc);
7016 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007017 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7018 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7019 ErrorFound = NotAnAssignmentOp;
7020 NoteLoc = ErrorLoc = SecondBinOp
7021 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007022 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007023 NoteRange = ErrorRange =
7024 SecondBinOp ? SecondBinOp->getSourceRange()
7025 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007026 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007027 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007028 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007029 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007030 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7031 llvm::FoldingSetNodeID X1Id, X2Id;
7032 PossibleXRHSInFirst->Profile(X1Id, Context,
7033 /*Canonical=*/true);
7034 PossibleXLHSInSecond->Profile(X2Id, Context,
7035 /*Canonical=*/true);
7036 IsUpdateExprFound = X1Id == X2Id;
7037 if (IsUpdateExprFound) {
7038 V = FirstBinOp->getLHS();
7039 X = SecondBinOp->getLHS();
7040 E = SecondBinOp->getRHS();
7041 UE = nullptr;
7042 IsXLHSInRHSPart = false;
7043 IsPostfixUpdate = true;
7044 } else {
7045 ErrorFound = NotASpecificExpression;
7046 ErrorLoc = FirstBinOp->getExprLoc();
7047 ErrorRange = FirstBinOp->getSourceRange();
7048 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7049 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7050 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007051 }
7052 }
7053 }
7054 }
7055 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007056 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007057 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007058 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007059 ErrorFound = NotTwoSubstatements;
7060 }
7061 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007062 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007063 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007064 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007065 ErrorFound = NotACompoundStatement;
7066 }
7067 if (ErrorFound != NoError) {
7068 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7069 << ErrorRange;
7070 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7071 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007072 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007073 if (CurContext->isDependentContext())
7074 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007075 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007076 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007077
Reid Kleckner87a31802018-03-12 21:43:02 +00007078 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007079
Alexey Bataev62cec442014-11-18 10:14:22 +00007080 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007081 X, V, E, UE, IsXLHSInRHSPart,
7082 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007083}
7084
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007085StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7086 Stmt *AStmt,
7087 SourceLocation StartLoc,
7088 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007089 if (!AStmt)
7090 return StmtError();
7091
Alexey Bataeve3727102018-04-18 15:57:46 +00007092 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007093 // 1.2.2 OpenMP Language Terminology
7094 // Structured block - An executable statement with a single entry at the
7095 // top and a single exit at the bottom.
7096 // The point of exit cannot be a branch out of the structured block.
7097 // longjmp() and throw() must not violate the entry/exit criteria.
7098 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007099 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7100 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7101 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7102 // 1.2.2 OpenMP Language Terminology
7103 // Structured block - An executable statement with a single entry at the
7104 // top and a single exit at the bottom.
7105 // The point of exit cannot be a branch out of the structured block.
7106 // longjmp() and throw() must not violate the entry/exit criteria.
7107 CS->getCapturedDecl()->setNothrow();
7108 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007109
Alexey Bataev13314bf2014-10-09 04:18:56 +00007110 // OpenMP [2.16, Nesting of Regions]
7111 // If specified, a teams construct must be contained within a target
7112 // construct. That target construct must contain no statements or directives
7113 // outside of the teams construct.
7114 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007115 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007116 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007117 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007118 auto I = CS->body_begin();
7119 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007120 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007121 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7122 OMPTeamsFound) {
7123
Alexey Bataev13314bf2014-10-09 04:18:56 +00007124 OMPTeamsFound = false;
7125 break;
7126 }
7127 ++I;
7128 }
7129 assert(I != CS->body_end() && "Not found statement");
7130 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007131 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007132 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007133 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007134 }
7135 if (!OMPTeamsFound) {
7136 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7137 Diag(DSAStack->getInnerTeamsRegionLoc(),
7138 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007139 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007140 << isa<OMPExecutableDirective>(S);
7141 return StmtError();
7142 }
7143 }
7144
Reid Kleckner87a31802018-03-12 21:43:02 +00007145 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007146
7147 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7148}
7149
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007150StmtResult
7151Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7152 Stmt *AStmt, SourceLocation StartLoc,
7153 SourceLocation EndLoc) {
7154 if (!AStmt)
7155 return StmtError();
7156
Alexey Bataeve3727102018-04-18 15:57:46 +00007157 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007158 // 1.2.2 OpenMP Language Terminology
7159 // Structured block - An executable statement with a single entry at the
7160 // top and a single exit at the bottom.
7161 // The point of exit cannot be a branch out of the structured block.
7162 // longjmp() and throw() must not violate the entry/exit criteria.
7163 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007164 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7165 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7166 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7167 // 1.2.2 OpenMP Language Terminology
7168 // Structured block - An executable statement with a single entry at the
7169 // top and a single exit at the bottom.
7170 // The point of exit cannot be a branch out of the structured block.
7171 // longjmp() and throw() must not violate the entry/exit criteria.
7172 CS->getCapturedDecl()->setNothrow();
7173 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007174
Reid Kleckner87a31802018-03-12 21:43:02 +00007175 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007176
7177 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7178 AStmt);
7179}
7180
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007181StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7182 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007183 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007184 if (!AStmt)
7185 return StmtError();
7186
Alexey Bataeve3727102018-04-18 15:57:46 +00007187 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007188 // 1.2.2 OpenMP Language Terminology
7189 // Structured block - An executable statement with a single entry at the
7190 // top and a single exit at the bottom.
7191 // The point of exit cannot be a branch out of the structured block.
7192 // longjmp() and throw() must not violate the entry/exit criteria.
7193 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007194 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7195 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7196 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7197 // 1.2.2 OpenMP Language Terminology
7198 // Structured block - An executable statement with a single entry at the
7199 // top and a single exit at the bottom.
7200 // The point of exit cannot be a branch out of the structured block.
7201 // longjmp() and throw() must not violate the entry/exit criteria.
7202 CS->getCapturedDecl()->setNothrow();
7203 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007204
7205 OMPLoopDirective::HelperExprs B;
7206 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7207 // define the nested loops number.
7208 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007209 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007210 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007211 VarsWithImplicitDSA, B);
7212 if (NestedLoopCount == 0)
7213 return StmtError();
7214
7215 assert((CurContext->isDependentContext() || B.builtAll()) &&
7216 "omp target parallel for loop exprs were not built");
7217
7218 if (!CurContext->isDependentContext()) {
7219 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007220 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007221 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007222 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007223 B.NumIterations, *this, CurScope,
7224 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007225 return StmtError();
7226 }
7227 }
7228
Reid Kleckner87a31802018-03-12 21:43:02 +00007229 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007230 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7231 NestedLoopCount, Clauses, AStmt,
7232 B, DSAStack->isCancelRegion());
7233}
7234
Alexey Bataev95b64a92017-05-30 16:00:04 +00007235/// Check for existence of a map clause in the list of clauses.
7236static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7237 const OpenMPClauseKind K) {
7238 return llvm::any_of(
7239 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7240}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007241
Alexey Bataev95b64a92017-05-30 16:00:04 +00007242template <typename... Params>
7243static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7244 const Params... ClauseTypes) {
7245 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007246}
7247
Michael Wong65f367f2015-07-21 13:44:28 +00007248StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7249 Stmt *AStmt,
7250 SourceLocation StartLoc,
7251 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007252 if (!AStmt)
7253 return StmtError();
7254
7255 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7256
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007257 // OpenMP [2.10.1, Restrictions, p. 97]
7258 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007259 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7260 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7261 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007262 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007263 return StmtError();
7264 }
7265
Reid Kleckner87a31802018-03-12 21:43:02 +00007266 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007267
7268 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7269 AStmt);
7270}
7271
Samuel Antaodf67fc42016-01-19 19:15:56 +00007272StmtResult
7273Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7274 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007275 SourceLocation EndLoc, Stmt *AStmt) {
7276 if (!AStmt)
7277 return StmtError();
7278
Alexey Bataeve3727102018-04-18 15:57:46 +00007279 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007280 // 1.2.2 OpenMP Language Terminology
7281 // Structured block - An executable statement with a single entry at the
7282 // top and a single exit at the bottom.
7283 // The point of exit cannot be a branch out of the structured block.
7284 // longjmp() and throw() must not violate the entry/exit criteria.
7285 CS->getCapturedDecl()->setNothrow();
7286 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7287 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7288 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7289 // 1.2.2 OpenMP Language Terminology
7290 // Structured block - An executable statement with a single entry at the
7291 // top and a single exit at the bottom.
7292 // The point of exit cannot be a branch out of the structured block.
7293 // longjmp() and throw() must not violate the entry/exit criteria.
7294 CS->getCapturedDecl()->setNothrow();
7295 }
7296
Samuel Antaodf67fc42016-01-19 19:15:56 +00007297 // OpenMP [2.10.2, Restrictions, p. 99]
7298 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007299 if (!hasClauses(Clauses, OMPC_map)) {
7300 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7301 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007302 return StmtError();
7303 }
7304
Alexey Bataev7828b252017-11-21 17:08:48 +00007305 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7306 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007307}
7308
Samuel Antao72590762016-01-19 20:04:50 +00007309StmtResult
7310Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7311 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007312 SourceLocation EndLoc, Stmt *AStmt) {
7313 if (!AStmt)
7314 return StmtError();
7315
Alexey Bataeve3727102018-04-18 15:57:46 +00007316 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007317 // 1.2.2 OpenMP Language Terminology
7318 // Structured block - An executable statement with a single entry at the
7319 // top and a single exit at the bottom.
7320 // The point of exit cannot be a branch out of the structured block.
7321 // longjmp() and throw() must not violate the entry/exit criteria.
7322 CS->getCapturedDecl()->setNothrow();
7323 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7324 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7325 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7326 // 1.2.2 OpenMP Language Terminology
7327 // Structured block - An executable statement with a single entry at the
7328 // top and a single exit at the bottom.
7329 // The point of exit cannot be a branch out of the structured block.
7330 // longjmp() and throw() must not violate the entry/exit criteria.
7331 CS->getCapturedDecl()->setNothrow();
7332 }
7333
Samuel Antao72590762016-01-19 20:04:50 +00007334 // OpenMP [2.10.3, Restrictions, p. 102]
7335 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007336 if (!hasClauses(Clauses, OMPC_map)) {
7337 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7338 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007339 return StmtError();
7340 }
7341
Alexey Bataev7828b252017-11-21 17:08:48 +00007342 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7343 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007344}
7345
Samuel Antao686c70c2016-05-26 17:30:50 +00007346StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7347 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007348 SourceLocation EndLoc,
7349 Stmt *AStmt) {
7350 if (!AStmt)
7351 return StmtError();
7352
Alexey Bataeve3727102018-04-18 15:57:46 +00007353 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007354 // 1.2.2 OpenMP Language Terminology
7355 // Structured block - An executable statement with a single entry at the
7356 // top and a single exit at the bottom.
7357 // The point of exit cannot be a branch out of the structured block.
7358 // longjmp() and throw() must not violate the entry/exit criteria.
7359 CS->getCapturedDecl()->setNothrow();
7360 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7361 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7362 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7363 // 1.2.2 OpenMP Language Terminology
7364 // Structured block - An executable statement with a single entry at the
7365 // top and a single exit at the bottom.
7366 // The point of exit cannot be a branch out of the structured block.
7367 // longjmp() and throw() must not violate the entry/exit criteria.
7368 CS->getCapturedDecl()->setNothrow();
7369 }
7370
Alexey Bataev95b64a92017-05-30 16:00:04 +00007371 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007372 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7373 return StmtError();
7374 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007375 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7376 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007377}
7378
Alexey Bataev13314bf2014-10-09 04:18:56 +00007379StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7380 Stmt *AStmt, SourceLocation StartLoc,
7381 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007382 if (!AStmt)
7383 return StmtError();
7384
Alexey Bataeve3727102018-04-18 15:57:46 +00007385 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007386 // 1.2.2 OpenMP Language Terminology
7387 // Structured block - An executable statement with a single entry at the
7388 // top and a single exit at the bottom.
7389 // The point of exit cannot be a branch out of the structured block.
7390 // longjmp() and throw() must not violate the entry/exit criteria.
7391 CS->getCapturedDecl()->setNothrow();
7392
Reid Kleckner87a31802018-03-12 21:43:02 +00007393 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007394
Alexey Bataevceabd412017-11-30 18:01:54 +00007395 DSAStack->setParentTeamsRegionLoc(StartLoc);
7396
Alexey Bataev13314bf2014-10-09 04:18:56 +00007397 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7398}
7399
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007400StmtResult
7401Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7402 SourceLocation EndLoc,
7403 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007404 if (DSAStack->isParentNowaitRegion()) {
7405 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7406 return StmtError();
7407 }
7408 if (DSAStack->isParentOrderedRegion()) {
7409 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7410 return StmtError();
7411 }
7412 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7413 CancelRegion);
7414}
7415
Alexey Bataev87933c72015-09-18 08:07:34 +00007416StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7417 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007418 SourceLocation EndLoc,
7419 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007420 if (DSAStack->isParentNowaitRegion()) {
7421 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7422 return StmtError();
7423 }
7424 if (DSAStack->isParentOrderedRegion()) {
7425 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7426 return StmtError();
7427 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007428 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007429 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7430 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007431}
7432
Alexey Bataev382967a2015-12-08 12:06:20 +00007433static bool checkGrainsizeNumTasksClauses(Sema &S,
7434 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007435 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007436 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007437 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007438 if (C->getClauseKind() == OMPC_grainsize ||
7439 C->getClauseKind() == OMPC_num_tasks) {
7440 if (!PrevClause)
7441 PrevClause = C;
7442 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007443 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007444 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7445 << getOpenMPClauseName(C->getClauseKind())
7446 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007447 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007448 diag::note_omp_previous_grainsize_num_tasks)
7449 << getOpenMPClauseName(PrevClause->getClauseKind());
7450 ErrorFound = true;
7451 }
7452 }
7453 }
7454 return ErrorFound;
7455}
7456
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007457static bool checkReductionClauseWithNogroup(Sema &S,
7458 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007459 const OMPClause *ReductionClause = nullptr;
7460 const OMPClause *NogroupClause = nullptr;
7461 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007462 if (C->getClauseKind() == OMPC_reduction) {
7463 ReductionClause = C;
7464 if (NogroupClause)
7465 break;
7466 continue;
7467 }
7468 if (C->getClauseKind() == OMPC_nogroup) {
7469 NogroupClause = C;
7470 if (ReductionClause)
7471 break;
7472 continue;
7473 }
7474 }
7475 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007476 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7477 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007478 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007479 return true;
7480 }
7481 return false;
7482}
7483
Alexey Bataev49f6e782015-12-01 04:18:41 +00007484StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007486 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007487 if (!AStmt)
7488 return StmtError();
7489
7490 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7491 OMPLoopDirective::HelperExprs B;
7492 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7493 // define the nested loops number.
7494 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007495 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007496 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007497 VarsWithImplicitDSA, B);
7498 if (NestedLoopCount == 0)
7499 return StmtError();
7500
7501 assert((CurContext->isDependentContext() || B.builtAll()) &&
7502 "omp for loop exprs were not built");
7503
Alexey Bataev382967a2015-12-08 12:06:20 +00007504 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7505 // The grainsize clause and num_tasks clause are mutually exclusive and may
7506 // not appear on the same taskloop directive.
7507 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7508 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007509 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7510 // If a reduction clause is present on the taskloop directive, the nogroup
7511 // clause must not be specified.
7512 if (checkReductionClauseWithNogroup(*this, Clauses))
7513 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007514
Reid Kleckner87a31802018-03-12 21:43:02 +00007515 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007516 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7517 NestedLoopCount, Clauses, AStmt, B);
7518}
7519
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007520StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007522 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007523 if (!AStmt)
7524 return StmtError();
7525
7526 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7527 OMPLoopDirective::HelperExprs B;
7528 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7529 // define the nested loops number.
7530 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007531 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007532 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7533 VarsWithImplicitDSA, B);
7534 if (NestedLoopCount == 0)
7535 return StmtError();
7536
7537 assert((CurContext->isDependentContext() || B.builtAll()) &&
7538 "omp for loop exprs were not built");
7539
Alexey Bataev5a3af132016-03-29 08:58:54 +00007540 if (!CurContext->isDependentContext()) {
7541 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007542 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007543 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007544 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007545 B.NumIterations, *this, CurScope,
7546 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007547 return StmtError();
7548 }
7549 }
7550
Alexey Bataev382967a2015-12-08 12:06:20 +00007551 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7552 // The grainsize clause and num_tasks clause are mutually exclusive and may
7553 // not appear on the same taskloop directive.
7554 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7555 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007556 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7557 // If a reduction clause is present on the taskloop directive, the nogroup
7558 // clause must not be specified.
7559 if (checkReductionClauseWithNogroup(*this, Clauses))
7560 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007561 if (checkSimdlenSafelenSpecified(*this, Clauses))
7562 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007563
Reid Kleckner87a31802018-03-12 21:43:02 +00007564 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007565 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7566 NestedLoopCount, Clauses, AStmt, B);
7567}
7568
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007569StmtResult Sema::ActOnOpenMPDistributeDirective(
7570 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007571 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007572 if (!AStmt)
7573 return StmtError();
7574
7575 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7576 OMPLoopDirective::HelperExprs B;
7577 // In presence of clause 'collapse' with number of loops, it will
7578 // define the nested loops number.
7579 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007580 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007581 nullptr /*ordered not a clause on distribute*/, AStmt,
7582 *this, *DSAStack, VarsWithImplicitDSA, B);
7583 if (NestedLoopCount == 0)
7584 return StmtError();
7585
7586 assert((CurContext->isDependentContext() || B.builtAll()) &&
7587 "omp for loop exprs were not built");
7588
Reid Kleckner87a31802018-03-12 21:43:02 +00007589 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007590 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7591 NestedLoopCount, Clauses, AStmt, B);
7592}
7593
Carlo Bertolli9925f152016-06-27 14:55:37 +00007594StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7595 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007596 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007597 if (!AStmt)
7598 return StmtError();
7599
Alexey Bataeve3727102018-04-18 15:57:46 +00007600 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007601 // 1.2.2 OpenMP Language Terminology
7602 // Structured block - An executable statement with a single entry at the
7603 // top and a single exit at the bottom.
7604 // The point of exit cannot be a branch out of the structured block.
7605 // longjmp() and throw() must not violate the entry/exit criteria.
7606 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007607 for (int ThisCaptureLevel =
7608 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7609 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7610 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7611 // 1.2.2 OpenMP Language Terminology
7612 // Structured block - An executable statement with a single entry at the
7613 // top and a single exit at the bottom.
7614 // The point of exit cannot be a branch out of the structured block.
7615 // longjmp() and throw() must not violate the entry/exit criteria.
7616 CS->getCapturedDecl()->setNothrow();
7617 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007618
7619 OMPLoopDirective::HelperExprs B;
7620 // In presence of clause 'collapse' with number of loops, it will
7621 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007622 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007623 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007624 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007625 VarsWithImplicitDSA, B);
7626 if (NestedLoopCount == 0)
7627 return StmtError();
7628
7629 assert((CurContext->isDependentContext() || B.builtAll()) &&
7630 "omp for loop exprs were not built");
7631
Reid Kleckner87a31802018-03-12 21:43:02 +00007632 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007633 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7635 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007636}
7637
Kelvin Li4a39add2016-07-05 05:00:15 +00007638StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007640 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007641 if (!AStmt)
7642 return StmtError();
7643
Alexey Bataeve3727102018-04-18 15:57:46 +00007644 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007645 // 1.2.2 OpenMP Language Terminology
7646 // Structured block - An executable statement with a single entry at the
7647 // top and a single exit at the bottom.
7648 // The point of exit cannot be a branch out of the structured block.
7649 // longjmp() and throw() must not violate the entry/exit criteria.
7650 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007651 for (int ThisCaptureLevel =
7652 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7653 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7654 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7655 // 1.2.2 OpenMP Language Terminology
7656 // Structured block - An executable statement with a single entry at the
7657 // top and a single exit at the bottom.
7658 // The point of exit cannot be a branch out of the structured block.
7659 // longjmp() and throw() must not violate the entry/exit criteria.
7660 CS->getCapturedDecl()->setNothrow();
7661 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007662
7663 OMPLoopDirective::HelperExprs B;
7664 // In presence of clause 'collapse' with number of loops, it will
7665 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007666 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007667 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007668 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007669 VarsWithImplicitDSA, B);
7670 if (NestedLoopCount == 0)
7671 return StmtError();
7672
7673 assert((CurContext->isDependentContext() || B.builtAll()) &&
7674 "omp for loop exprs were not built");
7675
Alexey Bataev438388c2017-11-22 18:34:02 +00007676 if (!CurContext->isDependentContext()) {
7677 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007678 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007679 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7680 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7681 B.NumIterations, *this, CurScope,
7682 DSAStack))
7683 return StmtError();
7684 }
7685 }
7686
Kelvin Lic5609492016-07-15 04:39:07 +00007687 if (checkSimdlenSafelenSpecified(*this, Clauses))
7688 return StmtError();
7689
Reid Kleckner87a31802018-03-12 21:43:02 +00007690 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007691 return OMPDistributeParallelForSimdDirective::Create(
7692 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7693}
7694
Kelvin Li787f3fc2016-07-06 04:45:38 +00007695StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007697 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007698 if (!AStmt)
7699 return StmtError();
7700
Alexey Bataeve3727102018-04-18 15:57:46 +00007701 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007702 // 1.2.2 OpenMP Language Terminology
7703 // Structured block - An executable statement with a single entry at the
7704 // top and a single exit at the bottom.
7705 // The point of exit cannot be a branch out of the structured block.
7706 // longjmp() and throw() must not violate the entry/exit criteria.
7707 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007708 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7709 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7710 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7711 // 1.2.2 OpenMP Language Terminology
7712 // Structured block - An executable statement with a single entry at the
7713 // top and a single exit at the bottom.
7714 // The point of exit cannot be a branch out of the structured block.
7715 // longjmp() and throw() must not violate the entry/exit criteria.
7716 CS->getCapturedDecl()->setNothrow();
7717 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007718
7719 OMPLoopDirective::HelperExprs B;
7720 // In presence of clause 'collapse' with number of loops, it will
7721 // define the nested loops number.
7722 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007723 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007724 nullptr /*ordered not a clause on distribute*/, CS, *this,
7725 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007726 if (NestedLoopCount == 0)
7727 return StmtError();
7728
7729 assert((CurContext->isDependentContext() || B.builtAll()) &&
7730 "omp for loop exprs were not built");
7731
Alexey Bataev438388c2017-11-22 18:34:02 +00007732 if (!CurContext->isDependentContext()) {
7733 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007734 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007735 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7736 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7737 B.NumIterations, *this, CurScope,
7738 DSAStack))
7739 return StmtError();
7740 }
7741 }
7742
Kelvin Lic5609492016-07-15 04:39:07 +00007743 if (checkSimdlenSafelenSpecified(*this, Clauses))
7744 return StmtError();
7745
Reid Kleckner87a31802018-03-12 21:43:02 +00007746 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007747 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7748 NestedLoopCount, Clauses, AStmt, B);
7749}
7750
Kelvin Lia579b912016-07-14 02:54:56 +00007751StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7752 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007753 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007754 if (!AStmt)
7755 return StmtError();
7756
Alexey Bataeve3727102018-04-18 15:57:46 +00007757 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007758 // 1.2.2 OpenMP Language Terminology
7759 // Structured block - An executable statement with a single entry at the
7760 // top and a single exit at the bottom.
7761 // The point of exit cannot be a branch out of the structured block.
7762 // longjmp() and throw() must not violate the entry/exit criteria.
7763 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007764 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7765 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7766 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7767 // 1.2.2 OpenMP Language Terminology
7768 // Structured block - An executable statement with a single entry at the
7769 // top and a single exit at the bottom.
7770 // The point of exit cannot be a branch out of the structured block.
7771 // longjmp() and throw() must not violate the entry/exit criteria.
7772 CS->getCapturedDecl()->setNothrow();
7773 }
Kelvin Lia579b912016-07-14 02:54:56 +00007774
7775 OMPLoopDirective::HelperExprs B;
7776 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7777 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007778 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00007779 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007780 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007781 VarsWithImplicitDSA, B);
7782 if (NestedLoopCount == 0)
7783 return StmtError();
7784
7785 assert((CurContext->isDependentContext() || B.builtAll()) &&
7786 "omp target parallel for simd loop exprs were not built");
7787
7788 if (!CurContext->isDependentContext()) {
7789 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007790 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007791 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007792 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7793 B.NumIterations, *this, CurScope,
7794 DSAStack))
7795 return StmtError();
7796 }
7797 }
Kelvin Lic5609492016-07-15 04:39:07 +00007798 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007799 return StmtError();
7800
Reid Kleckner87a31802018-03-12 21:43:02 +00007801 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007802 return OMPTargetParallelForSimdDirective::Create(
7803 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7804}
7805
Kelvin Li986330c2016-07-20 22:57:10 +00007806StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007808 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00007809 if (!AStmt)
7810 return StmtError();
7811
Alexey Bataeve3727102018-04-18 15:57:46 +00007812 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00007813 // 1.2.2 OpenMP Language Terminology
7814 // Structured block - An executable statement with a single entry at the
7815 // top and a single exit at the bottom.
7816 // The point of exit cannot be a branch out of the structured block.
7817 // longjmp() and throw() must not violate the entry/exit criteria.
7818 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007819 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7820 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7821 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7822 // 1.2.2 OpenMP Language Terminology
7823 // Structured block - An executable statement with a single entry at the
7824 // top and a single exit at the bottom.
7825 // The point of exit cannot be a branch out of the structured block.
7826 // longjmp() and throw() must not violate the entry/exit criteria.
7827 CS->getCapturedDecl()->setNothrow();
7828 }
7829
Kelvin Li986330c2016-07-20 22:57:10 +00007830 OMPLoopDirective::HelperExprs B;
7831 // In presence of clause 'collapse' with number of loops, it will define the
7832 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007833 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007834 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007835 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007836 VarsWithImplicitDSA, B);
7837 if (NestedLoopCount == 0)
7838 return StmtError();
7839
7840 assert((CurContext->isDependentContext() || B.builtAll()) &&
7841 "omp target simd loop exprs were not built");
7842
7843 if (!CurContext->isDependentContext()) {
7844 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007845 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007846 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007847 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7848 B.NumIterations, *this, CurScope,
7849 DSAStack))
7850 return StmtError();
7851 }
7852 }
7853
7854 if (checkSimdlenSafelenSpecified(*this, Clauses))
7855 return StmtError();
7856
Reid Kleckner87a31802018-03-12 21:43:02 +00007857 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007858 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7859 NestedLoopCount, Clauses, AStmt, B);
7860}
7861
Kelvin Li02532872016-08-05 14:37:37 +00007862StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7863 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007864 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00007865 if (!AStmt)
7866 return StmtError();
7867
Alexey Bataeve3727102018-04-18 15:57:46 +00007868 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00007869 // 1.2.2 OpenMP Language Terminology
7870 // Structured block - An executable statement with a single entry at the
7871 // top and a single exit at the bottom.
7872 // The point of exit cannot be a branch out of the structured block.
7873 // longjmp() and throw() must not violate the entry/exit criteria.
7874 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007875 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7876 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7877 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7878 // 1.2.2 OpenMP Language Terminology
7879 // Structured block - An executable statement with a single entry at the
7880 // top and a single exit at the bottom.
7881 // The point of exit cannot be a branch out of the structured block.
7882 // longjmp() and throw() must not violate the entry/exit criteria.
7883 CS->getCapturedDecl()->setNothrow();
7884 }
Kelvin Li02532872016-08-05 14:37:37 +00007885
7886 OMPLoopDirective::HelperExprs B;
7887 // In presence of clause 'collapse' with number of loops, it will
7888 // define the nested loops number.
7889 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007890 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007891 nullptr /*ordered not a clause on distribute*/, CS, *this,
7892 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007893 if (NestedLoopCount == 0)
7894 return StmtError();
7895
7896 assert((CurContext->isDependentContext() || B.builtAll()) &&
7897 "omp teams distribute loop exprs were not built");
7898
Reid Kleckner87a31802018-03-12 21:43:02 +00007899 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007900
7901 DSAStack->setParentTeamsRegionLoc(StartLoc);
7902
David Majnemer9d168222016-08-05 17:44:54 +00007903 return OMPTeamsDistributeDirective::Create(
7904 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007905}
7906
Kelvin Li4e325f72016-10-25 12:50:55 +00007907StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7908 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007909 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007910 if (!AStmt)
7911 return StmtError();
7912
Alexey Bataeve3727102018-04-18 15:57:46 +00007913 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00007914 // 1.2.2 OpenMP Language Terminology
7915 // Structured block - An executable statement with a single entry at the
7916 // top and a single exit at the bottom.
7917 // The point of exit cannot be a branch out of the structured block.
7918 // longjmp() and throw() must not violate the entry/exit criteria.
7919 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007920 for (int ThisCaptureLevel =
7921 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7922 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7923 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7924 // 1.2.2 OpenMP Language Terminology
7925 // Structured block - An executable statement with a single entry at the
7926 // top and a single exit at the bottom.
7927 // The point of exit cannot be a branch out of the structured block.
7928 // longjmp() and throw() must not violate the entry/exit criteria.
7929 CS->getCapturedDecl()->setNothrow();
7930 }
7931
Kelvin Li4e325f72016-10-25 12:50:55 +00007932
7933 OMPLoopDirective::HelperExprs B;
7934 // In presence of clause 'collapse' with number of loops, it will
7935 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007936 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00007937 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007938 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007939 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007940
7941 if (NestedLoopCount == 0)
7942 return StmtError();
7943
7944 assert((CurContext->isDependentContext() || B.builtAll()) &&
7945 "omp teams distribute simd loop exprs were not built");
7946
7947 if (!CurContext->isDependentContext()) {
7948 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007949 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007950 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7951 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7952 B.NumIterations, *this, CurScope,
7953 DSAStack))
7954 return StmtError();
7955 }
7956 }
7957
7958 if (checkSimdlenSafelenSpecified(*this, Clauses))
7959 return StmtError();
7960
Reid Kleckner87a31802018-03-12 21:43:02 +00007961 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007962
7963 DSAStack->setParentTeamsRegionLoc(StartLoc);
7964
Kelvin Li4e325f72016-10-25 12:50:55 +00007965 return OMPTeamsDistributeSimdDirective::Create(
7966 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7967}
7968
Kelvin Li579e41c2016-11-30 23:51:03 +00007969StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7970 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007971 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00007972 if (!AStmt)
7973 return StmtError();
7974
Alexey Bataeve3727102018-04-18 15:57:46 +00007975 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00007976 // 1.2.2 OpenMP Language Terminology
7977 // Structured block - An executable statement with a single entry at the
7978 // top and a single exit at the bottom.
7979 // The point of exit cannot be a branch out of the structured block.
7980 // longjmp() and throw() must not violate the entry/exit criteria.
7981 CS->getCapturedDecl()->setNothrow();
7982
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007983 for (int ThisCaptureLevel =
7984 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7985 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7986 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7987 // 1.2.2 OpenMP Language Terminology
7988 // Structured block - An executable statement with a single entry at the
7989 // top and a single exit at the bottom.
7990 // The point of exit cannot be a branch out of the structured block.
7991 // longjmp() and throw() must not violate the entry/exit criteria.
7992 CS->getCapturedDecl()->setNothrow();
7993 }
7994
Kelvin Li579e41c2016-11-30 23:51:03 +00007995 OMPLoopDirective::HelperExprs B;
7996 // In presence of clause 'collapse' with number of loops, it will
7997 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007998 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00007999 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008000 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008001 VarsWithImplicitDSA, B);
8002
8003 if (NestedLoopCount == 0)
8004 return StmtError();
8005
8006 assert((CurContext->isDependentContext() || B.builtAll()) &&
8007 "omp for loop exprs were not built");
8008
8009 if (!CurContext->isDependentContext()) {
8010 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008011 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008012 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8013 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8014 B.NumIterations, *this, CurScope,
8015 DSAStack))
8016 return StmtError();
8017 }
8018 }
8019
8020 if (checkSimdlenSafelenSpecified(*this, Clauses))
8021 return StmtError();
8022
Reid Kleckner87a31802018-03-12 21:43:02 +00008023 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008024
8025 DSAStack->setParentTeamsRegionLoc(StartLoc);
8026
Kelvin Li579e41c2016-11-30 23:51:03 +00008027 return OMPTeamsDistributeParallelForSimdDirective::Create(
8028 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8029}
8030
Kelvin Li7ade93f2016-12-09 03:24:30 +00008031StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8032 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008033 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008034 if (!AStmt)
8035 return StmtError();
8036
Alexey Bataeve3727102018-04-18 15:57:46 +00008037 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008038 // 1.2.2 OpenMP Language Terminology
8039 // Structured block - An executable statement with a single entry at the
8040 // top and a single exit at the bottom.
8041 // The point of exit cannot be a branch out of the structured block.
8042 // longjmp() and throw() must not violate the entry/exit criteria.
8043 CS->getCapturedDecl()->setNothrow();
8044
Carlo Bertolli62fae152017-11-20 20:46:39 +00008045 for (int ThisCaptureLevel =
8046 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8047 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8048 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8049 // 1.2.2 OpenMP Language Terminology
8050 // Structured block - An executable statement with a single entry at the
8051 // top and a single exit at the bottom.
8052 // The point of exit cannot be a branch out of the structured block.
8053 // longjmp() and throw() must not violate the entry/exit criteria.
8054 CS->getCapturedDecl()->setNothrow();
8055 }
8056
Kelvin Li7ade93f2016-12-09 03:24:30 +00008057 OMPLoopDirective::HelperExprs B;
8058 // In presence of clause 'collapse' with number of loops, it will
8059 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008060 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008061 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008062 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008063 VarsWithImplicitDSA, B);
8064
8065 if (NestedLoopCount == 0)
8066 return StmtError();
8067
8068 assert((CurContext->isDependentContext() || B.builtAll()) &&
8069 "omp for loop exprs were not built");
8070
Reid Kleckner87a31802018-03-12 21:43:02 +00008071 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008072
8073 DSAStack->setParentTeamsRegionLoc(StartLoc);
8074
Kelvin Li7ade93f2016-12-09 03:24:30 +00008075 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008076 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8077 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008078}
8079
Kelvin Libf594a52016-12-17 05:48:59 +00008080StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8081 Stmt *AStmt,
8082 SourceLocation StartLoc,
8083 SourceLocation EndLoc) {
8084 if (!AStmt)
8085 return StmtError();
8086
Alexey Bataeve3727102018-04-18 15:57:46 +00008087 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008088 // 1.2.2 OpenMP Language Terminology
8089 // Structured block - An executable statement with a single entry at the
8090 // top and a single exit at the bottom.
8091 // The point of exit cannot be a branch out of the structured block.
8092 // longjmp() and throw() must not violate the entry/exit criteria.
8093 CS->getCapturedDecl()->setNothrow();
8094
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008095 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8096 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8097 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8098 // 1.2.2 OpenMP Language Terminology
8099 // Structured block - An executable statement with a single entry at the
8100 // top and a single exit at the bottom.
8101 // The point of exit cannot be a branch out of the structured block.
8102 // longjmp() and throw() must not violate the entry/exit criteria.
8103 CS->getCapturedDecl()->setNothrow();
8104 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008105 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008106
8107 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8108 AStmt);
8109}
8110
Kelvin Li83c451e2016-12-25 04:52:54 +00008111StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8112 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008113 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008114 if (!AStmt)
8115 return StmtError();
8116
Alexey Bataeve3727102018-04-18 15:57:46 +00008117 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008118 // 1.2.2 OpenMP Language Terminology
8119 // Structured block - An executable statement with a single entry at the
8120 // top and a single exit at the bottom.
8121 // The point of exit cannot be a branch out of the structured block.
8122 // longjmp() and throw() must not violate the entry/exit criteria.
8123 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008124 for (int ThisCaptureLevel =
8125 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8126 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8127 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8128 // 1.2.2 OpenMP Language Terminology
8129 // Structured block - An executable statement with a single entry at the
8130 // top and a single exit at the bottom.
8131 // The point of exit cannot be a branch out of the structured block.
8132 // longjmp() and throw() must not violate the entry/exit criteria.
8133 CS->getCapturedDecl()->setNothrow();
8134 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008135
8136 OMPLoopDirective::HelperExprs B;
8137 // In presence of clause 'collapse' with number of loops, it will
8138 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008139 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008140 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8141 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008142 VarsWithImplicitDSA, B);
8143 if (NestedLoopCount == 0)
8144 return StmtError();
8145
8146 assert((CurContext->isDependentContext() || B.builtAll()) &&
8147 "omp target teams distribute loop exprs were not built");
8148
Reid Kleckner87a31802018-03-12 21:43:02 +00008149 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008150 return OMPTargetTeamsDistributeDirective::Create(
8151 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8152}
8153
Kelvin Li80e8f562016-12-29 22:16:30 +00008154StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8155 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008156 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008157 if (!AStmt)
8158 return StmtError();
8159
Alexey Bataeve3727102018-04-18 15:57:46 +00008160 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008161 // 1.2.2 OpenMP Language Terminology
8162 // Structured block - An executable statement with a single entry at the
8163 // top and a single exit at the bottom.
8164 // The point of exit cannot be a branch out of the structured block.
8165 // longjmp() and throw() must not violate the entry/exit criteria.
8166 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008167 for (int ThisCaptureLevel =
8168 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8169 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8170 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8171 // 1.2.2 OpenMP Language Terminology
8172 // Structured block - An executable statement with a single entry at the
8173 // top and a single exit at the bottom.
8174 // The point of exit cannot be a branch out of the structured block.
8175 // longjmp() and throw() must not violate the entry/exit criteria.
8176 CS->getCapturedDecl()->setNothrow();
8177 }
8178
Kelvin Li80e8f562016-12-29 22:16:30 +00008179 OMPLoopDirective::HelperExprs B;
8180 // In presence of clause 'collapse' with number of loops, it will
8181 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008182 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008183 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8184 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008185 VarsWithImplicitDSA, B);
8186 if (NestedLoopCount == 0)
8187 return StmtError();
8188
8189 assert((CurContext->isDependentContext() || B.builtAll()) &&
8190 "omp target teams distribute parallel for loop exprs were not built");
8191
Alexey Bataev647dd842018-01-15 20:59:40 +00008192 if (!CurContext->isDependentContext()) {
8193 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008194 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008195 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8196 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8197 B.NumIterations, *this, CurScope,
8198 DSAStack))
8199 return StmtError();
8200 }
8201 }
8202
Reid Kleckner87a31802018-03-12 21:43:02 +00008203 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008204 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008205 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8206 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008207}
8208
Kelvin Li1851df52017-01-03 05:23:48 +00008209StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008212 if (!AStmt)
8213 return StmtError();
8214
Alexey Bataeve3727102018-04-18 15:57:46 +00008215 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008216 // 1.2.2 OpenMP Language Terminology
8217 // Structured block - An executable statement with a single entry at the
8218 // top and a single exit at the bottom.
8219 // The point of exit cannot be a branch out of the structured block.
8220 // longjmp() and throw() must not violate the entry/exit criteria.
8221 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008222 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8223 OMPD_target_teams_distribute_parallel_for_simd);
8224 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8225 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8226 // 1.2.2 OpenMP Language Terminology
8227 // Structured block - An executable statement with a single entry at the
8228 // top and a single exit at the bottom.
8229 // The point of exit cannot be a branch out of the structured block.
8230 // longjmp() and throw() must not violate the entry/exit criteria.
8231 CS->getCapturedDecl()->setNothrow();
8232 }
Kelvin Li1851df52017-01-03 05:23:48 +00008233
8234 OMPLoopDirective::HelperExprs B;
8235 // In presence of clause 'collapse' with number of loops, it will
8236 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008237 unsigned NestedLoopCount =
8238 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008239 getCollapseNumberExpr(Clauses),
8240 nullptr /*ordered not a clause on distribute*/, CS, *this,
8241 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008242 if (NestedLoopCount == 0)
8243 return StmtError();
8244
8245 assert((CurContext->isDependentContext() || B.builtAll()) &&
8246 "omp target teams distribute parallel for simd loop exprs were not "
8247 "built");
8248
8249 if (!CurContext->isDependentContext()) {
8250 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008251 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008252 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8253 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8254 B.NumIterations, *this, CurScope,
8255 DSAStack))
8256 return StmtError();
8257 }
8258 }
8259
Alexey Bataev438388c2017-11-22 18:34:02 +00008260 if (checkSimdlenSafelenSpecified(*this, Clauses))
8261 return StmtError();
8262
Reid Kleckner87a31802018-03-12 21:43:02 +00008263 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008264 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8265 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8266}
8267
Kelvin Lida681182017-01-10 18:08:18 +00008268StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8269 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008270 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008271 if (!AStmt)
8272 return StmtError();
8273
8274 auto *CS = cast<CapturedStmt>(AStmt);
8275 // 1.2.2 OpenMP Language Terminology
8276 // Structured block - An executable statement with a single entry at the
8277 // top and a single exit at the bottom.
8278 // The point of exit cannot be a branch out of the structured block.
8279 // longjmp() and throw() must not violate the entry/exit criteria.
8280 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008281 for (int ThisCaptureLevel =
8282 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8283 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8284 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8285 // 1.2.2 OpenMP Language Terminology
8286 // Structured block - An executable statement with a single entry at the
8287 // top and a single exit at the bottom.
8288 // The point of exit cannot be a branch out of the structured block.
8289 // longjmp() and throw() must not violate the entry/exit criteria.
8290 CS->getCapturedDecl()->setNothrow();
8291 }
Kelvin Lida681182017-01-10 18:08:18 +00008292
8293 OMPLoopDirective::HelperExprs B;
8294 // In presence of clause 'collapse' with number of loops, it will
8295 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008296 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008297 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008298 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008299 VarsWithImplicitDSA, B);
8300 if (NestedLoopCount == 0)
8301 return StmtError();
8302
8303 assert((CurContext->isDependentContext() || B.builtAll()) &&
8304 "omp target teams distribute simd loop exprs were not built");
8305
Alexey Bataev438388c2017-11-22 18:34:02 +00008306 if (!CurContext->isDependentContext()) {
8307 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008308 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008309 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8310 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8311 B.NumIterations, *this, CurScope,
8312 DSAStack))
8313 return StmtError();
8314 }
8315 }
8316
8317 if (checkSimdlenSafelenSpecified(*this, Clauses))
8318 return StmtError();
8319
Reid Kleckner87a31802018-03-12 21:43:02 +00008320 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008321 return OMPTargetTeamsDistributeSimdDirective::Create(
8322 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8323}
8324
Alexey Bataeved09d242014-05-28 05:53:51 +00008325OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008326 SourceLocation StartLoc,
8327 SourceLocation LParenLoc,
8328 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008329 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008330 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008331 case OMPC_final:
8332 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8333 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008334 case OMPC_num_threads:
8335 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8336 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008337 case OMPC_safelen:
8338 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8339 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008340 case OMPC_simdlen:
8341 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8342 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008343 case OMPC_collapse:
8344 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8345 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008346 case OMPC_ordered:
8347 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8348 break;
Michael Wonge710d542015-08-07 16:16:36 +00008349 case OMPC_device:
8350 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8351 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008352 case OMPC_num_teams:
8353 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8354 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008355 case OMPC_thread_limit:
8356 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8357 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008358 case OMPC_priority:
8359 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8360 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008361 case OMPC_grainsize:
8362 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8363 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008364 case OMPC_num_tasks:
8365 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8366 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008367 case OMPC_hint:
8368 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8369 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008370 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008371 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008372 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008373 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008374 case OMPC_private:
8375 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008376 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008377 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008378 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008379 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008380 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008381 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008382 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008383 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008384 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008385 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008386 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008387 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008388 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008389 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008390 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008391 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008392 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008393 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008394 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008395 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008396 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008397 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008398 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008399 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008400 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008401 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008402 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008403 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008404 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008405 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008406 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008407 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008408 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008409 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008410 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008411 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008412 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008413 llvm_unreachable("Clause is not allowed.");
8414 }
8415 return Res;
8416}
8417
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008418// An OpenMP directive such as 'target parallel' has two captured regions:
8419// for the 'target' and 'parallel' respectively. This function returns
8420// the region in which to capture expressions associated with a clause.
8421// A return value of OMPD_unknown signifies that the expression should not
8422// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008423static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8424 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8425 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008426 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008427 switch (CKind) {
8428 case OMPC_if:
8429 switch (DKind) {
8430 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008431 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008432 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008433 // If this clause applies to the nested 'parallel' region, capture within
8434 // the 'target' region, otherwise do not capture.
8435 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8436 CaptureRegion = OMPD_target;
8437 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008438 case OMPD_target_teams_distribute_parallel_for:
8439 case OMPD_target_teams_distribute_parallel_for_simd:
8440 // If this clause applies to the nested 'parallel' region, capture within
8441 // the 'teams' region, otherwise do not capture.
8442 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8443 CaptureRegion = OMPD_teams;
8444 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008445 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008446 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008447 CaptureRegion = OMPD_teams;
8448 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008449 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008450 case OMPD_target_enter_data:
8451 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008452 CaptureRegion = OMPD_task;
8453 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008454 case OMPD_cancel:
8455 case OMPD_parallel:
8456 case OMPD_parallel_sections:
8457 case OMPD_parallel_for:
8458 case OMPD_parallel_for_simd:
8459 case OMPD_target:
8460 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008461 case OMPD_target_teams:
8462 case OMPD_target_teams_distribute:
8463 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008464 case OMPD_distribute_parallel_for:
8465 case OMPD_distribute_parallel_for_simd:
8466 case OMPD_task:
8467 case OMPD_taskloop:
8468 case OMPD_taskloop_simd:
8469 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008470 // Do not capture if-clause expressions.
8471 break;
8472 case OMPD_threadprivate:
8473 case OMPD_taskyield:
8474 case OMPD_barrier:
8475 case OMPD_taskwait:
8476 case OMPD_cancellation_point:
8477 case OMPD_flush:
8478 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008479 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008480 case OMPD_declare_simd:
8481 case OMPD_declare_target:
8482 case OMPD_end_declare_target:
8483 case OMPD_teams:
8484 case OMPD_simd:
8485 case OMPD_for:
8486 case OMPD_for_simd:
8487 case OMPD_sections:
8488 case OMPD_section:
8489 case OMPD_single:
8490 case OMPD_master:
8491 case OMPD_critical:
8492 case OMPD_taskgroup:
8493 case OMPD_distribute:
8494 case OMPD_ordered:
8495 case OMPD_atomic:
8496 case OMPD_distribute_simd:
8497 case OMPD_teams_distribute:
8498 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008499 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008500 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8501 case OMPD_unknown:
8502 llvm_unreachable("Unknown OpenMP directive");
8503 }
8504 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008505 case OMPC_num_threads:
8506 switch (DKind) {
8507 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008508 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008509 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008510 CaptureRegion = OMPD_target;
8511 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008512 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008513 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008514 case OMPD_target_teams_distribute_parallel_for:
8515 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008516 CaptureRegion = OMPD_teams;
8517 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008518 case OMPD_parallel:
8519 case OMPD_parallel_sections:
8520 case OMPD_parallel_for:
8521 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008522 case OMPD_distribute_parallel_for:
8523 case OMPD_distribute_parallel_for_simd:
8524 // Do not capture num_threads-clause expressions.
8525 break;
8526 case OMPD_target_data:
8527 case OMPD_target_enter_data:
8528 case OMPD_target_exit_data:
8529 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008530 case OMPD_target:
8531 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008532 case OMPD_target_teams:
8533 case OMPD_target_teams_distribute:
8534 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008535 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008536 case OMPD_task:
8537 case OMPD_taskloop:
8538 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008539 case OMPD_threadprivate:
8540 case OMPD_taskyield:
8541 case OMPD_barrier:
8542 case OMPD_taskwait:
8543 case OMPD_cancellation_point:
8544 case OMPD_flush:
8545 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008546 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008547 case OMPD_declare_simd:
8548 case OMPD_declare_target:
8549 case OMPD_end_declare_target:
8550 case OMPD_teams:
8551 case OMPD_simd:
8552 case OMPD_for:
8553 case OMPD_for_simd:
8554 case OMPD_sections:
8555 case OMPD_section:
8556 case OMPD_single:
8557 case OMPD_master:
8558 case OMPD_critical:
8559 case OMPD_taskgroup:
8560 case OMPD_distribute:
8561 case OMPD_ordered:
8562 case OMPD_atomic:
8563 case OMPD_distribute_simd:
8564 case OMPD_teams_distribute:
8565 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008566 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008567 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8568 case OMPD_unknown:
8569 llvm_unreachable("Unknown OpenMP directive");
8570 }
8571 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008572 case OMPC_num_teams:
8573 switch (DKind) {
8574 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008575 case OMPD_target_teams_distribute:
8576 case OMPD_target_teams_distribute_simd:
8577 case OMPD_target_teams_distribute_parallel_for:
8578 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008579 CaptureRegion = OMPD_target;
8580 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008581 case OMPD_teams_distribute_parallel_for:
8582 case OMPD_teams_distribute_parallel_for_simd:
8583 case OMPD_teams:
8584 case OMPD_teams_distribute:
8585 case OMPD_teams_distribute_simd:
8586 // Do not capture num_teams-clause expressions.
8587 break;
8588 case OMPD_distribute_parallel_for:
8589 case OMPD_distribute_parallel_for_simd:
8590 case OMPD_task:
8591 case OMPD_taskloop:
8592 case OMPD_taskloop_simd:
8593 case OMPD_target_data:
8594 case OMPD_target_enter_data:
8595 case OMPD_target_exit_data:
8596 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008597 case OMPD_cancel:
8598 case OMPD_parallel:
8599 case OMPD_parallel_sections:
8600 case OMPD_parallel_for:
8601 case OMPD_parallel_for_simd:
8602 case OMPD_target:
8603 case OMPD_target_simd:
8604 case OMPD_target_parallel:
8605 case OMPD_target_parallel_for:
8606 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008607 case OMPD_threadprivate:
8608 case OMPD_taskyield:
8609 case OMPD_barrier:
8610 case OMPD_taskwait:
8611 case OMPD_cancellation_point:
8612 case OMPD_flush:
8613 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008614 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008615 case OMPD_declare_simd:
8616 case OMPD_declare_target:
8617 case OMPD_end_declare_target:
8618 case OMPD_simd:
8619 case OMPD_for:
8620 case OMPD_for_simd:
8621 case OMPD_sections:
8622 case OMPD_section:
8623 case OMPD_single:
8624 case OMPD_master:
8625 case OMPD_critical:
8626 case OMPD_taskgroup:
8627 case OMPD_distribute:
8628 case OMPD_ordered:
8629 case OMPD_atomic:
8630 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008631 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008632 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8633 case OMPD_unknown:
8634 llvm_unreachable("Unknown OpenMP directive");
8635 }
8636 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008637 case OMPC_thread_limit:
8638 switch (DKind) {
8639 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008640 case OMPD_target_teams_distribute:
8641 case OMPD_target_teams_distribute_simd:
8642 case OMPD_target_teams_distribute_parallel_for:
8643 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008644 CaptureRegion = OMPD_target;
8645 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008646 case OMPD_teams_distribute_parallel_for:
8647 case OMPD_teams_distribute_parallel_for_simd:
8648 case OMPD_teams:
8649 case OMPD_teams_distribute:
8650 case OMPD_teams_distribute_simd:
8651 // Do not capture thread_limit-clause expressions.
8652 break;
8653 case OMPD_distribute_parallel_for:
8654 case OMPD_distribute_parallel_for_simd:
8655 case OMPD_task:
8656 case OMPD_taskloop:
8657 case OMPD_taskloop_simd:
8658 case OMPD_target_data:
8659 case OMPD_target_enter_data:
8660 case OMPD_target_exit_data:
8661 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008662 case OMPD_cancel:
8663 case OMPD_parallel:
8664 case OMPD_parallel_sections:
8665 case OMPD_parallel_for:
8666 case OMPD_parallel_for_simd:
8667 case OMPD_target:
8668 case OMPD_target_simd:
8669 case OMPD_target_parallel:
8670 case OMPD_target_parallel_for:
8671 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008672 case OMPD_threadprivate:
8673 case OMPD_taskyield:
8674 case OMPD_barrier:
8675 case OMPD_taskwait:
8676 case OMPD_cancellation_point:
8677 case OMPD_flush:
8678 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008679 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008680 case OMPD_declare_simd:
8681 case OMPD_declare_target:
8682 case OMPD_end_declare_target:
8683 case OMPD_simd:
8684 case OMPD_for:
8685 case OMPD_for_simd:
8686 case OMPD_sections:
8687 case OMPD_section:
8688 case OMPD_single:
8689 case OMPD_master:
8690 case OMPD_critical:
8691 case OMPD_taskgroup:
8692 case OMPD_distribute:
8693 case OMPD_ordered:
8694 case OMPD_atomic:
8695 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008696 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008697 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8698 case OMPD_unknown:
8699 llvm_unreachable("Unknown OpenMP directive");
8700 }
8701 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008702 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008703 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008704 case OMPD_parallel_for:
8705 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008706 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008707 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008708 case OMPD_teams_distribute_parallel_for:
8709 case OMPD_teams_distribute_parallel_for_simd:
8710 case OMPD_target_parallel_for:
8711 case OMPD_target_parallel_for_simd:
8712 case OMPD_target_teams_distribute_parallel_for:
8713 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008714 CaptureRegion = OMPD_parallel;
8715 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008716 case OMPD_for:
8717 case OMPD_for_simd:
8718 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008719 break;
8720 case OMPD_task:
8721 case OMPD_taskloop:
8722 case OMPD_taskloop_simd:
8723 case OMPD_target_data:
8724 case OMPD_target_enter_data:
8725 case OMPD_target_exit_data:
8726 case OMPD_target_update:
8727 case OMPD_teams:
8728 case OMPD_teams_distribute:
8729 case OMPD_teams_distribute_simd:
8730 case OMPD_target_teams_distribute:
8731 case OMPD_target_teams_distribute_simd:
8732 case OMPD_target:
8733 case OMPD_target_simd:
8734 case OMPD_target_parallel:
8735 case OMPD_cancel:
8736 case OMPD_parallel:
8737 case OMPD_parallel_sections:
8738 case OMPD_threadprivate:
8739 case OMPD_taskyield:
8740 case OMPD_barrier:
8741 case OMPD_taskwait:
8742 case OMPD_cancellation_point:
8743 case OMPD_flush:
8744 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008745 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008746 case OMPD_declare_simd:
8747 case OMPD_declare_target:
8748 case OMPD_end_declare_target:
8749 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008750 case OMPD_sections:
8751 case OMPD_section:
8752 case OMPD_single:
8753 case OMPD_master:
8754 case OMPD_critical:
8755 case OMPD_taskgroup:
8756 case OMPD_distribute:
8757 case OMPD_ordered:
8758 case OMPD_atomic:
8759 case OMPD_distribute_simd:
8760 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008761 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008762 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8763 case OMPD_unknown:
8764 llvm_unreachable("Unknown OpenMP directive");
8765 }
8766 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008767 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008768 switch (DKind) {
8769 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008770 case OMPD_teams_distribute_parallel_for_simd:
8771 case OMPD_teams_distribute:
8772 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008773 case OMPD_target_teams_distribute_parallel_for:
8774 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008775 case OMPD_target_teams_distribute:
8776 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008777 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008778 break;
8779 case OMPD_distribute_parallel_for:
8780 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008781 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008782 case OMPD_distribute_simd:
8783 // Do not capture thread_limit-clause expressions.
8784 break;
8785 case OMPD_parallel_for:
8786 case OMPD_parallel_for_simd:
8787 case OMPD_target_parallel_for_simd:
8788 case OMPD_target_parallel_for:
8789 case OMPD_task:
8790 case OMPD_taskloop:
8791 case OMPD_taskloop_simd:
8792 case OMPD_target_data:
8793 case OMPD_target_enter_data:
8794 case OMPD_target_exit_data:
8795 case OMPD_target_update:
8796 case OMPD_teams:
8797 case OMPD_target:
8798 case OMPD_target_simd:
8799 case OMPD_target_parallel:
8800 case OMPD_cancel:
8801 case OMPD_parallel:
8802 case OMPD_parallel_sections:
8803 case OMPD_threadprivate:
8804 case OMPD_taskyield:
8805 case OMPD_barrier:
8806 case OMPD_taskwait:
8807 case OMPD_cancellation_point:
8808 case OMPD_flush:
8809 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008810 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008811 case OMPD_declare_simd:
8812 case OMPD_declare_target:
8813 case OMPD_end_declare_target:
8814 case OMPD_simd:
8815 case OMPD_for:
8816 case OMPD_for_simd:
8817 case OMPD_sections:
8818 case OMPD_section:
8819 case OMPD_single:
8820 case OMPD_master:
8821 case OMPD_critical:
8822 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008823 case OMPD_ordered:
8824 case OMPD_atomic:
8825 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008826 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008827 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8828 case OMPD_unknown:
8829 llvm_unreachable("Unknown OpenMP directive");
8830 }
8831 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008832 case OMPC_device:
8833 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008834 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008835 case OMPD_target_enter_data:
8836 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008837 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008838 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008839 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008840 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008841 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008842 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008843 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008844 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008845 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008846 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008847 CaptureRegion = OMPD_task;
8848 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008849 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008850 // Do not capture device-clause expressions.
8851 break;
8852 case OMPD_teams_distribute_parallel_for:
8853 case OMPD_teams_distribute_parallel_for_simd:
8854 case OMPD_teams:
8855 case OMPD_teams_distribute:
8856 case OMPD_teams_distribute_simd:
8857 case OMPD_distribute_parallel_for:
8858 case OMPD_distribute_parallel_for_simd:
8859 case OMPD_task:
8860 case OMPD_taskloop:
8861 case OMPD_taskloop_simd:
8862 case OMPD_cancel:
8863 case OMPD_parallel:
8864 case OMPD_parallel_sections:
8865 case OMPD_parallel_for:
8866 case OMPD_parallel_for_simd:
8867 case OMPD_threadprivate:
8868 case OMPD_taskyield:
8869 case OMPD_barrier:
8870 case OMPD_taskwait:
8871 case OMPD_cancellation_point:
8872 case OMPD_flush:
8873 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008874 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008875 case OMPD_declare_simd:
8876 case OMPD_declare_target:
8877 case OMPD_end_declare_target:
8878 case OMPD_simd:
8879 case OMPD_for:
8880 case OMPD_for_simd:
8881 case OMPD_sections:
8882 case OMPD_section:
8883 case OMPD_single:
8884 case OMPD_master:
8885 case OMPD_critical:
8886 case OMPD_taskgroup:
8887 case OMPD_distribute:
8888 case OMPD_ordered:
8889 case OMPD_atomic:
8890 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008891 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008892 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8893 case OMPD_unknown:
8894 llvm_unreachable("Unknown OpenMP directive");
8895 }
8896 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008897 case OMPC_firstprivate:
8898 case OMPC_lastprivate:
8899 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008900 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008901 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008902 case OMPC_linear:
8903 case OMPC_default:
8904 case OMPC_proc_bind:
8905 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008906 case OMPC_safelen:
8907 case OMPC_simdlen:
8908 case OMPC_collapse:
8909 case OMPC_private:
8910 case OMPC_shared:
8911 case OMPC_aligned:
8912 case OMPC_copyin:
8913 case OMPC_copyprivate:
8914 case OMPC_ordered:
8915 case OMPC_nowait:
8916 case OMPC_untied:
8917 case OMPC_mergeable:
8918 case OMPC_threadprivate:
8919 case OMPC_flush:
8920 case OMPC_read:
8921 case OMPC_write:
8922 case OMPC_update:
8923 case OMPC_capture:
8924 case OMPC_seq_cst:
8925 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008926 case OMPC_threads:
8927 case OMPC_simd:
8928 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008929 case OMPC_priority:
8930 case OMPC_grainsize:
8931 case OMPC_nogroup:
8932 case OMPC_num_tasks:
8933 case OMPC_hint:
8934 case OMPC_defaultmap:
8935 case OMPC_unknown:
8936 case OMPC_uniform:
8937 case OMPC_to:
8938 case OMPC_from:
8939 case OMPC_use_device_ptr:
8940 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008941 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008942 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008943 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008944 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008945 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008946 llvm_unreachable("Unexpected OpenMP clause.");
8947 }
8948 return CaptureRegion;
8949}
8950
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008951OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8952 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008953 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008954 SourceLocation NameModifierLoc,
8955 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008956 SourceLocation EndLoc) {
8957 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008958 Stmt *HelperValStmt = nullptr;
8959 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008960 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8961 !Condition->isInstantiationDependent() &&
8962 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008963 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008964 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008965 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008966
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008967 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008968
8969 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8970 CaptureRegion =
8971 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008972 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008973 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008974 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008975 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8976 HelperValStmt = buildPreInits(Context, Captures);
8977 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008978 }
8979
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008980 return new (Context)
8981 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8982 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008983}
8984
Alexey Bataev3778b602014-07-17 07:32:53 +00008985OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8986 SourceLocation StartLoc,
8987 SourceLocation LParenLoc,
8988 SourceLocation EndLoc) {
8989 Expr *ValExpr = Condition;
8990 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8991 !Condition->isInstantiationDependent() &&
8992 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008993 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008994 if (Val.isInvalid())
8995 return nullptr;
8996
Richard Smith03a4aa32016-06-23 19:02:52 +00008997 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008998 }
8999
9000 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9001}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009002ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9003 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009004 if (!Op)
9005 return ExprError();
9006
9007 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9008 public:
9009 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009010 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009011 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9012 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009013 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9014 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009015 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9016 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009017 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9018 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009019 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9020 QualType T,
9021 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009022 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9023 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009024 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9025 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009026 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009027 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009028 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009029 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9030 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009031 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9032 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009033 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9034 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009035 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009036 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009037 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009038 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9039 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009040 llvm_unreachable("conversion functions are permitted");
9041 }
9042 } ConvertDiagnoser;
9043 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9044}
9045
Alexey Bataeve3727102018-04-18 15:57:46 +00009046static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009047 OpenMPClauseKind CKind,
9048 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009049 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9050 !ValExpr->isInstantiationDependent()) {
9051 SourceLocation Loc = ValExpr->getExprLoc();
9052 ExprResult Value =
9053 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9054 if (Value.isInvalid())
9055 return false;
9056
9057 ValExpr = Value.get();
9058 // The expression must evaluate to a non-negative integer value.
9059 llvm::APSInt Result;
9060 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009061 Result.isSigned() &&
9062 !((!StrictlyPositive && Result.isNonNegative()) ||
9063 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009064 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009065 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9066 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009067 return false;
9068 }
9069 }
9070 return true;
9071}
9072
Alexey Bataev568a8332014-03-06 06:15:19 +00009073OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9074 SourceLocation StartLoc,
9075 SourceLocation LParenLoc,
9076 SourceLocation EndLoc) {
9077 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009078 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009079
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009080 // OpenMP [2.5, Restrictions]
9081 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009082 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009083 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009084 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009085
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009086 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009087 OpenMPDirectiveKind CaptureRegion =
9088 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9089 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009090 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009091 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009092 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9093 HelperValStmt = buildPreInits(Context, Captures);
9094 }
9095
9096 return new (Context) OMPNumThreadsClause(
9097 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009098}
9099
Alexey Bataev62c87d22014-03-21 04:51:18 +00009100ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009101 OpenMPClauseKind CKind,
9102 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009103 if (!E)
9104 return ExprError();
9105 if (E->isValueDependent() || E->isTypeDependent() ||
9106 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009107 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009108 llvm::APSInt Result;
9109 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9110 if (ICE.isInvalid())
9111 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009112 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9113 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009114 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009115 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9116 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009117 return ExprError();
9118 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009119 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9120 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9121 << E->getSourceRange();
9122 return ExprError();
9123 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009124 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9125 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009126 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009127 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009128 return ICE;
9129}
9130
9131OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9132 SourceLocation LParenLoc,
9133 SourceLocation EndLoc) {
9134 // OpenMP [2.8.1, simd construct, Description]
9135 // The parameter of the safelen clause must be a constant
9136 // positive integer expression.
9137 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9138 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009139 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009140 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009141 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009142}
9143
Alexey Bataev66b15b52015-08-21 11:14:16 +00009144OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9145 SourceLocation LParenLoc,
9146 SourceLocation EndLoc) {
9147 // OpenMP [2.8.1, simd construct, Description]
9148 // The parameter of the simdlen clause must be a constant
9149 // positive integer expression.
9150 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9151 if (Simdlen.isInvalid())
9152 return nullptr;
9153 return new (Context)
9154 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9155}
9156
Alexander Musman64d33f12014-06-04 07:53:32 +00009157OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9158 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009159 SourceLocation LParenLoc,
9160 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009161 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009162 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009163 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009164 // The parameter of the collapse clause must be a constant
9165 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009166 ExprResult NumForLoopsResult =
9167 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9168 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009169 return nullptr;
9170 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009171 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009172}
9173
Alexey Bataev10e775f2015-07-30 11:36:16 +00009174OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9175 SourceLocation EndLoc,
9176 SourceLocation LParenLoc,
9177 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009178 // OpenMP [2.7.1, loop construct, Description]
9179 // OpenMP [2.8.1, simd construct, Description]
9180 // OpenMP [2.9.6, distribute construct, Description]
9181 // The parameter of the ordered clause must be a constant
9182 // positive integer expression if any.
9183 if (NumForLoops && LParenLoc.isValid()) {
9184 ExprResult NumForLoopsResult =
9185 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9186 if (NumForLoopsResult.isInvalid())
9187 return nullptr;
9188 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009189 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009190 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009191 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009192 auto *Clause = OMPOrderedClause::Create(
9193 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9194 StartLoc, LParenLoc, EndLoc);
9195 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9196 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009197}
9198
Alexey Bataeved09d242014-05-28 05:53:51 +00009199OMPClause *Sema::ActOnOpenMPSimpleClause(
9200 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9201 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009202 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009203 switch (Kind) {
9204 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009205 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009206 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9207 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009208 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009209 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009210 Res = ActOnOpenMPProcBindClause(
9211 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9212 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009213 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009214 case OMPC_atomic_default_mem_order:
9215 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9216 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9217 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9218 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009219 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009220 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009221 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009222 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009223 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009224 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009225 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009226 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009227 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009228 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009229 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009230 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009231 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009232 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009233 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009234 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009235 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009236 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009237 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009238 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009239 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009240 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009241 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009242 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009243 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009244 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009245 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009246 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009247 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009248 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009249 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009250 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009251 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009252 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009253 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009254 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009255 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009256 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009257 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009258 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009259 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009260 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009261 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009262 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009263 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009264 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009265 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009266 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009267 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009268 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009269 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009270 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009271 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009272 llvm_unreachable("Clause is not allowed.");
9273 }
9274 return Res;
9275}
9276
Alexey Bataev6402bca2015-12-28 07:25:51 +00009277static std::string
9278getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9279 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009280 SmallString<256> Buffer;
9281 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009282 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9283 unsigned Skipped = Exclude.size();
9284 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009285 for (unsigned I = First; I < Last; ++I) {
9286 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009287 --Skipped;
9288 continue;
9289 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009290 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9291 if (I == Bound - Skipped)
9292 Out << " or ";
9293 else if (I != Bound + 1 - Skipped)
9294 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009295 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009296 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009297}
9298
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009299OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9300 SourceLocation KindKwLoc,
9301 SourceLocation StartLoc,
9302 SourceLocation LParenLoc,
9303 SourceLocation EndLoc) {
9304 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009305 static_assert(OMPC_DEFAULT_unknown > 0,
9306 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009307 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009308 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9309 /*Last=*/OMPC_DEFAULT_unknown)
9310 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009311 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009312 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009313 switch (Kind) {
9314 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009315 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009316 break;
9317 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009318 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009319 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009320 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009321 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009322 break;
9323 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009324 return new (Context)
9325 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009326}
9327
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009328OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9329 SourceLocation KindKwLoc,
9330 SourceLocation StartLoc,
9331 SourceLocation LParenLoc,
9332 SourceLocation EndLoc) {
9333 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009334 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009335 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9336 /*Last=*/OMPC_PROC_BIND_unknown)
9337 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009338 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009339 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009340 return new (Context)
9341 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009342}
9343
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009344OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9345 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9346 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9347 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9348 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9349 << getListOfPossibleValues(
9350 OMPC_atomic_default_mem_order, /*First=*/0,
9351 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9352 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9353 return nullptr;
9354 }
9355 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9356 LParenLoc, EndLoc);
9357}
9358
Alexey Bataev56dafe82014-06-20 07:16:17 +00009359OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009360 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009361 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009362 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009363 SourceLocation EndLoc) {
9364 OMPClause *Res = nullptr;
9365 switch (Kind) {
9366 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009367 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9368 assert(Argument.size() == NumberOfElements &&
9369 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009370 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009371 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9372 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9373 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9374 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9375 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009376 break;
9377 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009378 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9379 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9380 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9381 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009382 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009383 case OMPC_dist_schedule:
9384 Res = ActOnOpenMPDistScheduleClause(
9385 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9386 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9387 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009388 case OMPC_defaultmap:
9389 enum { Modifier, DefaultmapKind };
9390 Res = ActOnOpenMPDefaultmapClause(
9391 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9392 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009393 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9394 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009395 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009396 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009397 case OMPC_num_threads:
9398 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009399 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009400 case OMPC_collapse:
9401 case OMPC_default:
9402 case OMPC_proc_bind:
9403 case OMPC_private:
9404 case OMPC_firstprivate:
9405 case OMPC_lastprivate:
9406 case OMPC_shared:
9407 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009408 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009409 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009410 case OMPC_linear:
9411 case OMPC_aligned:
9412 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009413 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009414 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009415 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009416 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009417 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009418 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009419 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009420 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009421 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009422 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009423 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009424 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009425 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009426 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009427 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009428 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009429 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009430 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009431 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009432 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009433 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009434 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009435 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009436 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009437 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009438 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009439 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009440 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009441 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009442 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009443 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009444 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009445 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009446 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009447 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009448 llvm_unreachable("Clause is not allowed.");
9449 }
9450 return Res;
9451}
9452
Alexey Bataev6402bca2015-12-28 07:25:51 +00009453static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9454 OpenMPScheduleClauseModifier M2,
9455 SourceLocation M1Loc, SourceLocation M2Loc) {
9456 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9457 SmallVector<unsigned, 2> Excluded;
9458 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9459 Excluded.push_back(M2);
9460 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9461 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9462 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9463 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9464 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9465 << getListOfPossibleValues(OMPC_schedule,
9466 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9467 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9468 Excluded)
9469 << getOpenMPClauseName(OMPC_schedule);
9470 return true;
9471 }
9472 return false;
9473}
9474
Alexey Bataev56dafe82014-06-20 07:16:17 +00009475OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009476 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009477 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009478 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9479 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9480 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9481 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9482 return nullptr;
9483 // OpenMP, 2.7.1, Loop Construct, Restrictions
9484 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9485 // but not both.
9486 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9487 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9488 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9489 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9490 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9491 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9492 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9493 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9494 return nullptr;
9495 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009496 if (Kind == OMPC_SCHEDULE_unknown) {
9497 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009498 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9499 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9500 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9501 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9502 Exclude);
9503 } else {
9504 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9505 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009506 }
9507 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9508 << Values << getOpenMPClauseName(OMPC_schedule);
9509 return nullptr;
9510 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009511 // OpenMP, 2.7.1, Loop Construct, Restrictions
9512 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9513 // schedule(guided).
9514 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9515 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9516 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9517 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9518 diag::err_omp_schedule_nonmonotonic_static);
9519 return nullptr;
9520 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009521 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009522 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009523 if (ChunkSize) {
9524 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9525 !ChunkSize->isInstantiationDependent() &&
9526 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009527 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009528 ExprResult Val =
9529 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9530 if (Val.isInvalid())
9531 return nullptr;
9532
9533 ValExpr = Val.get();
9534
9535 // OpenMP [2.7.1, Restrictions]
9536 // chunk_size must be a loop invariant integer expression with a positive
9537 // value.
9538 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009539 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9540 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9541 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009542 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009543 return nullptr;
9544 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009545 } else if (getOpenMPCaptureRegionForClause(
9546 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9547 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009548 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009549 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009550 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009551 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9552 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009553 }
9554 }
9555 }
9556
Alexey Bataev6402bca2015-12-28 07:25:51 +00009557 return new (Context)
9558 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009559 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009560}
9561
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009562OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9563 SourceLocation StartLoc,
9564 SourceLocation EndLoc) {
9565 OMPClause *Res = nullptr;
9566 switch (Kind) {
9567 case OMPC_ordered:
9568 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9569 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009570 case OMPC_nowait:
9571 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9572 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009573 case OMPC_untied:
9574 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9575 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009576 case OMPC_mergeable:
9577 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9578 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009579 case OMPC_read:
9580 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9581 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009582 case OMPC_write:
9583 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9584 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009585 case OMPC_update:
9586 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9587 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009588 case OMPC_capture:
9589 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9590 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009591 case OMPC_seq_cst:
9592 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9593 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009594 case OMPC_threads:
9595 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9596 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009597 case OMPC_simd:
9598 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9599 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009600 case OMPC_nogroup:
9601 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9602 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009603 case OMPC_unified_address:
9604 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9605 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009606 case OMPC_unified_shared_memory:
9607 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9608 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009609 case OMPC_reverse_offload:
9610 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9611 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009612 case OMPC_dynamic_allocators:
9613 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9614 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009615 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009616 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009617 case OMPC_num_threads:
9618 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009619 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009620 case OMPC_collapse:
9621 case OMPC_schedule:
9622 case OMPC_private:
9623 case OMPC_firstprivate:
9624 case OMPC_lastprivate:
9625 case OMPC_shared:
9626 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009627 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009628 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009629 case OMPC_linear:
9630 case OMPC_aligned:
9631 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009632 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009633 case OMPC_default:
9634 case OMPC_proc_bind:
9635 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009636 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009637 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009638 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009639 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009640 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009641 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009642 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009643 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009644 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009645 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009646 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009647 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009648 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009649 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009650 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009651 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009652 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009653 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009654 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009655 llvm_unreachable("Clause is not allowed.");
9656 }
9657 return Res;
9658}
9659
Alexey Bataev236070f2014-06-20 11:19:47 +00009660OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9661 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009662 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009663 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9664}
9665
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009666OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9667 SourceLocation EndLoc) {
9668 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9669}
9670
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009671OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9672 SourceLocation EndLoc) {
9673 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9674}
9675
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009676OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9677 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009678 return new (Context) OMPReadClause(StartLoc, EndLoc);
9679}
9680
Alexey Bataevdea47612014-07-23 07:46:59 +00009681OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9682 SourceLocation EndLoc) {
9683 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9684}
9685
Alexey Bataev67a4f222014-07-23 10:25:33 +00009686OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9687 SourceLocation EndLoc) {
9688 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9689}
9690
Alexey Bataev459dec02014-07-24 06:46:57 +00009691OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9692 SourceLocation EndLoc) {
9693 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9694}
9695
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009696OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9697 SourceLocation EndLoc) {
9698 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9699}
9700
Alexey Bataev346265e2015-09-25 10:37:12 +00009701OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9702 SourceLocation EndLoc) {
9703 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9704}
9705
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009706OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9707 SourceLocation EndLoc) {
9708 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9709}
9710
Alexey Bataevb825de12015-12-07 10:51:44 +00009711OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9712 SourceLocation EndLoc) {
9713 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9714}
9715
Kelvin Li1408f912018-09-26 04:28:39 +00009716OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9717 SourceLocation EndLoc) {
9718 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9719}
9720
Patrick Lyster4a370b92018-10-01 13:47:43 +00009721OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9722 SourceLocation EndLoc) {
9723 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9724}
9725
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009726OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9727 SourceLocation EndLoc) {
9728 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9729}
9730
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009731OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9732 SourceLocation EndLoc) {
9733 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9734}
9735
Alexey Bataevc5e02582014-06-16 07:08:35 +00009736OMPClause *Sema::ActOnOpenMPVarListClause(
9737 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009738 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
9739 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
9740 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +00009741 OpenMPLinearClauseKind LinKind,
9742 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009743 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
9744 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
9745 SourceLocation StartLoc = Locs.StartLoc;
9746 SourceLocation LParenLoc = Locs.LParenLoc;
9747 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009748 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009749 switch (Kind) {
9750 case OMPC_private:
9751 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9752 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009753 case OMPC_firstprivate:
9754 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9755 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009756 case OMPC_lastprivate:
9757 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9758 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009759 case OMPC_shared:
9760 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9761 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009762 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009763 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009764 EndLoc, ReductionOrMapperIdScopeSpec,
9765 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009766 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009767 case OMPC_task_reduction:
9768 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009769 EndLoc, ReductionOrMapperIdScopeSpec,
9770 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +00009771 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009772 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009773 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9774 EndLoc, ReductionOrMapperIdScopeSpec,
9775 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +00009776 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009777 case OMPC_linear:
9778 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009779 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009780 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009781 case OMPC_aligned:
9782 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9783 ColonLoc, EndLoc);
9784 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009785 case OMPC_copyin:
9786 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9787 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009788 case OMPC_copyprivate:
9789 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9790 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009791 case OMPC_flush:
9792 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9793 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009794 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009795 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009796 StartLoc, LParenLoc, EndLoc);
9797 break;
9798 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009799 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
9800 ReductionOrMapperIdScopeSpec,
9801 ReductionOrMapperId, MapType, IsMapTypeImplicit,
9802 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009803 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009804 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +00009805 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
9806 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +00009807 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009808 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +00009809 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
9810 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +00009811 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009812 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009813 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +00009814 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009815 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009816 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +00009817 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009818 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009819 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009820 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009821 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009822 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009823 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009824 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009825 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009826 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009827 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009828 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009829 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009830 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009831 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009832 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009833 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009834 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009835 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009836 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009837 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009838 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009839 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009840 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009841 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009842 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009843 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009844 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009845 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009846 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009847 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009848 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009849 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009850 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +00009851 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009852 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009853 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009854 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009855 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009856 llvm_unreachable("Clause is not allowed.");
9857 }
9858 return Res;
9859}
9860
Alexey Bataev90c228f2016-02-08 09:29:13 +00009861ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009862 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009863 ExprResult Res = BuildDeclRefExpr(
9864 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9865 if (!Res.isUsable())
9866 return ExprError();
9867 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9868 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9869 if (!Res.isUsable())
9870 return ExprError();
9871 }
9872 if (VK != VK_LValue && Res.get()->isGLValue()) {
9873 Res = DefaultLvalueConversion(Res.get());
9874 if (!Res.isUsable())
9875 return ExprError();
9876 }
9877 return Res;
9878}
9879
Alexey Bataev60da77e2016-02-29 05:54:20 +00009880static std::pair<ValueDecl *, bool>
9881getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9882 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009883 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9884 RefExpr->containsUnexpandedParameterPack())
9885 return std::make_pair(nullptr, true);
9886
Alexey Bataevd985eda2016-02-10 11:29:16 +00009887 // OpenMP [3.1, C/C++]
9888 // A list item is a variable name.
9889 // OpenMP [2.9.3.3, Restrictions, p.1]
9890 // A variable that is part of another variable (as an array or
9891 // structure element) cannot appear in a private clause.
9892 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009893 enum {
9894 NoArrayExpr = -1,
9895 ArraySubscript = 0,
9896 OMPArraySection = 1
9897 } IsArrayExpr = NoArrayExpr;
9898 if (AllowArraySection) {
9899 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009900 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009901 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9902 Base = TempASE->getBase()->IgnoreParenImpCasts();
9903 RefExpr = Base;
9904 IsArrayExpr = ArraySubscript;
9905 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009906 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009907 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9908 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9909 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9910 Base = TempASE->getBase()->IgnoreParenImpCasts();
9911 RefExpr = Base;
9912 IsArrayExpr = OMPArraySection;
9913 }
9914 }
9915 ELoc = RefExpr->getExprLoc();
9916 ERange = RefExpr->getSourceRange();
9917 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009918 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9919 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9920 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9921 (S.getCurrentThisType().isNull() || !ME ||
9922 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9923 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009924 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009925 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9926 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009927 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009928 S.Diag(ELoc,
9929 AllowArraySection
9930 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9931 : diag::err_omp_expected_var_name_member_expr)
9932 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9933 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009934 return std::make_pair(nullptr, false);
9935 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009936 return std::make_pair(
9937 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009938}
9939
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009940OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9941 SourceLocation StartLoc,
9942 SourceLocation LParenLoc,
9943 SourceLocation EndLoc) {
9944 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009945 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00009946 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009947 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009948 SourceLocation ELoc;
9949 SourceRange ERange;
9950 Expr *SimpleRefExpr = RefExpr;
9951 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009952 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009953 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009954 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009955 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009956 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009957 ValueDecl *D = Res.first;
9958 if (!D)
9959 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009960
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009961 QualType Type = D->getType();
9962 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009963
9964 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9965 // A variable that appears in a private clause must not have an incomplete
9966 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009967 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009968 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009969 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009970
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009971 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
9972 // A variable that is privatized must not have a const-qualified type
9973 // unless it is of class type with a mutable member. This restriction does
9974 // not apply to the firstprivate clause.
9975 //
9976 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
9977 // A variable that appears in a private clause must not have a
9978 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +00009979 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009980 continue;
9981
Alexey Bataev758e55e2013-09-06 18:03:48 +00009982 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9983 // in a Construct]
9984 // Variables with the predetermined data-sharing attributes may not be
9985 // listed in data-sharing attributes clauses, except for the cases
9986 // listed below. For these exceptions only, listing a predetermined
9987 // variable in a data-sharing attribute clause is allowed and overrides
9988 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00009989 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009990 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009991 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9992 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +00009993 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009994 continue;
9995 }
9996
Alexey Bataeve3727102018-04-18 15:57:46 +00009997 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009998 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009999 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010000 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010001 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10002 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010003 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010004 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010005 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010006 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010007 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010008 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010009 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010010 continue;
10011 }
10012
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010013 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10014 // A list item cannot appear in both a map clause and a data-sharing
10015 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010016 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010017 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010018 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010019 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010020 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10021 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10022 ConflictKind = WhereFoundClauseKind;
10023 return true;
10024 })) {
10025 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010026 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010027 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010028 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010029 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010030 continue;
10031 }
10032 }
10033
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010034 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10035 // A variable of class type (or array thereof) that appears in a private
10036 // clause requires an accessible, unambiguous default constructor for the
10037 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010038 // Generate helper private variable and initialize it with the default
10039 // value. The address of the original variable is replaced by the address of
10040 // the new private variable in CodeGen. This new variable is not added to
10041 // IdResolver, so the code in the OpenMP region uses original variable for
10042 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010043 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010044 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010045 buildVarDecl(*this, ELoc, Type, D->getName(),
10046 D->hasAttrs() ? &D->getAttrs() : nullptr,
10047 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010048 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010049 if (VDPrivate->isInvalidDecl())
10050 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010051 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010052 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010053
Alexey Bataev90c228f2016-02-08 09:29:13 +000010054 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010055 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010056 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010057 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010058 Vars.push_back((VD || CurContext->isDependentContext())
10059 ? RefExpr->IgnoreParens()
10060 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010061 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010062 }
10063
Alexey Bataeved09d242014-05-28 05:53:51 +000010064 if (Vars.empty())
10065 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010066
Alexey Bataev03b340a2014-10-21 03:16:40 +000010067 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10068 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010069}
10070
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010071namespace {
10072class DiagsUninitializedSeveretyRAII {
10073private:
10074 DiagnosticsEngine &Diags;
10075 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010076 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010077
10078public:
10079 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10080 bool IsIgnored)
10081 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10082 if (!IsIgnored) {
10083 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10084 /*Map*/ diag::Severity::Ignored, Loc);
10085 }
10086 }
10087 ~DiagsUninitializedSeveretyRAII() {
10088 if (!IsIgnored)
10089 Diags.popMappings(SavedLoc);
10090 }
10091};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010092}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010093
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010094OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10095 SourceLocation StartLoc,
10096 SourceLocation LParenLoc,
10097 SourceLocation EndLoc) {
10098 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010099 SmallVector<Expr *, 8> PrivateCopies;
10100 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010101 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010102 bool IsImplicitClause =
10103 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010104 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010105
Alexey Bataeve3727102018-04-18 15:57:46 +000010106 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010107 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010108 SourceLocation ELoc;
10109 SourceRange ERange;
10110 Expr *SimpleRefExpr = RefExpr;
10111 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010112 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010113 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010114 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010115 PrivateCopies.push_back(nullptr);
10116 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010117 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010118 ValueDecl *D = Res.first;
10119 if (!D)
10120 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010121
Alexey Bataev60da77e2016-02-29 05:54:20 +000010122 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010123 QualType Type = D->getType();
10124 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010125
10126 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10127 // A variable that appears in a private clause must not have an incomplete
10128 // type or a reference type.
10129 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010130 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010131 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010132 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010133
10134 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10135 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010136 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010137 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010138 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010139
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010140 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010141 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010142 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010143 DSAStackTy::DSAVarData DVar =
10144 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010145 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010146 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010147 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010148 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10149 // A list item that specifies a given variable may not appear in more
10150 // than one clause on the same directive, except that a variable may be
10151 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010152 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10153 // A list item may appear in a firstprivate or lastprivate clause but not
10154 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010155 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010156 (isOpenMPDistributeDirective(CurrDir) ||
10157 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010158 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010159 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010160 << getOpenMPClauseName(DVar.CKind)
10161 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010162 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010163 continue;
10164 }
10165
10166 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10167 // in a Construct]
10168 // Variables with the predetermined data-sharing attributes may not be
10169 // listed in data-sharing attributes clauses, except for the cases
10170 // listed below. For these exceptions only, listing a predetermined
10171 // variable in a data-sharing attribute clause is allowed and overrides
10172 // the variable's predetermined data-sharing attributes.
10173 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10174 // in a Construct, C/C++, p.2]
10175 // Variables with const-qualified type having no mutable member may be
10176 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010177 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010178 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10179 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010180 << getOpenMPClauseName(DVar.CKind)
10181 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010182 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010183 continue;
10184 }
10185
10186 // OpenMP [2.9.3.4, Restrictions, p.2]
10187 // A list item that is private within a parallel region must not appear
10188 // in a firstprivate clause on a worksharing construct if any of the
10189 // worksharing regions arising from the worksharing construct ever bind
10190 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010191 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10192 // A list item that is private within a teams region must not appear in a
10193 // firstprivate clause on a distribute construct if any of the distribute
10194 // regions arising from the distribute construct ever bind to any of the
10195 // teams regions arising from the teams construct.
10196 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10197 // A list item that appears in a reduction clause of a teams construct
10198 // must not appear in a firstprivate clause on a distribute construct if
10199 // any of the distribute regions arising from the distribute construct
10200 // ever bind to any of the teams regions arising from the teams construct.
10201 if ((isOpenMPWorksharingDirective(CurrDir) ||
10202 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010203 !isOpenMPParallelDirective(CurrDir) &&
10204 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010205 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010206 if (DVar.CKind != OMPC_shared &&
10207 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010208 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010209 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010210 Diag(ELoc, diag::err_omp_required_access)
10211 << getOpenMPClauseName(OMPC_firstprivate)
10212 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010213 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010214 continue;
10215 }
10216 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010217 // OpenMP [2.9.3.4, Restrictions, p.3]
10218 // A list item that appears in a reduction clause of a parallel construct
10219 // must not appear in a firstprivate clause on a worksharing or task
10220 // construct if any of the worksharing or task regions arising from the
10221 // worksharing or task construct ever bind to any of the parallel regions
10222 // arising from the parallel construct.
10223 // OpenMP [2.9.3.4, Restrictions, p.4]
10224 // A list item that appears in a reduction clause in worksharing
10225 // construct must not appear in a firstprivate clause in a task construct
10226 // encountered during execution of any of the worksharing regions arising
10227 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010228 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010229 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010230 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10231 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010232 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010233 isOpenMPWorksharingDirective(K) ||
10234 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010235 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010236 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010237 if (DVar.CKind == OMPC_reduction &&
10238 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010239 isOpenMPWorksharingDirective(DVar.DKind) ||
10240 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010241 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10242 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010243 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010244 continue;
10245 }
10246 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010247
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010248 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10249 // A list item cannot appear in both a map clause and a data-sharing
10250 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010251 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010252 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010253 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010254 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010255 [&ConflictKind](
10256 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10257 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010258 ConflictKind = WhereFoundClauseKind;
10259 return true;
10260 })) {
10261 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010262 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010263 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010264 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010265 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010266 continue;
10267 }
10268 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010269 }
10270
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010271 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010272 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010273 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010274 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10275 << getOpenMPClauseName(OMPC_firstprivate) << Type
10276 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10277 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010278 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010279 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010280 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010281 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010282 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010283 continue;
10284 }
10285
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010286 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010287 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010288 buildVarDecl(*this, ELoc, Type, D->getName(),
10289 D->hasAttrs() ? &D->getAttrs() : nullptr,
10290 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010291 // Generate helper private variable and initialize it with the value of the
10292 // original variable. The address of the original variable is replaced by
10293 // the address of the new private variable in the CodeGen. This new variable
10294 // is not added to IdResolver, so the code in the OpenMP region uses
10295 // original variable for proper diagnostics and variable capturing.
10296 Expr *VDInitRefExpr = nullptr;
10297 // For arrays generate initializer for single element and replace it by the
10298 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010299 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010300 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010301 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010302 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010303 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010304 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010305 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10306 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010307 InitializedEntity Entity =
10308 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010309 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10310
10311 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10312 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10313 if (Result.isInvalid())
10314 VDPrivate->setInvalidDecl();
10315 else
10316 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010317 // Remove temp variable declaration.
10318 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010319 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010320 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10321 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010322 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10323 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010324 AddInitializerToDecl(VDPrivate,
10325 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010326 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010327 }
10328 if (VDPrivate->isInvalidDecl()) {
10329 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010330 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010331 diag::note_omp_task_predetermined_firstprivate_here);
10332 }
10333 continue;
10334 }
10335 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010336 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010337 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10338 RefExpr->getExprLoc());
10339 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010340 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010341 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010342 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010343 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010344 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010345 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010346 ExprCaptures.push_back(Ref->getDecl());
10347 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010348 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010349 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010350 Vars.push_back((VD || CurContext->isDependentContext())
10351 ? RefExpr->IgnoreParens()
10352 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010353 PrivateCopies.push_back(VDPrivateRefExpr);
10354 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010355 }
10356
Alexey Bataeved09d242014-05-28 05:53:51 +000010357 if (Vars.empty())
10358 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010359
10360 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010361 Vars, PrivateCopies, Inits,
10362 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010363}
10364
Alexander Musman1bb328c2014-06-04 13:06:39 +000010365OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10366 SourceLocation StartLoc,
10367 SourceLocation LParenLoc,
10368 SourceLocation EndLoc) {
10369 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010370 SmallVector<Expr *, 8> SrcExprs;
10371 SmallVector<Expr *, 8> DstExprs;
10372 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010373 SmallVector<Decl *, 4> ExprCaptures;
10374 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010375 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010376 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010377 SourceLocation ELoc;
10378 SourceRange ERange;
10379 Expr *SimpleRefExpr = RefExpr;
10380 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010381 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010382 // It will be analyzed later.
10383 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010384 SrcExprs.push_back(nullptr);
10385 DstExprs.push_back(nullptr);
10386 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010387 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010388 ValueDecl *D = Res.first;
10389 if (!D)
10390 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010391
Alexey Bataev74caaf22016-02-20 04:09:36 +000010392 QualType Type = D->getType();
10393 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010394
10395 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10396 // A variable that appears in a lastprivate clause must not have an
10397 // incomplete type or a reference type.
10398 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010399 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010400 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010401 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010402
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010403 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10404 // A variable that is privatized must not have a const-qualified type
10405 // unless it is of class type with a mutable member. This restriction does
10406 // not apply to the firstprivate clause.
10407 //
10408 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10409 // A variable that appears in a lastprivate clause must not have a
10410 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010411 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010412 continue;
10413
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010414 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010415 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10416 // in a Construct]
10417 // Variables with the predetermined data-sharing attributes may not be
10418 // listed in data-sharing attributes clauses, except for the cases
10419 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010420 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10421 // A list item may appear in a firstprivate or lastprivate clause but not
10422 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010423 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010424 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010425 (isOpenMPDistributeDirective(CurrDir) ||
10426 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010427 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10428 Diag(ELoc, diag::err_omp_wrong_dsa)
10429 << getOpenMPClauseName(DVar.CKind)
10430 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010431 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010432 continue;
10433 }
10434
Alexey Bataevf29276e2014-06-18 04:14:57 +000010435 // OpenMP [2.14.3.5, Restrictions, p.2]
10436 // A list item that is private within a parallel region, or that appears in
10437 // the reduction clause of a parallel construct, must not appear in a
10438 // lastprivate clause on a worksharing construct if any of the corresponding
10439 // worksharing regions ever binds to any of the corresponding parallel
10440 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010441 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010442 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010443 !isOpenMPParallelDirective(CurrDir) &&
10444 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010445 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010446 if (DVar.CKind != OMPC_shared) {
10447 Diag(ELoc, diag::err_omp_required_access)
10448 << getOpenMPClauseName(OMPC_lastprivate)
10449 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010450 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010451 continue;
10452 }
10453 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010454
Alexander Musman1bb328c2014-06-04 13:06:39 +000010455 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010456 // A variable of class type (or array thereof) that appears in a
10457 // lastprivate clause requires an accessible, unambiguous default
10458 // constructor for the class type, unless the list item is also specified
10459 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010460 // A variable of class type (or array thereof) that appears in a
10461 // lastprivate clause requires an accessible, unambiguous copy assignment
10462 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010463 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010464 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10465 Type.getUnqualifiedType(), ".lastprivate.src",
10466 D->hasAttrs() ? &D->getAttrs() : nullptr);
10467 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010468 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010469 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010470 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010471 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010472 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010473 // For arrays generate assignment operation for single element and replace
10474 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010475 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10476 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010477 if (AssignmentOp.isInvalid())
10478 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010479 AssignmentOp =
10480 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010481 if (AssignmentOp.isInvalid())
10482 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010483
Alexey Bataev74caaf22016-02-20 04:09:36 +000010484 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010485 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010486 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010487 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010488 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010489 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010490 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010491 ExprCaptures.push_back(Ref->getDecl());
10492 }
10493 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010494 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010495 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010496 ExprResult RefRes = DefaultLvalueConversion(Ref);
10497 if (!RefRes.isUsable())
10498 continue;
10499 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010500 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10501 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010502 if (!PostUpdateRes.isUsable())
10503 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010504 ExprPostUpdates.push_back(
10505 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010506 }
10507 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010508 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010509 Vars.push_back((VD || CurContext->isDependentContext())
10510 ? RefExpr->IgnoreParens()
10511 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010512 SrcExprs.push_back(PseudoSrcExpr);
10513 DstExprs.push_back(PseudoDstExpr);
10514 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010515 }
10516
10517 if (Vars.empty())
10518 return nullptr;
10519
10520 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010521 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010522 buildPreInits(Context, ExprCaptures),
10523 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010524}
10525
Alexey Bataev758e55e2013-09-06 18:03:48 +000010526OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10527 SourceLocation StartLoc,
10528 SourceLocation LParenLoc,
10529 SourceLocation EndLoc) {
10530 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010531 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010532 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010533 SourceLocation ELoc;
10534 SourceRange ERange;
10535 Expr *SimpleRefExpr = RefExpr;
10536 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010537 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010538 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010539 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010540 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010541 ValueDecl *D = Res.first;
10542 if (!D)
10543 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010544
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010545 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010546 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10547 // in a Construct]
10548 // Variables with the predetermined data-sharing attributes may not be
10549 // listed in data-sharing attributes clauses, except for the cases
10550 // listed below. For these exceptions only, listing a predetermined
10551 // variable in a data-sharing attribute clause is allowed and overrides
10552 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010553 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010554 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10555 DVar.RefExpr) {
10556 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10557 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010558 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010559 continue;
10560 }
10561
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010562 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010563 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010564 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010565 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010566 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10567 ? RefExpr->IgnoreParens()
10568 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010569 }
10570
Alexey Bataeved09d242014-05-28 05:53:51 +000010571 if (Vars.empty())
10572 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010573
10574 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10575}
10576
Alexey Bataevc5e02582014-06-16 07:08:35 +000010577namespace {
10578class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10579 DSAStackTy *Stack;
10580
10581public:
10582 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010583 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10584 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010585 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10586 return false;
10587 if (DVar.CKind != OMPC_unknown)
10588 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010589 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010590 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010591 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010592 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010593 }
10594 return false;
10595 }
10596 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010597 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010598 if (Child && Visit(Child))
10599 return true;
10600 }
10601 return false;
10602 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010603 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010604};
Alexey Bataev23b69422014-06-18 07:08:49 +000010605} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010606
Alexey Bataev60da77e2016-02-29 05:54:20 +000010607namespace {
10608// Transform MemberExpression for specified FieldDecl of current class to
10609// DeclRefExpr to specified OMPCapturedExprDecl.
10610class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10611 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010612 ValueDecl *Field = nullptr;
10613 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010614
10615public:
10616 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10617 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10618
10619 ExprResult TransformMemberExpr(MemberExpr *E) {
10620 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10621 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010622 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010623 return CapturedExpr;
10624 }
10625 return BaseTransform::TransformMemberExpr(E);
10626 }
10627 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10628};
10629} // namespace
10630
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010631template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010632static T filterLookupForUDReductionAndMapper(
10633 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010634 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010635 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010636 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010637 return Res;
10638 }
10639 }
10640 return T();
10641}
10642
Alexey Bataev43b90b72018-09-12 16:31:59 +000010643static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10644 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10645
10646 for (auto RD : D->redecls()) {
10647 // Don't bother with extra checks if we already know this one isn't visible.
10648 if (RD == D)
10649 continue;
10650
10651 auto ND = cast<NamedDecl>(RD);
10652 if (LookupResult::isVisible(SemaRef, ND))
10653 return ND;
10654 }
10655
10656 return nullptr;
10657}
10658
10659static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010660argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010661 SourceLocation Loc, QualType Ty,
10662 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10663 // Find all of the associated namespaces and classes based on the
10664 // arguments we have.
10665 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10666 Sema::AssociatedClassSet AssociatedClasses;
10667 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10668 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10669 AssociatedClasses);
10670
10671 // C++ [basic.lookup.argdep]p3:
10672 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10673 // and let Y be the lookup set produced by argument dependent
10674 // lookup (defined as follows). If X contains [...] then Y is
10675 // empty. Otherwise Y is the set of declarations found in the
10676 // namespaces associated with the argument types as described
10677 // below. The set of declarations found by the lookup of the name
10678 // is the union of X and Y.
10679 //
10680 // Here, we compute Y and add its members to the overloaded
10681 // candidate set.
10682 for (auto *NS : AssociatedNamespaces) {
10683 // When considering an associated namespace, the lookup is the
10684 // same as the lookup performed when the associated namespace is
10685 // used as a qualifier (3.4.3.2) except that:
10686 //
10687 // -- Any using-directives in the associated namespace are
10688 // ignored.
10689 //
10690 // -- Any namespace-scope friend functions declared in
10691 // associated classes are visible within their respective
10692 // namespaces even if they are not visible during an ordinary
10693 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000010694 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000010695 for (auto *D : R) {
10696 auto *Underlying = D;
10697 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10698 Underlying = USD->getTargetDecl();
10699
Michael Kruse4304e9d2019-02-19 16:38:20 +000010700 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
10701 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000010702 continue;
10703
10704 if (!SemaRef.isVisible(D)) {
10705 D = findAcceptableDecl(SemaRef, D);
10706 if (!D)
10707 continue;
10708 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10709 Underlying = USD->getTargetDecl();
10710 }
10711 Lookups.emplace_back();
10712 Lookups.back().addDecl(Underlying);
10713 }
10714 }
10715}
10716
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010717static ExprResult
10718buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10719 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10720 const DeclarationNameInfo &ReductionId, QualType Ty,
10721 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10722 if (ReductionIdScopeSpec.isInvalid())
10723 return ExprError();
10724 SmallVector<UnresolvedSet<8>, 4> Lookups;
10725 if (S) {
10726 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10727 Lookup.suppressDiagnostics();
10728 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010729 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010730 do {
10731 S = S->getParent();
10732 } while (S && !S->isDeclScope(D));
10733 if (S)
10734 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000010735 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010736 Lookups.back().append(Lookup.begin(), Lookup.end());
10737 Lookup.clear();
10738 }
10739 } else if (auto *ULE =
10740 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10741 Lookups.push_back(UnresolvedSet<8>());
10742 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010743 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010744 if (D == PrevD)
10745 Lookups.push_back(UnresolvedSet<8>());
10746 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10747 Lookups.back().addDecl(DRD);
10748 PrevD = D;
10749 }
10750 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000010751 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10752 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010753 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000010754 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010755 return !D->isInvalidDecl() &&
10756 (D->getType()->isDependentType() ||
10757 D->getType()->isInstantiationDependentType() ||
10758 D->getType()->containsUnexpandedParameterPack());
10759 })) {
10760 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000010761 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000010762 if (Set.empty())
10763 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010764 ResSet.append(Set.begin(), Set.end());
10765 // The last item marks the end of all declarations at the specified scope.
10766 ResSet.addDecl(Set[Set.size() - 1]);
10767 }
10768 return UnresolvedLookupExpr::Create(
10769 SemaRef.Context, /*NamingClass=*/nullptr,
10770 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10771 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10772 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000010773 // Lookup inside the classes.
10774 // C++ [over.match.oper]p3:
10775 // For a unary operator @ with an operand of a type whose
10776 // cv-unqualified version is T1, and for a binary operator @ with
10777 // a left operand of a type whose cv-unqualified version is T1 and
10778 // a right operand of a type whose cv-unqualified version is T2,
10779 // three sets of candidate functions, designated member
10780 // candidates, non-member candidates and built-in candidates, are
10781 // constructed as follows:
10782 // -- If T1 is a complete class type or a class currently being
10783 // defined, the set of member candidates is the result of the
10784 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10785 // the set of member candidates is empty.
10786 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10787 Lookup.suppressDiagnostics();
10788 if (const auto *TyRec = Ty->getAs<RecordType>()) {
10789 // Complete the type if it can be completed.
10790 // If the type is neither complete nor being defined, bail out now.
10791 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10792 TyRec->getDecl()->getDefinition()) {
10793 Lookup.clear();
10794 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10795 if (Lookup.empty()) {
10796 Lookups.emplace_back();
10797 Lookups.back().append(Lookup.begin(), Lookup.end());
10798 }
10799 }
10800 }
10801 // Perform ADL.
10802 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010803 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010804 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10805 if (!D->isInvalidDecl() &&
10806 SemaRef.Context.hasSameType(D->getType(), Ty))
10807 return D;
10808 return nullptr;
10809 }))
James Y Knightb92d2902019-02-05 16:05:50 +000010810 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
10811 VK_LValue, Loc);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010812 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010813 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10814 if (!D->isInvalidDecl() &&
10815 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10816 !Ty.isMoreQualifiedThan(D->getType()))
10817 return D;
10818 return nullptr;
10819 })) {
10820 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10821 /*DetectVirtual=*/false);
10822 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10823 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10824 VD->getType().getUnqualifiedType()))) {
10825 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10826 /*DiagID=*/0) !=
10827 Sema::AR_inaccessible) {
10828 SemaRef.BuildBasePathArray(Paths, BasePath);
James Y Knightb92d2902019-02-05 16:05:50 +000010829 return SemaRef.BuildDeclRefExpr(
10830 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010831 }
10832 }
10833 }
10834 }
10835 if (ReductionIdScopeSpec.isSet()) {
10836 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10837 return ExprError();
10838 }
10839 return ExprEmpty();
10840}
10841
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010842namespace {
10843/// Data for the reduction-based clauses.
10844struct ReductionData {
10845 /// List of original reduction items.
10846 SmallVector<Expr *, 8> Vars;
10847 /// List of private copies of the reduction items.
10848 SmallVector<Expr *, 8> Privates;
10849 /// LHS expressions for the reduction_op expressions.
10850 SmallVector<Expr *, 8> LHSs;
10851 /// RHS expressions for the reduction_op expressions.
10852 SmallVector<Expr *, 8> RHSs;
10853 /// Reduction operation expression.
10854 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010855 /// Taskgroup descriptors for the corresponding reduction items in
10856 /// in_reduction clauses.
10857 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010858 /// List of captures for clause.
10859 SmallVector<Decl *, 4> ExprCaptures;
10860 /// List of postupdate expressions.
10861 SmallVector<Expr *, 4> ExprPostUpdates;
10862 ReductionData() = delete;
10863 /// Reserves required memory for the reduction data.
10864 ReductionData(unsigned Size) {
10865 Vars.reserve(Size);
10866 Privates.reserve(Size);
10867 LHSs.reserve(Size);
10868 RHSs.reserve(Size);
10869 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010870 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010871 ExprCaptures.reserve(Size);
10872 ExprPostUpdates.reserve(Size);
10873 }
10874 /// Stores reduction item and reduction operation only (required for dependent
10875 /// reduction item).
10876 void push(Expr *Item, Expr *ReductionOp) {
10877 Vars.emplace_back(Item);
10878 Privates.emplace_back(nullptr);
10879 LHSs.emplace_back(nullptr);
10880 RHSs.emplace_back(nullptr);
10881 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010882 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010883 }
10884 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010885 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10886 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010887 Vars.emplace_back(Item);
10888 Privates.emplace_back(Private);
10889 LHSs.emplace_back(LHS);
10890 RHSs.emplace_back(RHS);
10891 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010892 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010893 }
10894};
10895} // namespace
10896
Alexey Bataeve3727102018-04-18 15:57:46 +000010897static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010898 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10899 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10900 const Expr *Length = OASE->getLength();
10901 if (Length == nullptr) {
10902 // For array sections of the form [1:] or [:], we would need to analyze
10903 // the lower bound...
10904 if (OASE->getColonLoc().isValid())
10905 return false;
10906
10907 // This is an array subscript which has implicit length 1!
10908 SingleElement = true;
10909 ArraySizes.push_back(llvm::APSInt::get(1));
10910 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010911 Expr::EvalResult Result;
10912 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010913 return false;
10914
Fangrui Song407659a2018-11-30 23:41:18 +000010915 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010916 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10917 ArraySizes.push_back(ConstantLengthValue);
10918 }
10919
10920 // Get the base of this array section and walk up from there.
10921 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10922
10923 // We require length = 1 for all array sections except the right-most to
10924 // guarantee that the memory region is contiguous and has no holes in it.
10925 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10926 Length = TempOASE->getLength();
10927 if (Length == nullptr) {
10928 // For array sections of the form [1:] or [:], we would need to analyze
10929 // the lower bound...
10930 if (OASE->getColonLoc().isValid())
10931 return false;
10932
10933 // This is an array subscript which has implicit length 1!
10934 ArraySizes.push_back(llvm::APSInt::get(1));
10935 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010936 Expr::EvalResult Result;
10937 if (!Length->EvaluateAsInt(Result, Context))
10938 return false;
10939
10940 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10941 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010942 return false;
10943
10944 ArraySizes.push_back(ConstantLengthValue);
10945 }
10946 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10947 }
10948
10949 // If we have a single element, we don't need to add the implicit lengths.
10950 if (!SingleElement) {
10951 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10952 // Has implicit length 1!
10953 ArraySizes.push_back(llvm::APSInt::get(1));
10954 Base = TempASE->getBase()->IgnoreParenImpCasts();
10955 }
10956 }
10957
10958 // This array section can be privatized as a single value or as a constant
10959 // sized array.
10960 return true;
10961}
10962
Alexey Bataeve3727102018-04-18 15:57:46 +000010963static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010964 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10965 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10966 SourceLocation ColonLoc, SourceLocation EndLoc,
10967 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010968 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010969 DeclarationName DN = ReductionId.getName();
10970 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010971 BinaryOperatorKind BOK = BO_Comma;
10972
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010973 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010974 // OpenMP [2.14.3.6, reduction clause]
10975 // C
10976 // reduction-identifier is either an identifier or one of the following
10977 // operators: +, -, *, &, |, ^, && and ||
10978 // C++
10979 // reduction-identifier is either an id-expression or one of the following
10980 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010981 switch (OOK) {
10982 case OO_Plus:
10983 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010984 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010985 break;
10986 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010987 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010988 break;
10989 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010990 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010991 break;
10992 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010993 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010994 break;
10995 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010996 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010997 break;
10998 case OO_AmpAmp:
10999 BOK = BO_LAnd;
11000 break;
11001 case OO_PipePipe:
11002 BOK = BO_LOr;
11003 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011004 case OO_New:
11005 case OO_Delete:
11006 case OO_Array_New:
11007 case OO_Array_Delete:
11008 case OO_Slash:
11009 case OO_Percent:
11010 case OO_Tilde:
11011 case OO_Exclaim:
11012 case OO_Equal:
11013 case OO_Less:
11014 case OO_Greater:
11015 case OO_LessEqual:
11016 case OO_GreaterEqual:
11017 case OO_PlusEqual:
11018 case OO_MinusEqual:
11019 case OO_StarEqual:
11020 case OO_SlashEqual:
11021 case OO_PercentEqual:
11022 case OO_CaretEqual:
11023 case OO_AmpEqual:
11024 case OO_PipeEqual:
11025 case OO_LessLess:
11026 case OO_GreaterGreater:
11027 case OO_LessLessEqual:
11028 case OO_GreaterGreaterEqual:
11029 case OO_EqualEqual:
11030 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011031 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011032 case OO_PlusPlus:
11033 case OO_MinusMinus:
11034 case OO_Comma:
11035 case OO_ArrowStar:
11036 case OO_Arrow:
11037 case OO_Call:
11038 case OO_Subscript:
11039 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011040 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011041 case NUM_OVERLOADED_OPERATORS:
11042 llvm_unreachable("Unexpected reduction identifier");
11043 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011044 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011045 if (II->isStr("max"))
11046 BOK = BO_GT;
11047 else if (II->isStr("min"))
11048 BOK = BO_LT;
11049 }
11050 break;
11051 }
11052 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011053 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011054 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011055 else
11056 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011057 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011058
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011059 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11060 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011061 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011062 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011063 // OpenMP [2.1, C/C++]
11064 // A list item is a variable or array section, subject to the restrictions
11065 // specified in Section 2.4 on page 42 and in each of the sections
11066 // describing clauses and directives for which a list appears.
11067 // OpenMP [2.14.3.3, Restrictions, p.1]
11068 // A variable that is part of another variable (as an array or
11069 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011070 if (!FirstIter && IR != ER)
11071 ++IR;
11072 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011073 SourceLocation ELoc;
11074 SourceRange ERange;
11075 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011076 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011077 /*AllowArraySection=*/true);
11078 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011079 // Try to find 'declare reduction' corresponding construct before using
11080 // builtin/overloaded operators.
11081 QualType Type = Context.DependentTy;
11082 CXXCastPath BasePath;
11083 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011084 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011085 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011086 Expr *ReductionOp = nullptr;
11087 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011088 (DeclareReductionRef.isUnset() ||
11089 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011090 ReductionOp = DeclareReductionRef.get();
11091 // It will be analyzed later.
11092 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011093 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011094 ValueDecl *D = Res.first;
11095 if (!D)
11096 continue;
11097
Alexey Bataev88202be2017-07-27 13:20:36 +000011098 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011099 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011100 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11101 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011102 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011103 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011104 } else if (OASE) {
11105 QualType BaseType =
11106 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11107 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011108 Type = ATy->getElementType();
11109 else
11110 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011111 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011112 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011113 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011114 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011115 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011116
Alexey Bataevc5e02582014-06-16 07:08:35 +000011117 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11118 // A variable that appears in a private clause must not have an incomplete
11119 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011120 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011121 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011122 continue;
11123 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011124 // A list item that appears in a reduction clause must not be
11125 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011126 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11127 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011128 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011129
11130 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011131 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11132 // If a list-item is a reference type then it must bind to the same object
11133 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011134 if (!ASE && !OASE) {
11135 if (VD) {
11136 VarDecl *VDDef = VD->getDefinition();
11137 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11138 DSARefChecker Check(Stack);
11139 if (Check.Visit(VDDef->getInit())) {
11140 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11141 << getOpenMPClauseName(ClauseKind) << ERange;
11142 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11143 continue;
11144 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011145 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011146 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011147
Alexey Bataevbc529672018-09-28 19:33:14 +000011148 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11149 // in a Construct]
11150 // Variables with the predetermined data-sharing attributes may not be
11151 // listed in data-sharing attributes clauses, except for the cases
11152 // listed below. For these exceptions only, listing a predetermined
11153 // variable in a data-sharing attribute clause is allowed and overrides
11154 // the variable's predetermined data-sharing attributes.
11155 // OpenMP [2.14.3.6, Restrictions, p.3]
11156 // Any number of reduction clauses can be specified on the directive,
11157 // but a list item can appear only once in the reduction clauses for that
11158 // directive.
11159 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11160 if (DVar.CKind == OMPC_reduction) {
11161 S.Diag(ELoc, diag::err_omp_once_referenced)
11162 << getOpenMPClauseName(ClauseKind);
11163 if (DVar.RefExpr)
11164 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11165 continue;
11166 }
11167 if (DVar.CKind != OMPC_unknown) {
11168 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11169 << getOpenMPClauseName(DVar.CKind)
11170 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011171 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011172 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011173 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011174
11175 // OpenMP [2.14.3.6, Restrictions, p.1]
11176 // A list item that appears in a reduction clause of a worksharing
11177 // construct must be shared in the parallel regions to which any of the
11178 // worksharing regions arising from the worksharing construct bind.
11179 if (isOpenMPWorksharingDirective(CurrDir) &&
11180 !isOpenMPParallelDirective(CurrDir) &&
11181 !isOpenMPTeamsDirective(CurrDir)) {
11182 DVar = Stack->getImplicitDSA(D, true);
11183 if (DVar.CKind != OMPC_shared) {
11184 S.Diag(ELoc, diag::err_omp_required_access)
11185 << getOpenMPClauseName(OMPC_reduction)
11186 << getOpenMPClauseName(OMPC_shared);
11187 reportOriginalDsa(S, Stack, D, DVar);
11188 continue;
11189 }
11190 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011191 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011192
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011193 // Try to find 'declare reduction' corresponding construct before using
11194 // builtin/overloaded operators.
11195 CXXCastPath BasePath;
11196 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011197 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011198 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11199 if (DeclareReductionRef.isInvalid())
11200 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011201 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011202 (DeclareReductionRef.isUnset() ||
11203 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011204 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011205 continue;
11206 }
11207 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11208 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011209 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011210 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011211 << Type << ReductionIdRange;
11212 continue;
11213 }
11214
11215 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11216 // The type of a list item that appears in a reduction clause must be valid
11217 // for the reduction-identifier. For a max or min reduction in C, the type
11218 // of the list item must be an allowed arithmetic data type: char, int,
11219 // float, double, or _Bool, possibly modified with long, short, signed, or
11220 // unsigned. For a max or min reduction in C++, the type of the list item
11221 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11222 // double, or bool, possibly modified with long, short, signed, or unsigned.
11223 if (DeclareReductionRef.isUnset()) {
11224 if ((BOK == BO_GT || BOK == BO_LT) &&
11225 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011226 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11227 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011228 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011229 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011230 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11231 VarDecl::DeclarationOnly;
11232 S.Diag(D->getLocation(),
11233 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011234 << D;
11235 }
11236 continue;
11237 }
11238 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011239 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011240 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11241 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011242 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011243 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11244 VarDecl::DeclarationOnly;
11245 S.Diag(D->getLocation(),
11246 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011247 << D;
11248 }
11249 continue;
11250 }
11251 }
11252
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011253 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011254 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11255 D->hasAttrs() ? &D->getAttrs() : nullptr);
11256 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11257 D->hasAttrs() ? &D->getAttrs() : nullptr);
11258 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011259
11260 // Try if we can determine constant lengths for all array sections and avoid
11261 // the VLA.
11262 bool ConstantLengthOASE = false;
11263 if (OASE) {
11264 bool SingleElement;
11265 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011266 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011267 Context, OASE, SingleElement, ArraySizes);
11268
11269 // If we don't have a single element, we must emit a constant array type.
11270 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011271 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011272 PrivateTy = Context.getConstantArrayType(
11273 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011274 }
11275 }
11276
11277 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011278 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011279 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011280 if (!Context.getTargetInfo().isVLASupported() &&
11281 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11282 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11283 S.Diag(ELoc, diag::note_vla_unsupported);
11284 continue;
11285 }
David Majnemer9d168222016-08-05 17:44:54 +000011286 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011287 // Create pseudo array type for private copy. The size for this array will
11288 // be generated during codegen.
11289 // For array subscripts or single variables Private Ty is the same as Type
11290 // (type of the variable or single array element).
11291 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011292 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011293 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011294 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011295 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011296 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011297 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011298 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011299 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011300 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011301 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11302 D->hasAttrs() ? &D->getAttrs() : nullptr,
11303 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011304 // Add initializer for private variable.
11305 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011306 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11307 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011308 if (DeclareReductionRef.isUsable()) {
11309 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11310 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11311 if (DRD->getInitializer()) {
11312 Init = DRDRef;
11313 RHSVD->setInit(DRDRef);
11314 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011315 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011316 } else {
11317 switch (BOK) {
11318 case BO_Add:
11319 case BO_Xor:
11320 case BO_Or:
11321 case BO_LOr:
11322 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11323 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011324 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011325 break;
11326 case BO_Mul:
11327 case BO_LAnd:
11328 if (Type->isScalarType() || Type->isAnyComplexType()) {
11329 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011330 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011331 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011332 break;
11333 case BO_And: {
11334 // '&' reduction op - initializer is '~0'.
11335 QualType OrigType = Type;
11336 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11337 Type = ComplexTy->getElementType();
11338 if (Type->isRealFloatingType()) {
11339 llvm::APFloat InitValue =
11340 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11341 /*isIEEE=*/true);
11342 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11343 Type, ELoc);
11344 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011345 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011346 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11347 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11348 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11349 }
11350 if (Init && OrigType->isAnyComplexType()) {
11351 // Init = 0xFFFF + 0xFFFFi;
11352 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011353 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011354 }
11355 Type = OrigType;
11356 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011357 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011358 case BO_LT:
11359 case BO_GT: {
11360 // 'min' reduction op - initializer is 'Largest representable number in
11361 // the reduction list item type'.
11362 // 'max' reduction op - initializer is 'Least representable number in
11363 // the reduction list item type'.
11364 if (Type->isIntegerType() || Type->isPointerType()) {
11365 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011366 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011367 QualType IntTy =
11368 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11369 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011370 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11371 : llvm::APInt::getMinValue(Size)
11372 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11373 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011374 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11375 if (Type->isPointerType()) {
11376 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011377 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011378 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011379 if (CastExpr.isInvalid())
11380 continue;
11381 Init = CastExpr.get();
11382 }
11383 } else if (Type->isRealFloatingType()) {
11384 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11385 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11386 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11387 Type, ELoc);
11388 }
11389 break;
11390 }
11391 case BO_PtrMemD:
11392 case BO_PtrMemI:
11393 case BO_MulAssign:
11394 case BO_Div:
11395 case BO_Rem:
11396 case BO_Sub:
11397 case BO_Shl:
11398 case BO_Shr:
11399 case BO_LE:
11400 case BO_GE:
11401 case BO_EQ:
11402 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011403 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011404 case BO_AndAssign:
11405 case BO_XorAssign:
11406 case BO_OrAssign:
11407 case BO_Assign:
11408 case BO_AddAssign:
11409 case BO_SubAssign:
11410 case BO_DivAssign:
11411 case BO_RemAssign:
11412 case BO_ShlAssign:
11413 case BO_ShrAssign:
11414 case BO_Comma:
11415 llvm_unreachable("Unexpected reduction operation");
11416 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011417 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011418 if (Init && DeclareReductionRef.isUnset())
11419 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11420 else if (!Init)
11421 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011422 if (RHSVD->isInvalidDecl())
11423 continue;
11424 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011425 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11426 << Type << ReductionIdRange;
11427 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11428 VarDecl::DeclarationOnly;
11429 S.Diag(D->getLocation(),
11430 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011431 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011432 continue;
11433 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011434 // Store initializer for single element in private copy. Will be used during
11435 // codegen.
11436 PrivateVD->setInit(RHSVD->getInit());
11437 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011438 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011439 ExprResult ReductionOp;
11440 if (DeclareReductionRef.isUsable()) {
11441 QualType RedTy = DeclareReductionRef.get()->getType();
11442 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011443 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11444 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011445 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011446 LHS = S.DefaultLvalueConversion(LHS.get());
11447 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011448 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11449 CK_UncheckedDerivedToBase, LHS.get(),
11450 &BasePath, LHS.get()->getValueKind());
11451 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11452 CK_UncheckedDerivedToBase, RHS.get(),
11453 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011454 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011455 FunctionProtoType::ExtProtoInfo EPI;
11456 QualType Params[] = {PtrRedTy, PtrRedTy};
11457 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11458 auto *OVE = new (Context) OpaqueValueExpr(
11459 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011460 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011461 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011462 ReductionOp =
11463 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011464 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011465 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011466 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011467 if (ReductionOp.isUsable()) {
11468 if (BOK != BO_LT && BOK != BO_GT) {
11469 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011470 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011471 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011472 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011473 auto *ConditionalOp = new (Context)
11474 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11475 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011476 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011477 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011478 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011479 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011480 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011481 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11482 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011483 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011484 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011485 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011486 }
11487
Alexey Bataevfa312f32017-07-21 18:48:21 +000011488 // OpenMP [2.15.4.6, Restrictions, p.2]
11489 // A list item that appears in an in_reduction clause of a task construct
11490 // must appear in a task_reduction clause of a construct associated with a
11491 // taskgroup region that includes the participating task in its taskgroup
11492 // set. The construct associated with the innermost region that meets this
11493 // condition must specify the same reduction-identifier as the in_reduction
11494 // clause.
11495 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011496 SourceRange ParentSR;
11497 BinaryOperatorKind ParentBOK;
11498 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011499 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011500 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011501 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11502 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011503 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011504 Stack->getTopMostTaskgroupReductionData(
11505 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011506 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11507 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11508 if (!IsParentBOK && !IsParentReductionOp) {
11509 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11510 continue;
11511 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011512 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11513 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11514 IsParentReductionOp) {
11515 bool EmitError = true;
11516 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11517 llvm::FoldingSetNodeID RedId, ParentRedId;
11518 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11519 DeclareReductionRef.get()->Profile(RedId, Context,
11520 /*Canonical=*/true);
11521 EmitError = RedId != ParentRedId;
11522 }
11523 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011524 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011525 diag::err_omp_reduction_identifier_mismatch)
11526 << ReductionIdRange << RefExpr->getSourceRange();
11527 S.Diag(ParentSR.getBegin(),
11528 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011529 << ParentSR
11530 << (IsParentBOK ? ParentBOKDSA.RefExpr
11531 : ParentReductionOpDSA.RefExpr)
11532 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011533 continue;
11534 }
11535 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011536 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11537 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011538 }
11539
Alexey Bataev60da77e2016-02-29 05:54:20 +000011540 DeclRefExpr *Ref = nullptr;
11541 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011542 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011543 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011544 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011545 VarsExpr =
11546 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11547 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011548 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011549 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011550 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011551 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011552 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011553 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011554 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011555 if (!RefRes.isUsable())
11556 continue;
11557 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011558 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11559 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011560 if (!PostUpdateRes.isUsable())
11561 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011562 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11563 Stack->getCurrentDirective() == OMPD_taskgroup) {
11564 S.Diag(RefExpr->getExprLoc(),
11565 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011566 << RefExpr->getSourceRange();
11567 continue;
11568 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011569 RD.ExprPostUpdates.emplace_back(
11570 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011571 }
11572 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011573 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011574 // All reduction items are still marked as reduction (to do not increase
11575 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011576 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011577 if (CurrDir == OMPD_taskgroup) {
11578 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011579 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11580 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011581 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011582 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011583 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011584 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11585 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011586 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011587 return RD.Vars.empty();
11588}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011589
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011590OMPClause *Sema::ActOnOpenMPReductionClause(
11591 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11592 SourceLocation ColonLoc, SourceLocation EndLoc,
11593 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11594 ArrayRef<Expr *> UnresolvedReductions) {
11595 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011596 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011597 StartLoc, LParenLoc, ColonLoc, EndLoc,
11598 ReductionIdScopeSpec, ReductionId,
11599 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011600 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011601
Alexey Bataevc5e02582014-06-16 07:08:35 +000011602 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011603 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11604 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11605 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11606 buildPreInits(Context, RD.ExprCaptures),
11607 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011608}
11609
Alexey Bataev169d96a2017-07-18 20:17:46 +000011610OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11611 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11612 SourceLocation ColonLoc, SourceLocation EndLoc,
11613 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11614 ArrayRef<Expr *> UnresolvedReductions) {
11615 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011616 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11617 StartLoc, LParenLoc, ColonLoc, EndLoc,
11618 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011619 UnresolvedReductions, RD))
11620 return nullptr;
11621
11622 return OMPTaskReductionClause::Create(
11623 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11624 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11625 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11626 buildPreInits(Context, RD.ExprCaptures),
11627 buildPostUpdate(*this, RD.ExprPostUpdates));
11628}
11629
Alexey Bataevfa312f32017-07-21 18:48:21 +000011630OMPClause *Sema::ActOnOpenMPInReductionClause(
11631 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11632 SourceLocation ColonLoc, SourceLocation EndLoc,
11633 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11634 ArrayRef<Expr *> UnresolvedReductions) {
11635 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011636 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011637 StartLoc, LParenLoc, ColonLoc, EndLoc,
11638 ReductionIdScopeSpec, ReductionId,
11639 UnresolvedReductions, RD))
11640 return nullptr;
11641
11642 return OMPInReductionClause::Create(
11643 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11644 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011645 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011646 buildPreInits(Context, RD.ExprCaptures),
11647 buildPostUpdate(*this, RD.ExprPostUpdates));
11648}
11649
Alexey Bataevecba70f2016-04-12 11:02:11 +000011650bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11651 SourceLocation LinLoc) {
11652 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11653 LinKind == OMPC_LINEAR_unknown) {
11654 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11655 return true;
11656 }
11657 return false;
11658}
11659
Alexey Bataeve3727102018-04-18 15:57:46 +000011660bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011661 OpenMPLinearClauseKind LinKind,
11662 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011663 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011664 // A variable must not have an incomplete type or a reference type.
11665 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11666 return true;
11667 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11668 !Type->isReferenceType()) {
11669 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11670 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11671 return true;
11672 }
11673 Type = Type.getNonReferenceType();
11674
Joel E. Dennybae586f2019-01-04 22:12:13 +000011675 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11676 // A variable that is privatized must not have a const-qualified type
11677 // unless it is of class type with a mutable member. This restriction does
11678 // not apply to the firstprivate clause.
11679 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011680 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011681
11682 // A list item must be of integral or pointer type.
11683 Type = Type.getUnqualifiedType().getCanonicalType();
11684 const auto *Ty = Type.getTypePtrOrNull();
11685 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11686 !Ty->isPointerType())) {
11687 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11688 if (D) {
11689 bool IsDecl =
11690 !VD ||
11691 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11692 Diag(D->getLocation(),
11693 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11694 << D;
11695 }
11696 return true;
11697 }
11698 return false;
11699}
11700
Alexey Bataev182227b2015-08-20 10:54:39 +000011701OMPClause *Sema::ActOnOpenMPLinearClause(
11702 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11703 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11704 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011705 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011706 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000011707 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011708 SmallVector<Decl *, 4> ExprCaptures;
11709 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011710 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000011711 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000011712 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011713 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011714 SourceLocation ELoc;
11715 SourceRange ERange;
11716 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011717 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011718 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011719 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011720 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011721 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000011722 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000011723 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011724 ValueDecl *D = Res.first;
11725 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000011726 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000011727
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011728 QualType Type = D->getType();
11729 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000011730
11731 // OpenMP [2.14.3.7, linear clause]
11732 // A list-item cannot appear in more than one linear clause.
11733 // A list-item that appears in a linear clause cannot appear in any
11734 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011735 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000011736 if (DVar.RefExpr) {
11737 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11738 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000011739 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000011740 continue;
11741 }
11742
Alexey Bataevecba70f2016-04-12 11:02:11 +000011743 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000011744 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011745 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000011746
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011747 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000011748 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011749 buildVarDecl(*this, ELoc, Type, D->getName(),
11750 D->hasAttrs() ? &D->getAttrs() : nullptr,
11751 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011752 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011753 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011754 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011755 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011756 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011757 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011758 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011759 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011760 ExprCaptures.push_back(Ref->getDecl());
11761 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11762 ExprResult RefRes = DefaultLvalueConversion(Ref);
11763 if (!RefRes.isUsable())
11764 continue;
11765 ExprResult PostUpdateRes =
11766 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11767 SimpleRefExpr, RefRes.get());
11768 if (!PostUpdateRes.isUsable())
11769 continue;
11770 ExprPostUpdates.push_back(
11771 IgnoredValueConversions(PostUpdateRes.get()).get());
11772 }
11773 }
11774 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011775 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011776 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011777 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011778 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011779 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011780 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011781 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011782
11783 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011784 Vars.push_back((VD || CurContext->isDependentContext())
11785 ? RefExpr->IgnoreParens()
11786 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011787 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000011788 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000011789 }
11790
11791 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011792 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011793
11794 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000011795 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011796 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11797 !Step->isInstantiationDependent() &&
11798 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011799 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011800 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000011801 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011802 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011803 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000011804
Alexander Musman3276a272015-03-21 10:12:56 +000011805 // Build var to save the step value.
11806 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011807 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000011808 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011809 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011810 ExprResult CalcStep =
11811 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011812 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011813
Alexander Musman8dba6642014-04-22 13:09:42 +000011814 // Warn about zero linear step (it would be probably better specified as
11815 // making corresponding variables 'const').
11816 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011817 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11818 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011819 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11820 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011821 if (!IsConstant && CalcStep.isUsable()) {
11822 // Calculate the step beforehand instead of doing this on each iteration.
11823 // (This is not used if the number of iterations may be kfold-ed).
11824 CalcStepExpr = CalcStep.get();
11825 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011826 }
11827
Alexey Bataev182227b2015-08-20 10:54:39 +000011828 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11829 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011830 StepExpr, CalcStepExpr,
11831 buildPreInits(Context, ExprCaptures),
11832 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011833}
11834
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011835static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11836 Expr *NumIterations, Sema &SemaRef,
11837 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011838 // Walk the vars and build update/final expressions for the CodeGen.
11839 SmallVector<Expr *, 8> Updates;
11840 SmallVector<Expr *, 8> Finals;
11841 Expr *Step = Clause.getStep();
11842 Expr *CalcStep = Clause.getCalcStep();
11843 // OpenMP [2.14.3.7, linear clause]
11844 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000011845 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000011846 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011847 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000011848 Step = cast<BinaryOperator>(CalcStep)->getLHS();
11849 bool HasErrors = false;
11850 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011851 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000011852 OpenMPLinearClauseKind LinKind = Clause.getModifier();
11853 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011854 SourceLocation ELoc;
11855 SourceRange ERange;
11856 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011857 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011858 ValueDecl *D = Res.first;
11859 if (Res.second || !D) {
11860 Updates.push_back(nullptr);
11861 Finals.push_back(nullptr);
11862 HasErrors = true;
11863 continue;
11864 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011865 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011866 // OpenMP [2.15.11, distribute simd Construct]
11867 // A list item may not appear in a linear clause, unless it is the loop
11868 // iteration variable.
11869 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11870 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11871 SemaRef.Diag(ELoc,
11872 diag::err_omp_linear_distribute_var_non_loop_iteration);
11873 Updates.push_back(nullptr);
11874 Finals.push_back(nullptr);
11875 HasErrors = true;
11876 continue;
11877 }
Alexander Musman3276a272015-03-21 10:12:56 +000011878 Expr *InitExpr = *CurInit;
11879
11880 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011881 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011882 Expr *CapturedRef;
11883 if (LinKind == OMPC_LINEAR_uval)
11884 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11885 else
11886 CapturedRef =
11887 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11888 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11889 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011890
11891 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011892 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000011893 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011894 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000011895 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011896 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011897 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011898 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011899 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011900 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011901
11902 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011903 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000011904 if (!Info.first)
11905 Final =
11906 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11907 InitExpr, NumIterations, Step, /*Subtract=*/false);
11908 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011909 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011910 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011911 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011912
Alexander Musman3276a272015-03-21 10:12:56 +000011913 if (!Update.isUsable() || !Final.isUsable()) {
11914 Updates.push_back(nullptr);
11915 Finals.push_back(nullptr);
11916 HasErrors = true;
11917 } else {
11918 Updates.push_back(Update.get());
11919 Finals.push_back(Final.get());
11920 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011921 ++CurInit;
11922 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011923 }
11924 Clause.setUpdates(Updates);
11925 Clause.setFinals(Finals);
11926 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011927}
11928
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011929OMPClause *Sema::ActOnOpenMPAlignedClause(
11930 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11931 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011932 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011933 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011934 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11935 SourceLocation ELoc;
11936 SourceRange ERange;
11937 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011938 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000011939 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011940 // It will be analyzed later.
11941 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011942 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011943 ValueDecl *D = Res.first;
11944 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011945 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011946
Alexey Bataev1efd1662016-03-29 10:59:56 +000011947 QualType QType = D->getType();
11948 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011949
11950 // OpenMP [2.8.1, simd construct, Restrictions]
11951 // The type of list items appearing in the aligned clause must be
11952 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011953 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011954 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011955 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011956 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011957 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011958 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011959 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011960 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011961 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011962 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011963 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011964 continue;
11965 }
11966
11967 // OpenMP [2.8.1, simd construct, Restrictions]
11968 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011969 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011970 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011971 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11972 << getOpenMPClauseName(OMPC_aligned);
11973 continue;
11974 }
11975
Alexey Bataev1efd1662016-03-29 10:59:56 +000011976 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011977 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000011978 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11979 Vars.push_back(DefaultFunctionArrayConversion(
11980 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11981 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011982 }
11983
11984 // OpenMP [2.8.1, simd construct, Description]
11985 // The parameter of the aligned clause, alignment, must be a constant
11986 // positive integer expression.
11987 // If no optional parameter is specified, implementation-defined default
11988 // alignments for SIMD instructions on the target platforms are assumed.
11989 if (Alignment != nullptr) {
11990 ExprResult AlignResult =
11991 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11992 if (AlignResult.isInvalid())
11993 return nullptr;
11994 Alignment = AlignResult.get();
11995 }
11996 if (Vars.empty())
11997 return nullptr;
11998
11999 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12000 EndLoc, Vars, Alignment);
12001}
12002
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012003OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12004 SourceLocation StartLoc,
12005 SourceLocation LParenLoc,
12006 SourceLocation EndLoc) {
12007 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012008 SmallVector<Expr *, 8> SrcExprs;
12009 SmallVector<Expr *, 8> DstExprs;
12010 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012011 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012012 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12013 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012014 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012015 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012016 SrcExprs.push_back(nullptr);
12017 DstExprs.push_back(nullptr);
12018 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012019 continue;
12020 }
12021
Alexey Bataeved09d242014-05-28 05:53:51 +000012022 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012023 // OpenMP [2.1, C/C++]
12024 // A list item is a variable name.
12025 // OpenMP [2.14.4.1, Restrictions, p.1]
12026 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012027 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012028 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012029 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12030 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012031 continue;
12032 }
12033
12034 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012035 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012036
12037 QualType Type = VD->getType();
12038 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12039 // It will be analyzed later.
12040 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012041 SrcExprs.push_back(nullptr);
12042 DstExprs.push_back(nullptr);
12043 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012044 continue;
12045 }
12046
12047 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12048 // A list item that appears in a copyin clause must be threadprivate.
12049 if (!DSAStack->isThreadPrivate(VD)) {
12050 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012051 << getOpenMPClauseName(OMPC_copyin)
12052 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012053 continue;
12054 }
12055
12056 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12057 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012058 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012059 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012060 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12061 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012062 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012063 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012064 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012065 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012066 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012067 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012068 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012069 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012070 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012071 // For arrays generate assignment operation for single element and replace
12072 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012073 ExprResult AssignmentOp =
12074 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12075 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012076 if (AssignmentOp.isInvalid())
12077 continue;
12078 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012079 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012080 if (AssignmentOp.isInvalid())
12081 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012082
12083 DSAStack->addDSA(VD, DE, OMPC_copyin);
12084 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012085 SrcExprs.push_back(PseudoSrcExpr);
12086 DstExprs.push_back(PseudoDstExpr);
12087 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012088 }
12089
Alexey Bataeved09d242014-05-28 05:53:51 +000012090 if (Vars.empty())
12091 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012092
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012093 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12094 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012095}
12096
Alexey Bataevbae9a792014-06-27 10:37:06 +000012097OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12098 SourceLocation StartLoc,
12099 SourceLocation LParenLoc,
12100 SourceLocation EndLoc) {
12101 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012102 SmallVector<Expr *, 8> SrcExprs;
12103 SmallVector<Expr *, 8> DstExprs;
12104 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012105 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012106 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12107 SourceLocation ELoc;
12108 SourceRange ERange;
12109 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012110 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012111 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012112 // It will be analyzed later.
12113 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012114 SrcExprs.push_back(nullptr);
12115 DstExprs.push_back(nullptr);
12116 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012117 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012118 ValueDecl *D = Res.first;
12119 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012120 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012121
Alexey Bataeve122da12016-03-17 10:50:17 +000012122 QualType Type = D->getType();
12123 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012124
12125 // OpenMP [2.14.4.2, Restrictions, p.2]
12126 // A list item that appears in a copyprivate clause may not appear in a
12127 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012128 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012129 DSAStackTy::DSAVarData DVar =
12130 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012131 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12132 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012133 Diag(ELoc, diag::err_omp_wrong_dsa)
12134 << getOpenMPClauseName(DVar.CKind)
12135 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012136 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012137 continue;
12138 }
12139
12140 // OpenMP [2.11.4.2, Restrictions, p.1]
12141 // All list items that appear in a copyprivate clause must be either
12142 // threadprivate or private in the enclosing context.
12143 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012144 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012145 if (DVar.CKind == OMPC_shared) {
12146 Diag(ELoc, diag::err_omp_required_access)
12147 << getOpenMPClauseName(OMPC_copyprivate)
12148 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012149 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012150 continue;
12151 }
12152 }
12153 }
12154
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012155 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012156 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012157 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012158 << getOpenMPClauseName(OMPC_copyprivate) << Type
12159 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012160 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012161 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012162 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012163 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012164 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012165 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012166 continue;
12167 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012168
Alexey Bataevbae9a792014-06-27 10:37:06 +000012169 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12170 // A variable of class type (or array thereof) that appears in a
12171 // copyin clause requires an accessible, unambiguous copy assignment
12172 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012173 Type = Context.getBaseElementType(Type.getNonReferenceType())
12174 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012175 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012176 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012177 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012178 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12179 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012180 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012181 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012182 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12183 ExprResult AssignmentOp = BuildBinOp(
12184 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012185 if (AssignmentOp.isInvalid())
12186 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012187 AssignmentOp =
12188 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012189 if (AssignmentOp.isInvalid())
12190 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012191
12192 // No need to mark vars as copyprivate, they are already threadprivate or
12193 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012194 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012195 Vars.push_back(
12196 VD ? RefExpr->IgnoreParens()
12197 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012198 SrcExprs.push_back(PseudoSrcExpr);
12199 DstExprs.push_back(PseudoDstExpr);
12200 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012201 }
12202
12203 if (Vars.empty())
12204 return nullptr;
12205
Alexey Bataeva63048e2015-03-23 06:18:07 +000012206 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12207 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012208}
12209
Alexey Bataev6125da92014-07-21 11:26:11 +000012210OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12211 SourceLocation StartLoc,
12212 SourceLocation LParenLoc,
12213 SourceLocation EndLoc) {
12214 if (VarList.empty())
12215 return nullptr;
12216
12217 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12218}
Alexey Bataevdea47612014-07-23 07:46:59 +000012219
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012220OMPClause *
12221Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12222 SourceLocation DepLoc, SourceLocation ColonLoc,
12223 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12224 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012225 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012226 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012227 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012228 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012229 return nullptr;
12230 }
12231 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012232 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12233 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012234 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012235 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012236 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12237 /*Last=*/OMPC_DEPEND_unknown, Except)
12238 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012239 return nullptr;
12240 }
12241 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012242 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012243 llvm::APSInt DepCounter(/*BitWidth=*/32);
12244 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012245 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12246 if (const Expr *OrderedCountExpr =
12247 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012248 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12249 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012250 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012251 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012252 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012253 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12254 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12255 // It will be analyzed later.
12256 Vars.push_back(RefExpr);
12257 continue;
12258 }
12259
12260 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012261 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012262 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012263 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012264 DepCounter >= TotalDepCount) {
12265 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12266 continue;
12267 }
12268 ++DepCounter;
12269 // OpenMP [2.13.9, Summary]
12270 // depend(dependence-type : vec), where dependence-type is:
12271 // 'sink' and where vec is the iteration vector, which has the form:
12272 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12273 // where n is the value specified by the ordered clause in the loop
12274 // directive, xi denotes the loop iteration variable of the i-th nested
12275 // loop associated with the loop directive, and di is a constant
12276 // non-negative integer.
12277 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012278 // It will be analyzed later.
12279 Vars.push_back(RefExpr);
12280 continue;
12281 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012282 SimpleExpr = SimpleExpr->IgnoreImplicit();
12283 OverloadedOperatorKind OOK = OO_None;
12284 SourceLocation OOLoc;
12285 Expr *LHS = SimpleExpr;
12286 Expr *RHS = nullptr;
12287 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12288 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12289 OOLoc = BO->getOperatorLoc();
12290 LHS = BO->getLHS()->IgnoreParenImpCasts();
12291 RHS = BO->getRHS()->IgnoreParenImpCasts();
12292 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12293 OOK = OCE->getOperator();
12294 OOLoc = OCE->getOperatorLoc();
12295 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12296 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12297 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12298 OOK = MCE->getMethodDecl()
12299 ->getNameInfo()
12300 .getName()
12301 .getCXXOverloadedOperator();
12302 OOLoc = MCE->getCallee()->getExprLoc();
12303 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12304 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012305 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012306 SourceLocation ELoc;
12307 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012308 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012309 if (Res.second) {
12310 // It will be analyzed later.
12311 Vars.push_back(RefExpr);
12312 }
12313 ValueDecl *D = Res.first;
12314 if (!D)
12315 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012316
Alexey Bataev17daedf2018-02-15 22:42:57 +000012317 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12318 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12319 continue;
12320 }
12321 if (RHS) {
12322 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12323 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12324 if (RHSRes.isInvalid())
12325 continue;
12326 }
12327 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012328 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012329 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012330 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012331 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012332 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012333 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12334 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012335 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012336 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012337 continue;
12338 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012339 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012340 } else {
12341 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12342 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12343 (ASE &&
12344 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12345 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12346 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12347 << RefExpr->getSourceRange();
12348 continue;
12349 }
12350 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12351 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12352 ExprResult Res =
12353 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12354 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12355 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12356 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12357 << RefExpr->getSourceRange();
12358 continue;
12359 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012360 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012361 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012362 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012363
12364 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12365 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012366 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012367 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12368 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12369 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12370 }
12371 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12372 Vars.empty())
12373 return nullptr;
12374
Alexey Bataev8b427062016-05-25 12:36:08 +000012375 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012376 DepKind, DepLoc, ColonLoc, Vars,
12377 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012378 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12379 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012380 DSAStack->addDoacrossDependClause(C, OpsOffs);
12381 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012382}
Michael Wonge710d542015-08-07 16:16:36 +000012383
12384OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12385 SourceLocation LParenLoc,
12386 SourceLocation EndLoc) {
12387 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012388 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012389
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012390 // OpenMP [2.9.1, Restrictions]
12391 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012392 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012393 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012394 return nullptr;
12395
Alexey Bataev931e19b2017-10-02 16:32:39 +000012396 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012397 OpenMPDirectiveKind CaptureRegion =
12398 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12399 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012400 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012401 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012402 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12403 HelperValStmt = buildPreInits(Context, Captures);
12404 }
12405
Alexey Bataev8451efa2018-01-15 19:06:12 +000012406 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12407 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012408}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012409
Alexey Bataeve3727102018-04-18 15:57:46 +000012410static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012411 DSAStackTy *Stack, QualType QTy,
12412 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012413 NamedDecl *ND;
12414 if (QTy->isIncompleteType(&ND)) {
12415 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12416 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012417 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012418 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12419 !QTy.isTrivialType(SemaRef.Context))
12420 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012421 return true;
12422}
12423
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012424/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012425/// (array section or array subscript) does NOT specify the whole size of the
12426/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012427static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012428 const Expr *E,
12429 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012430 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012431
12432 // If this is an array subscript, it refers to the whole size if the size of
12433 // the dimension is constant and equals 1. Also, an array section assumes the
12434 // format of an array subscript if no colon is used.
12435 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012436 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012437 return ATy->getSize().getSExtValue() != 1;
12438 // Size can't be evaluated statically.
12439 return false;
12440 }
12441
12442 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012443 const Expr *LowerBound = OASE->getLowerBound();
12444 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012445
12446 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012447 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012448 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012449 Expr::EvalResult Result;
12450 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012451 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012452
12453 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012454 if (ConstLowerBound.getSExtValue())
12455 return true;
12456 }
12457
12458 // If we don't have a length we covering the whole dimension.
12459 if (!Length)
12460 return false;
12461
12462 // If the base is a pointer, we don't have a way to get the size of the
12463 // pointee.
12464 if (BaseQTy->isPointerType())
12465 return false;
12466
12467 // We can only check if the length is the same as the size of the dimension
12468 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012469 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012470 if (!CATy)
12471 return false;
12472
Fangrui Song407659a2018-11-30 23:41:18 +000012473 Expr::EvalResult Result;
12474 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012475 return false; // Can't get the integer value as a constant.
12476
Fangrui Song407659a2018-11-30 23:41:18 +000012477 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012478 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12479}
12480
12481// Return true if it can be proven that the provided array expression (array
12482// section or array subscript) does NOT specify a single element of the array
12483// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012484static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012485 const Expr *E,
12486 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012487 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012488
12489 // An array subscript always refer to a single element. Also, an array section
12490 // assumes the format of an array subscript if no colon is used.
12491 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12492 return false;
12493
12494 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012495 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012496
12497 // If we don't have a length we have to check if the array has unitary size
12498 // for this dimension. Also, we should always expect a length if the base type
12499 // is pointer.
12500 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012501 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012502 return ATy->getSize().getSExtValue() != 1;
12503 // We cannot assume anything.
12504 return false;
12505 }
12506
12507 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012508 Expr::EvalResult Result;
12509 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012510 return false; // Can't get the integer value as a constant.
12511
Fangrui Song407659a2018-11-30 23:41:18 +000012512 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012513 return ConstLength.getSExtValue() != 1;
12514}
12515
Samuel Antao661c0902016-05-26 17:39:58 +000012516// Return the expression of the base of the mappable expression or null if it
12517// cannot be determined and do all the necessary checks to see if the expression
12518// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012519// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012520static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012521 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012522 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012523 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012524 SourceLocation ELoc = E->getExprLoc();
12525 SourceRange ERange = E->getSourceRange();
12526
12527 // The base of elements of list in a map clause have to be either:
12528 // - a reference to variable or field.
12529 // - a member expression.
12530 // - an array expression.
12531 //
12532 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12533 // reference to 'r'.
12534 //
12535 // If we have:
12536 //
12537 // struct SS {
12538 // Bla S;
12539 // foo() {
12540 // #pragma omp target map (S.Arr[:12]);
12541 // }
12542 // }
12543 //
12544 // We want to retrieve the member expression 'this->S';
12545
Alexey Bataeve3727102018-04-18 15:57:46 +000012546 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012547
Samuel Antao5de996e2016-01-22 20:21:36 +000012548 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12549 // If a list item is an array section, it must specify contiguous storage.
12550 //
12551 // For this restriction it is sufficient that we make sure only references
12552 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012553 // exist except in the rightmost expression (unless they cover the whole
12554 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012555 //
12556 // r.ArrS[3:5].Arr[6:7]
12557 //
12558 // r.ArrS[3:5].x
12559 //
12560 // but these would be valid:
12561 // r.ArrS[3].Arr[6:7]
12562 //
12563 // r.ArrS[3].x
12564
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012565 bool AllowUnitySizeArraySection = true;
12566 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012567
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012568 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012569 E = E->IgnoreParenImpCasts();
12570
12571 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12572 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012573 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012574
12575 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012576
12577 // If we got a reference to a declaration, we should not expect any array
12578 // section before that.
12579 AllowUnitySizeArraySection = false;
12580 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012581
12582 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012583 CurComponents.emplace_back(CurE, CurE->getDecl());
12584 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012585 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012586
12587 if (isa<CXXThisExpr>(BaseE))
12588 // We found a base expression: this->Val.
12589 RelevantExpr = CurE;
12590 else
12591 E = BaseE;
12592
12593 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012594 if (!NoDiagnose) {
12595 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12596 << CurE->getSourceRange();
12597 return nullptr;
12598 }
12599 if (RelevantExpr)
12600 return nullptr;
12601 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012602 }
12603
12604 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12605
12606 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12607 // A bit-field cannot appear in a map clause.
12608 //
12609 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012610 if (!NoDiagnose) {
12611 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12612 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12613 return nullptr;
12614 }
12615 if (RelevantExpr)
12616 return nullptr;
12617 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012618 }
12619
12620 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12621 // If the type of a list item is a reference to a type T then the type
12622 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012623 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012624
12625 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12626 // A list item cannot be a variable that is a member of a structure with
12627 // a union type.
12628 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012629 if (CurType->isUnionType()) {
12630 if (!NoDiagnose) {
12631 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12632 << CurE->getSourceRange();
12633 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012634 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012635 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012636 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012637
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012638 // If we got a member expression, we should not expect any array section
12639 // before that:
12640 //
12641 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12642 // If a list item is an element of a structure, only the rightmost symbol
12643 // of the variable reference can be an array section.
12644 //
12645 AllowUnitySizeArraySection = false;
12646 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012647
12648 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012649 CurComponents.emplace_back(CurE, FD);
12650 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012651 E = CurE->getBase()->IgnoreParenImpCasts();
12652
12653 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012654 if (!NoDiagnose) {
12655 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12656 << 0 << CurE->getSourceRange();
12657 return nullptr;
12658 }
12659 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012660 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012661
12662 // If we got an array subscript that express the whole dimension we
12663 // can have any array expressions before. If it only expressing part of
12664 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012665 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012666 E->getType()))
12667 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012668
Patrick Lystere13b1e32019-01-02 19:28:48 +000012669 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12670 Expr::EvalResult Result;
12671 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12672 if (!Result.Val.getInt().isNullValue()) {
12673 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12674 diag::err_omp_invalid_map_this_expr);
12675 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12676 diag::note_omp_invalid_subscript_on_this_ptr_map);
12677 }
12678 }
12679 RelevantExpr = TE;
12680 }
12681
Samuel Antao90927002016-04-26 14:54:23 +000012682 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012683 CurComponents.emplace_back(CurE, nullptr);
12684 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012685 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000012686 E = CurE->getBase()->IgnoreParenImpCasts();
12687
Alexey Bataev27041fa2017-12-05 15:22:49 +000012688 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012689 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12690
Samuel Antao5de996e2016-01-22 20:21:36 +000012691 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12692 // If the type of a list item is a reference to a type T then the type
12693 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000012694 if (CurType->isReferenceType())
12695 CurType = CurType->getPointeeType();
12696
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012697 bool IsPointer = CurType->isAnyPointerType();
12698
12699 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012700 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12701 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012702 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012703 }
12704
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012705 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000012706 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012707 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000012708 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012709
Samuel Antaodab51bb2016-07-18 23:22:11 +000012710 if (AllowWholeSizeArraySection) {
12711 // Any array section is currently allowed. Allowing a whole size array
12712 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012713 //
12714 // If this array section refers to the whole dimension we can still
12715 // accept other array sections before this one, except if the base is a
12716 // pointer. Otherwise, only unitary sections are accepted.
12717 if (NotWhole || IsPointer)
12718 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000012719 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012720 // A unity or whole array section is not allowed and that is not
12721 // compatible with the properties of the current array section.
12722 SemaRef.Diag(
12723 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12724 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012725 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012726 }
Samuel Antao90927002016-04-26 14:54:23 +000012727
Patrick Lystere13b1e32019-01-02 19:28:48 +000012728 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12729 Expr::EvalResult ResultR;
12730 Expr::EvalResult ResultL;
12731 if (CurE->getLength()->EvaluateAsInt(ResultR,
12732 SemaRef.getASTContext())) {
12733 if (!ResultR.Val.getInt().isOneValue()) {
12734 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12735 diag::err_omp_invalid_map_this_expr);
12736 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12737 diag::note_omp_invalid_length_on_this_ptr_mapping);
12738 }
12739 }
12740 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
12741 ResultL, SemaRef.getASTContext())) {
12742 if (!ResultL.Val.getInt().isNullValue()) {
12743 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12744 diag::err_omp_invalid_map_this_expr);
12745 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12746 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
12747 }
12748 }
12749 RelevantExpr = TE;
12750 }
12751
Samuel Antao90927002016-04-26 14:54:23 +000012752 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012753 CurComponents.emplace_back(CurE, nullptr);
12754 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012755 if (!NoDiagnose) {
12756 // If nothing else worked, this is not a valid map clause expression.
12757 SemaRef.Diag(
12758 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12759 << ERange;
12760 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000012761 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012762 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012763 }
12764
12765 return RelevantExpr;
12766}
12767
12768// Return true if expression E associated with value VD has conflicts with other
12769// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000012770static bool checkMapConflicts(
12771 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000012772 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000012773 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12774 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012775 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000012776 SourceLocation ELoc = E->getExprLoc();
12777 SourceRange ERange = E->getSourceRange();
12778
12779 // In order to easily check the conflicts we need to match each component of
12780 // the expression under test with the components of the expressions that are
12781 // already in the stack.
12782
Samuel Antao5de996e2016-01-22 20:21:36 +000012783 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012784 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012785 "Map clause expression with unexpected base!");
12786
12787 // Variables to help detecting enclosing problems in data environment nests.
12788 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000012789 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012790
Samuel Antao90927002016-04-26 14:54:23 +000012791 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12792 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000012793 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12794 ERange, CKind, &EnclosingExpr,
12795 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12796 StackComponents,
12797 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012798 assert(!StackComponents.empty() &&
12799 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012800 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012801 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000012802 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012803
Samuel Antao90927002016-04-26 14:54:23 +000012804 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000012805 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000012806
Samuel Antao5de996e2016-01-22 20:21:36 +000012807 // Expressions must start from the same base. Here we detect at which
12808 // point both expressions diverge from each other and see if we can
12809 // detect if the memory referred to both expressions is contiguous and
12810 // do not overlap.
12811 auto CI = CurComponents.rbegin();
12812 auto CE = CurComponents.rend();
12813 auto SI = StackComponents.rbegin();
12814 auto SE = StackComponents.rend();
12815 for (; CI != CE && SI != SE; ++CI, ++SI) {
12816
12817 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12818 // At most one list item can be an array item derived from a given
12819 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000012820 if (CurrentRegionOnly &&
12821 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12822 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12823 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12824 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12825 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000012826 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000012827 << CI->getAssociatedExpression()->getSourceRange();
12828 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12829 diag::note_used_here)
12830 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000012831 return true;
12832 }
12833
12834 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000012835 if (CI->getAssociatedExpression()->getStmtClass() !=
12836 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000012837 break;
12838
12839 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000012840 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000012841 break;
12842 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000012843 // Check if the extra components of the expressions in the enclosing
12844 // data environment are redundant for the current base declaration.
12845 // If they are, the maps completely overlap, which is legal.
12846 for (; SI != SE; ++SI) {
12847 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000012848 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000012849 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012850 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012851 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000012852 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012853 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000012854 Type =
12855 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12856 }
12857 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012858 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000012859 SemaRef, SI->getAssociatedExpression(), Type))
12860 break;
12861 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012862
12863 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12864 // List items of map clauses in the same construct must not share
12865 // original storage.
12866 //
12867 // If the expressions are exactly the same or one is a subset of the
12868 // other, it means they are sharing storage.
12869 if (CI == CE && SI == SE) {
12870 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012871 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000012872 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012873 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012874 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012875 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12876 << ERange;
12877 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012878 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12879 << RE->getSourceRange();
12880 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012881 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012882 // If we find the same expression in the enclosing data environment,
12883 // that is legal.
12884 IsEnclosedByDataEnvironmentExpr = true;
12885 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000012886 }
12887
Samuel Antao90927002016-04-26 14:54:23 +000012888 QualType DerivedType =
12889 std::prev(CI)->getAssociatedDeclaration()->getType();
12890 SourceLocation DerivedLoc =
12891 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012892
12893 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12894 // If the type of a list item is a reference to a type T then the type
12895 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012896 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012897
12898 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12899 // A variable for which the type is pointer and an array section
12900 // derived from that variable must not appear as list items of map
12901 // clauses of the same construct.
12902 //
12903 // Also, cover one of the cases in:
12904 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12905 // If any part of the original storage of a list item has corresponding
12906 // storage in the device data environment, all of the original storage
12907 // must have corresponding storage in the device data environment.
12908 //
12909 if (DerivedType->isAnyPointerType()) {
12910 if (CI == CE || SI == SE) {
12911 SemaRef.Diag(
12912 DerivedLoc,
12913 diag::err_omp_pointer_mapped_along_with_derived_section)
12914 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012915 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12916 << RE->getSourceRange();
12917 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000012918 }
12919 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000012920 SI->getAssociatedExpression()->getStmtClass() ||
12921 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12922 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012923 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012924 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012925 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012926 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12927 << RE->getSourceRange();
12928 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012929 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012930 }
12931
12932 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12933 // List items of map clauses in the same construct must not share
12934 // original storage.
12935 //
12936 // An expression is a subset of the other.
12937 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012938 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000012939 if (CI != CE || SI != SE) {
12940 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12941 // a pointer.
12942 auto Begin =
12943 CI != CE ? CurComponents.begin() : StackComponents.begin();
12944 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12945 auto It = Begin;
12946 while (It != End && !It->getAssociatedDeclaration())
12947 std::advance(It, 1);
12948 assert(It != End &&
12949 "Expected at least one component with the declaration.");
12950 if (It != Begin && It->getAssociatedDeclaration()
12951 ->getType()
12952 .getCanonicalType()
12953 ->isAnyPointerType()) {
12954 IsEnclosedByDataEnvironmentExpr = false;
12955 EnclosingExpr = nullptr;
12956 return false;
12957 }
12958 }
Samuel Antao661c0902016-05-26 17:39:58 +000012959 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012960 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012961 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012962 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12963 << ERange;
12964 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012965 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12966 << RE->getSourceRange();
12967 return true;
12968 }
12969
12970 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012971 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012972 if (!CurrentRegionOnly && SI != SE)
12973 EnclosingExpr = RE;
12974
12975 // The current expression is a subset of the expression in the data
12976 // environment.
12977 IsEnclosedByDataEnvironmentExpr |=
12978 (!CurrentRegionOnly && CI != CE && SI == SE);
12979
12980 return false;
12981 });
12982
12983 if (CurrentRegionOnly)
12984 return FoundError;
12985
12986 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12987 // If any part of the original storage of a list item has corresponding
12988 // storage in the device data environment, all of the original storage must
12989 // have corresponding storage in the device data environment.
12990 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12991 // If a list item is an element of a structure, and a different element of
12992 // the structure has a corresponding list item in the device data environment
12993 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012994 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012995 // data environment prior to the task encountering the construct.
12996 //
12997 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12998 SemaRef.Diag(ELoc,
12999 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13000 << ERange;
13001 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13002 << EnclosingExpr->getSourceRange();
13003 return true;
13004 }
13005
13006 return FoundError;
13007}
13008
Michael Kruse4304e9d2019-02-19 16:38:20 +000013009// Look up the user-defined mapper given the mapper name and mapped type, and
13010// build a reference to it.
13011ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13012 CXXScopeSpec &MapperIdScopeSpec,
13013 const DeclarationNameInfo &MapperId,
13014 QualType Type, Expr *UnresolvedMapper) {
13015 if (MapperIdScopeSpec.isInvalid())
13016 return ExprError();
13017 // Find all user-defined mappers with the given MapperId.
13018 SmallVector<UnresolvedSet<8>, 4> Lookups;
13019 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13020 Lookup.suppressDiagnostics();
13021 if (S) {
13022 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13023 NamedDecl *D = Lookup.getRepresentativeDecl();
13024 while (S && !S->isDeclScope(D))
13025 S = S->getParent();
13026 if (S)
13027 S = S->getParent();
13028 Lookups.emplace_back();
13029 Lookups.back().append(Lookup.begin(), Lookup.end());
13030 Lookup.clear();
13031 }
13032 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13033 // Extract the user-defined mappers with the given MapperId.
13034 Lookups.push_back(UnresolvedSet<8>());
13035 for (NamedDecl *D : ULE->decls()) {
13036 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13037 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13038 Lookups.back().addDecl(DMD);
13039 }
13040 }
13041 // Defer the lookup for dependent types. The results will be passed through
13042 // UnresolvedMapper on instantiation.
13043 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13044 Type->isInstantiationDependentType() ||
13045 Type->containsUnexpandedParameterPack() ||
13046 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13047 return !D->isInvalidDecl() &&
13048 (D->getType()->isDependentType() ||
13049 D->getType()->isInstantiationDependentType() ||
13050 D->getType()->containsUnexpandedParameterPack());
13051 })) {
13052 UnresolvedSet<8> URS;
13053 for (const UnresolvedSet<8> &Set : Lookups) {
13054 if (Set.empty())
13055 continue;
13056 URS.append(Set.begin(), Set.end());
13057 }
13058 return UnresolvedLookupExpr::Create(
13059 SemaRef.Context, /*NamingClass=*/nullptr,
13060 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13061 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13062 }
13063 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13064 // The type must be of struct, union or class type in C and C++
13065 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13066 return ExprEmpty();
13067 SourceLocation Loc = MapperId.getLoc();
13068 // Perform argument dependent lookup.
13069 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13070 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13071 // Return the first user-defined mapper with the desired type.
13072 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13073 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13074 if (!D->isInvalidDecl() &&
13075 SemaRef.Context.hasSameType(D->getType(), Type))
13076 return D;
13077 return nullptr;
13078 }))
13079 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13080 // Find the first user-defined mapper with a type derived from the desired
13081 // type.
13082 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13083 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13084 if (!D->isInvalidDecl() &&
13085 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13086 !Type.isMoreQualifiedThan(D->getType()))
13087 return D;
13088 return nullptr;
13089 })) {
13090 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13091 /*DetectVirtual=*/false);
13092 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13093 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13094 VD->getType().getUnqualifiedType()))) {
13095 if (SemaRef.CheckBaseClassAccess(
13096 Loc, VD->getType(), Type, Paths.front(),
13097 /*DiagID=*/0) != Sema::AR_inaccessible) {
13098 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13099 }
13100 }
13101 }
13102 }
13103 // Report error if a mapper is specified, but cannot be found.
13104 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13105 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13106 << Type << MapperId.getName();
13107 return ExprError();
13108 }
13109 return ExprEmpty();
13110}
13111
Samuel Antao661c0902016-05-26 17:39:58 +000013112namespace {
13113// Utility struct that gathers all the related lists associated with a mappable
13114// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013115struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013116 // The list of expressions.
13117 ArrayRef<Expr *> VarList;
13118 // The list of processed expressions.
13119 SmallVector<Expr *, 16> ProcessedVarList;
13120 // The mappble components for each expression.
13121 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13122 // The base declaration of the variable.
13123 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013124 // The reference to the user-defined mapper associated with every expression.
13125 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013126
13127 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13128 // We have a list of components and base declarations for each entry in the
13129 // variable list.
13130 VarComponents.reserve(VarList.size());
13131 VarBaseDeclarations.reserve(VarList.size());
13132 }
13133};
13134}
13135
13136// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013137// \a CKind. In the check process the valid expressions, mappable expression
13138// components, variables, and user-defined mappers are extracted and used to
13139// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13140// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13141// and \a MapperId are expected to be valid if the clause kind is 'map'.
13142static void checkMappableExpressionList(
13143 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13144 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013145 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13146 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013147 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013148 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013149 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13150 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013151 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013152
13153 // If the identifier of user-defined mapper is not specified, it is "default".
13154 // We do not change the actual name in this clause to distinguish whether a
13155 // mapper is specified explicitly, i.e., it is not explicitly specified when
13156 // MapperId.getName() is empty.
13157 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13158 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13159 MapperId.setName(DeclNames.getIdentifier(
13160 &SemaRef.getASTContext().Idents.get("default")));
13161 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013162
13163 // Iterators to find the current unresolved mapper expression.
13164 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13165 bool UpdateUMIt = false;
13166 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013167
Samuel Antao90927002016-04-26 14:54:23 +000013168 // Keep track of the mappable components and base declarations in this clause.
13169 // Each entry in the list is going to have a list of components associated. We
13170 // record each set of the components so that we can build the clause later on.
13171 // In the end we should have the same amount of declarations and component
13172 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013173
Alexey Bataeve3727102018-04-18 15:57:46 +000013174 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013175 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013176 SourceLocation ELoc = RE->getExprLoc();
13177
Michael Kruse4304e9d2019-02-19 16:38:20 +000013178 // Find the current unresolved mapper expression.
13179 if (UpdateUMIt && UMIt != UMEnd) {
13180 UMIt++;
13181 assert(
13182 UMIt != UMEnd &&
13183 "Expect the size of UnresolvedMappers to match with that of VarList");
13184 }
13185 UpdateUMIt = true;
13186 if (UMIt != UMEnd)
13187 UnresolvedMapper = *UMIt;
13188
Alexey Bataeve3727102018-04-18 15:57:46 +000013189 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013190
13191 if (VE->isValueDependent() || VE->isTypeDependent() ||
13192 VE->isInstantiationDependent() ||
13193 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013194 // Try to find the associated user-defined mapper.
13195 ExprResult ER = buildUserDefinedMapperRef(
13196 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13197 VE->getType().getCanonicalType(), UnresolvedMapper);
13198 if (ER.isInvalid())
13199 continue;
13200 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013201 // We can only analyze this information once the missing information is
13202 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013203 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013204 continue;
13205 }
13206
Alexey Bataeve3727102018-04-18 15:57:46 +000013207 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013208
Samuel Antao5de996e2016-01-22 20:21:36 +000013209 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013210 SemaRef.Diag(ELoc,
13211 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013212 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013213 continue;
13214 }
13215
Samuel Antao90927002016-04-26 14:54:23 +000013216 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13217 ValueDecl *CurDeclaration = nullptr;
13218
13219 // Obtain the array or member expression bases if required. Also, fill the
13220 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013221 const Expr *BE = checkMapClauseExpressionBase(
13222 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013223 if (!BE)
13224 continue;
13225
Samuel Antao90927002016-04-26 14:54:23 +000013226 assert(!CurComponents.empty() &&
13227 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013228
Patrick Lystere13b1e32019-01-02 19:28:48 +000013229 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13230 // Add store "this" pointer to class in DSAStackTy for future checking
13231 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013232 // Try to find the associated user-defined mapper.
13233 ExprResult ER = buildUserDefinedMapperRef(
13234 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13235 VE->getType().getCanonicalType(), UnresolvedMapper);
13236 if (ER.isInvalid())
13237 continue;
13238 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013239 // Skip restriction checking for variable or field declarations
13240 MVLI.ProcessedVarList.push_back(RE);
13241 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13242 MVLI.VarComponents.back().append(CurComponents.begin(),
13243 CurComponents.end());
13244 MVLI.VarBaseDeclarations.push_back(nullptr);
13245 continue;
13246 }
13247
Samuel Antao90927002016-04-26 14:54:23 +000013248 // For the following checks, we rely on the base declaration which is
13249 // expected to be associated with the last component. The declaration is
13250 // expected to be a variable or a field (if 'this' is being mapped).
13251 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13252 assert(CurDeclaration && "Null decl on map clause.");
13253 assert(
13254 CurDeclaration->isCanonicalDecl() &&
13255 "Expecting components to have associated only canonical declarations.");
13256
13257 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013258 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013259
13260 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013261 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013262
13263 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013264 // threadprivate variables cannot appear in a map clause.
13265 // OpenMP 4.5 [2.10.5, target update Construct]
13266 // threadprivate variables cannot appear in a from clause.
13267 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013268 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013269 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13270 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013271 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013272 continue;
13273 }
13274
Samuel Antao5de996e2016-01-22 20:21:36 +000013275 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13276 // A list item cannot appear in both a map clause and a data-sharing
13277 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013278
Samuel Antao5de996e2016-01-22 20:21:36 +000013279 // Check conflicts with other map clause expressions. We check the conflicts
13280 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013281 // environment, because the restrictions are different. We only have to
13282 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013283 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013284 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013285 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013286 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013287 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013288 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013289 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013290
Samuel Antao661c0902016-05-26 17:39:58 +000013291 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013292 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13293 // If the type of a list item is a reference to a type T then the type will
13294 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013295 auto I = llvm::find_if(
13296 CurComponents,
13297 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13298 return MC.getAssociatedDeclaration();
13299 });
13300 assert(I != CurComponents.end() && "Null decl on map clause.");
13301 QualType Type =
13302 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013303
Samuel Antao661c0902016-05-26 17:39:58 +000013304 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13305 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013306 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013307 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013308 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013309 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013310 continue;
13311
Samuel Antao661c0902016-05-26 17:39:58 +000013312 if (CKind == OMPC_map) {
13313 // target enter data
13314 // OpenMP [2.10.2, Restrictions, p. 99]
13315 // A map-type must be specified in all map clauses and must be either
13316 // to or alloc.
13317 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13318 if (DKind == OMPD_target_enter_data &&
13319 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13320 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13321 << (IsMapTypeImplicit ? 1 : 0)
13322 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13323 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013324 continue;
13325 }
Samuel Antao661c0902016-05-26 17:39:58 +000013326
13327 // target exit_data
13328 // OpenMP [2.10.3, Restrictions, p. 102]
13329 // A map-type must be specified in all map clauses and must be either
13330 // from, release, or delete.
13331 if (DKind == OMPD_target_exit_data &&
13332 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13333 MapType == OMPC_MAP_delete)) {
13334 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13335 << (IsMapTypeImplicit ? 1 : 0)
13336 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13337 << getOpenMPDirectiveName(DKind);
13338 continue;
13339 }
13340
13341 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13342 // A list item cannot appear in both a map clause and a data-sharing
13343 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013344 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13345 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013346 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013347 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013348 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013349 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013350 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013351 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013352 continue;
13353 }
13354 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013355 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013356
Michael Kruse01f670d2019-02-22 22:29:42 +000013357 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013358 ExprResult ER = buildUserDefinedMapperRef(
13359 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13360 Type.getCanonicalType(), UnresolvedMapper);
13361 if (ER.isInvalid())
13362 continue;
13363 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013364
Samuel Antao90927002016-04-26 14:54:23 +000013365 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013366 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013367
13368 // Store the components in the stack so that they can be used to check
13369 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013370 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13371 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013372
13373 // Save the components and declaration to create the clause. For purposes of
13374 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013375 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013376 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13377 MVLI.VarComponents.back().append(CurComponents.begin(),
13378 CurComponents.end());
13379 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13380 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013381 }
Samuel Antao661c0902016-05-26 17:39:58 +000013382}
13383
Michael Kruse4304e9d2019-02-19 16:38:20 +000013384OMPClause *Sema::ActOnOpenMPMapClause(
13385 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13386 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13387 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13388 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13389 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13390 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13391 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13392 OMPC_MAP_MODIFIER_unknown,
13393 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013394 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13395
13396 // Process map-type-modifiers, flag errors for duplicate modifiers.
13397 unsigned Count = 0;
13398 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13399 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13400 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13401 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13402 continue;
13403 }
13404 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013405 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013406 Modifiers[Count] = MapTypeModifiers[I];
13407 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13408 ++Count;
13409 }
13410
Michael Kruse4304e9d2019-02-19 16:38:20 +000013411 MappableVarListInfo MVLI(VarList);
13412 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013413 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13414 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013415
Samuel Antao5de996e2016-01-22 20:21:36 +000013416 // We need to produce a map clause even if we don't have variables so that
13417 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013418 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13419 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13420 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13421 MapperIdScopeSpec.getWithLocInContext(Context),
13422 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013423}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013424
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013425QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13426 TypeResult ParsedType) {
13427 assert(ParsedType.isUsable());
13428
13429 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13430 if (ReductionType.isNull())
13431 return QualType();
13432
13433 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13434 // A type name in a declare reduction directive cannot be a function type, an
13435 // array type, a reference type, or a type qualified with const, volatile or
13436 // restrict.
13437 if (ReductionType.hasQualifiers()) {
13438 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13439 return QualType();
13440 }
13441
13442 if (ReductionType->isFunctionType()) {
13443 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13444 return QualType();
13445 }
13446 if (ReductionType->isReferenceType()) {
13447 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13448 return QualType();
13449 }
13450 if (ReductionType->isArrayType()) {
13451 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13452 return QualType();
13453 }
13454 return ReductionType;
13455}
13456
13457Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13458 Scope *S, DeclContext *DC, DeclarationName Name,
13459 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13460 AccessSpecifier AS, Decl *PrevDeclInScope) {
13461 SmallVector<Decl *, 8> Decls;
13462 Decls.reserve(ReductionTypes.size());
13463
13464 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013465 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013466 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13467 // A reduction-identifier may not be re-declared in the current scope for the
13468 // same type or for a type that is compatible according to the base language
13469 // rules.
13470 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13471 OMPDeclareReductionDecl *PrevDRD = nullptr;
13472 bool InCompoundScope = true;
13473 if (S != nullptr) {
13474 // Find previous declaration with the same name not referenced in other
13475 // declarations.
13476 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13477 InCompoundScope =
13478 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13479 LookupName(Lookup, S);
13480 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13481 /*AllowInlineNamespace=*/false);
13482 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013483 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013484 while (Filter.hasNext()) {
13485 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13486 if (InCompoundScope) {
13487 auto I = UsedAsPrevious.find(PrevDecl);
13488 if (I == UsedAsPrevious.end())
13489 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013490 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013491 UsedAsPrevious[D] = true;
13492 }
13493 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13494 PrevDecl->getLocation();
13495 }
13496 Filter.done();
13497 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013498 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013499 if (!PrevData.second) {
13500 PrevDRD = PrevData.first;
13501 break;
13502 }
13503 }
13504 }
13505 } else if (PrevDeclInScope != nullptr) {
13506 auto *PrevDRDInScope = PrevDRD =
13507 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13508 do {
13509 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13510 PrevDRDInScope->getLocation();
13511 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13512 } while (PrevDRDInScope != nullptr);
13513 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013514 for (const auto &TyData : ReductionTypes) {
13515 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013516 bool Invalid = false;
13517 if (I != PreviousRedeclTypes.end()) {
13518 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13519 << TyData.first;
13520 Diag(I->second, diag::note_previous_definition);
13521 Invalid = true;
13522 }
13523 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13524 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13525 Name, TyData.first, PrevDRD);
13526 DC->addDecl(DRD);
13527 DRD->setAccess(AS);
13528 Decls.push_back(DRD);
13529 if (Invalid)
13530 DRD->setInvalidDecl();
13531 else
13532 PrevDRD = DRD;
13533 }
13534
13535 return DeclGroupPtrTy::make(
13536 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13537}
13538
13539void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13540 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13541
13542 // Enter new function scope.
13543 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013544 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013545 getCurFunction()->setHasOMPDeclareReductionCombiner();
13546
13547 if (S != nullptr)
13548 PushDeclContext(S, DRD);
13549 else
13550 CurContext = DRD;
13551
Faisal Valid143a0c2017-04-01 21:30:49 +000013552 PushExpressionEvaluationContext(
13553 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013554
13555 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013556 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13557 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13558 // uses semantics of argument handles by value, but it should be passed by
13559 // reference. C lang does not support references, so pass all parameters as
13560 // pointers.
13561 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013562 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013563 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013564 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13565 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13566 // uses semantics of argument handles by value, but it should be passed by
13567 // reference. C lang does not support references, so pass all parameters as
13568 // pointers.
13569 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013570 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013571 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13572 if (S != nullptr) {
13573 PushOnScopeChains(OmpInParm, S);
13574 PushOnScopeChains(OmpOutParm, S);
13575 } else {
13576 DRD->addDecl(OmpInParm);
13577 DRD->addDecl(OmpOutParm);
13578 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013579 Expr *InE =
13580 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13581 Expr *OutE =
13582 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13583 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013584}
13585
13586void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13587 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13588 DiscardCleanupsInEvaluationContext();
13589 PopExpressionEvaluationContext();
13590
13591 PopDeclContext();
13592 PopFunctionScopeInfo();
13593
13594 if (Combiner != nullptr)
13595 DRD->setCombiner(Combiner);
13596 else
13597 DRD->setInvalidDecl();
13598}
13599
Alexey Bataev070f43a2017-09-06 14:49:58 +000013600VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013601 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13602
13603 // Enter new function scope.
13604 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013605 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013606
13607 if (S != nullptr)
13608 PushDeclContext(S, DRD);
13609 else
13610 CurContext = DRD;
13611
Faisal Valid143a0c2017-04-01 21:30:49 +000013612 PushExpressionEvaluationContext(
13613 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013614
13615 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013616 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13617 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13618 // uses semantics of argument handles by value, but it should be passed by
13619 // reference. C lang does not support references, so pass all parameters as
13620 // pointers.
13621 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013622 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013623 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013624 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13625 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13626 // uses semantics of argument handles by value, but it should be passed by
13627 // reference. C lang does not support references, so pass all parameters as
13628 // pointers.
13629 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013630 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013631 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013632 if (S != nullptr) {
13633 PushOnScopeChains(OmpPrivParm, S);
13634 PushOnScopeChains(OmpOrigParm, S);
13635 } else {
13636 DRD->addDecl(OmpPrivParm);
13637 DRD->addDecl(OmpOrigParm);
13638 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013639 Expr *OrigE =
13640 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13641 Expr *PrivE =
13642 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13643 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013644 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013645}
13646
Alexey Bataev070f43a2017-09-06 14:49:58 +000013647void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13648 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013649 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13650 DiscardCleanupsInEvaluationContext();
13651 PopExpressionEvaluationContext();
13652
13653 PopDeclContext();
13654 PopFunctionScopeInfo();
13655
Alexey Bataev070f43a2017-09-06 14:49:58 +000013656 if (Initializer != nullptr) {
13657 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13658 } else if (OmpPrivParm->hasInit()) {
13659 DRD->setInitializer(OmpPrivParm->getInit(),
13660 OmpPrivParm->isDirectInit()
13661 ? OMPDeclareReductionDecl::DirectInit
13662 : OMPDeclareReductionDecl::CopyInit);
13663 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013664 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013665 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013666}
13667
13668Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13669 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013670 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013671 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013672 if (S)
13673 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13674 /*AddToContext=*/false);
13675 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013676 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013677 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013678 }
13679 return DeclReductions;
13680}
13681
Michael Kruse251e1482019-02-01 20:25:04 +000013682TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13683 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13684 QualType T = TInfo->getType();
13685 if (D.isInvalidType())
13686 return true;
13687
13688 if (getLangOpts().CPlusPlus) {
13689 // Check that there are no default arguments (C++ only).
13690 CheckExtraCXXDefaultArguments(D);
13691 }
13692
13693 return CreateParsedType(T, TInfo);
13694}
13695
13696QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
13697 TypeResult ParsedType) {
13698 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
13699
13700 QualType MapperType = GetTypeFromParser(ParsedType.get());
13701 assert(!MapperType.isNull() && "Expect valid mapper type");
13702
13703 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13704 // The type must be of struct, union or class type in C and C++
13705 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
13706 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
13707 return QualType();
13708 }
13709 return MapperType;
13710}
13711
13712OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
13713 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
13714 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
13715 Decl *PrevDeclInScope) {
13716 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
13717 forRedeclarationInCurContext());
13718 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13719 // A mapper-identifier may not be redeclared in the current scope for the
13720 // same type or for a type that is compatible according to the base language
13721 // rules.
13722 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13723 OMPDeclareMapperDecl *PrevDMD = nullptr;
13724 bool InCompoundScope = true;
13725 if (S != nullptr) {
13726 // Find previous declaration with the same name not referenced in other
13727 // declarations.
13728 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13729 InCompoundScope =
13730 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13731 LookupName(Lookup, S);
13732 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13733 /*AllowInlineNamespace=*/false);
13734 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
13735 LookupResult::Filter Filter = Lookup.makeFilter();
13736 while (Filter.hasNext()) {
13737 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
13738 if (InCompoundScope) {
13739 auto I = UsedAsPrevious.find(PrevDecl);
13740 if (I == UsedAsPrevious.end())
13741 UsedAsPrevious[PrevDecl] = false;
13742 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
13743 UsedAsPrevious[D] = true;
13744 }
13745 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13746 PrevDecl->getLocation();
13747 }
13748 Filter.done();
13749 if (InCompoundScope) {
13750 for (const auto &PrevData : UsedAsPrevious) {
13751 if (!PrevData.second) {
13752 PrevDMD = PrevData.first;
13753 break;
13754 }
13755 }
13756 }
13757 } else if (PrevDeclInScope) {
13758 auto *PrevDMDInScope = PrevDMD =
13759 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
13760 do {
13761 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
13762 PrevDMDInScope->getLocation();
13763 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
13764 } while (PrevDMDInScope != nullptr);
13765 }
13766 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
13767 bool Invalid = false;
13768 if (I != PreviousRedeclTypes.end()) {
13769 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
13770 << MapperType << Name;
13771 Diag(I->second, diag::note_previous_definition);
13772 Invalid = true;
13773 }
13774 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
13775 MapperType, VN, PrevDMD);
13776 DC->addDecl(DMD);
13777 DMD->setAccess(AS);
13778 if (Invalid)
13779 DMD->setInvalidDecl();
13780
13781 // Enter new function scope.
13782 PushFunctionScope();
13783 setFunctionHasBranchProtectedScope();
13784
13785 CurContext = DMD;
13786
13787 return DMD;
13788}
13789
13790void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
13791 Scope *S,
13792 QualType MapperType,
13793 SourceLocation StartLoc,
13794 DeclarationName VN) {
13795 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
13796 if (S)
13797 PushOnScopeChains(VD, S);
13798 else
13799 DMD->addDecl(VD);
13800 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
13801 DMD->setMapperVarRef(MapperVarRefExpr);
13802}
13803
13804Sema::DeclGroupPtrTy
13805Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
13806 ArrayRef<OMPClause *> ClauseList) {
13807 PopDeclContext();
13808 PopFunctionScopeInfo();
13809
13810 if (D) {
13811 if (S)
13812 PushOnScopeChains(D, S, /*AddToContext=*/false);
13813 D->CreateClauses(Context, ClauseList);
13814 }
13815
13816 return DeclGroupPtrTy::make(DeclGroupRef(D));
13817}
13818
David Majnemer9d168222016-08-05 17:44:54 +000013819OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000013820 SourceLocation StartLoc,
13821 SourceLocation LParenLoc,
13822 SourceLocation EndLoc) {
13823 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013824 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013825
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013826 // OpenMP [teams Constrcut, Restrictions]
13827 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013828 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000013829 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013830 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013831
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013832 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013833 OpenMPDirectiveKind CaptureRegion =
13834 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13835 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013836 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013837 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013838 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13839 HelperValStmt = buildPreInits(Context, Captures);
13840 }
13841
13842 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13843 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000013844}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013845
13846OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13847 SourceLocation StartLoc,
13848 SourceLocation LParenLoc,
13849 SourceLocation EndLoc) {
13850 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013851 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013852
13853 // OpenMP [teams Constrcut, Restrictions]
13854 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013855 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000013856 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013857 return nullptr;
13858
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013859 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013860 OpenMPDirectiveKind CaptureRegion =
13861 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13862 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013863 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013864 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013865 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13866 HelperValStmt = buildPreInits(Context, Captures);
13867 }
13868
13869 return new (Context) OMPThreadLimitClause(
13870 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013871}
Alexey Bataeva0569352015-12-01 10:17:31 +000013872
13873OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13874 SourceLocation StartLoc,
13875 SourceLocation LParenLoc,
13876 SourceLocation EndLoc) {
13877 Expr *ValExpr = Priority;
13878
13879 // OpenMP [2.9.1, task Constrcut]
13880 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013881 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000013882 /*StrictlyPositive=*/false))
13883 return nullptr;
13884
13885 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13886}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013887
13888OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13889 SourceLocation StartLoc,
13890 SourceLocation LParenLoc,
13891 SourceLocation EndLoc) {
13892 Expr *ValExpr = Grainsize;
13893
13894 // OpenMP [2.9.2, taskloop Constrcut]
13895 // The parameter of the grainsize clause must be a positive integer
13896 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013897 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013898 /*StrictlyPositive=*/true))
13899 return nullptr;
13900
13901 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13902}
Alexey Bataev382967a2015-12-08 12:06:20 +000013903
13904OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13905 SourceLocation StartLoc,
13906 SourceLocation LParenLoc,
13907 SourceLocation EndLoc) {
13908 Expr *ValExpr = NumTasks;
13909
13910 // OpenMP [2.9.2, taskloop Constrcut]
13911 // The parameter of the num_tasks clause must be a positive integer
13912 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013913 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000013914 /*StrictlyPositive=*/true))
13915 return nullptr;
13916
13917 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13918}
13919
Alexey Bataev28c75412015-12-15 08:19:24 +000013920OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13921 SourceLocation LParenLoc,
13922 SourceLocation EndLoc) {
13923 // OpenMP [2.13.2, critical construct, Description]
13924 // ... where hint-expression is an integer constant expression that evaluates
13925 // to a valid lock hint.
13926 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13927 if (HintExpr.isInvalid())
13928 return nullptr;
13929 return new (Context)
13930 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13931}
13932
Carlo Bertollib4adf552016-01-15 18:50:31 +000013933OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13934 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13935 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13936 SourceLocation EndLoc) {
13937 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13938 std::string Values;
13939 Values += "'";
13940 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13941 Values += "'";
13942 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13943 << Values << getOpenMPClauseName(OMPC_dist_schedule);
13944 return nullptr;
13945 }
13946 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000013947 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000013948 if (ChunkSize) {
13949 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13950 !ChunkSize->isInstantiationDependent() &&
13951 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013952 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000013953 ExprResult Val =
13954 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13955 if (Val.isInvalid())
13956 return nullptr;
13957
13958 ValExpr = Val.get();
13959
13960 // OpenMP [2.7.1, Restrictions]
13961 // chunk_size must be a loop invariant integer expression with a positive
13962 // value.
13963 llvm::APSInt Result;
13964 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13965 if (Result.isSigned() && !Result.isStrictlyPositive()) {
13966 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13967 << "dist_schedule" << ChunkSize->getSourceRange();
13968 return nullptr;
13969 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000013970 } else if (getOpenMPCaptureRegionForClause(
13971 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13972 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000013973 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013974 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013975 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000013976 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13977 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013978 }
13979 }
13980 }
13981
13982 return new (Context)
13983 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000013984 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013985}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013986
13987OMPClause *Sema::ActOnOpenMPDefaultmapClause(
13988 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
13989 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
13990 SourceLocation KindLoc, SourceLocation EndLoc) {
13991 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000013992 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013993 std::string Value;
13994 SourceLocation Loc;
13995 Value += "'";
13996 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
13997 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000013998 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013999 Loc = MLoc;
14000 } else {
14001 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014002 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014003 Loc = KindLoc;
14004 }
14005 Value += "'";
14006 Diag(Loc, diag::err_omp_unexpected_clause_value)
14007 << Value << getOpenMPClauseName(OMPC_defaultmap);
14008 return nullptr;
14009 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014010 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014011
14012 return new (Context)
14013 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14014}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014015
14016bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14017 DeclContext *CurLexicalContext = getCurLexicalContext();
14018 if (!CurLexicalContext->isFileContext() &&
14019 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014020 !CurLexicalContext->isExternCXXContext() &&
14021 !isa<CXXRecordDecl>(CurLexicalContext) &&
14022 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14023 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14024 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014025 Diag(Loc, diag::err_omp_region_not_file_context);
14026 return false;
14027 }
Kelvin Libc38e632018-09-10 02:07:09 +000014028 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014029 return true;
14030}
14031
14032void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014033 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014034 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014035 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014036}
14037
David Majnemer9d168222016-08-05 17:44:54 +000014038void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14039 CXXScopeSpec &ScopeSpec,
14040 const DeclarationNameInfo &Id,
14041 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14042 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014043 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14044 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14045
14046 if (Lookup.isAmbiguous())
14047 return;
14048 Lookup.suppressDiagnostics();
14049
14050 if (!Lookup.isSingleResult()) {
14051 if (TypoCorrection Corrected =
14052 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14053 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14054 CTK_ErrorRecovery)) {
14055 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14056 << Id.getName());
14057 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14058 return;
14059 }
14060
14061 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14062 return;
14063 }
14064
14065 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014066 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14067 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014068 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14069 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014070 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14071 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14072 cast<ValueDecl>(ND));
14073 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014074 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014075 ND->addAttr(A);
14076 if (ASTMutationListener *ML = Context.getASTMutationListener())
14077 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014078 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014079 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014080 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14081 << Id.getName();
14082 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014083 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014084 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014085 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014086}
14087
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014088static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14089 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014090 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014091 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014092 auto *VD = cast<VarDecl>(D);
14093 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14094 return;
14095 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14096 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014097}
14098
14099static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14100 Sema &SemaRef, DSAStackTy *Stack,
14101 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014102 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14103 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14104 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014105}
14106
Kelvin Li1ce87c72017-12-12 20:08:12 +000014107void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14108 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014109 if (!D || D->isInvalidDecl())
14110 return;
14111 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014112 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014113 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014114 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014115 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14116 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014117 return;
14118 // 2.10.6: threadprivate variable cannot appear in a declare target
14119 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014120 if (DSAStack->isThreadPrivate(VD)) {
14121 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014122 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014123 return;
14124 }
14125 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014126 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14127 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014128 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014129 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14130 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14131 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014132 assert(IdLoc.isValid() && "Source location is expected");
14133 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14134 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14135 return;
14136 }
14137 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014138 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14139 // Problem if any with var declared with incomplete type will be reported
14140 // as normal, so no need to check it here.
14141 if ((E || !VD->getType()->isIncompleteType()) &&
14142 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14143 return;
14144 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14145 // Checking declaration inside declare target region.
14146 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14147 isa<FunctionTemplateDecl>(D)) {
14148 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14149 Context, OMPDeclareTargetDeclAttr::MT_To);
14150 D->addAttr(A);
14151 if (ASTMutationListener *ML = Context.getASTMutationListener())
14152 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14153 }
14154 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014155 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014156 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014157 if (!E)
14158 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014159 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14160}
Samuel Antao661c0902016-05-26 17:39:58 +000014161
14162OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014163 CXXScopeSpec &MapperIdScopeSpec,
14164 DeclarationNameInfo &MapperId,
14165 const OMPVarListLocTy &Locs,
14166 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014167 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014168 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14169 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014170 if (MVLI.ProcessedVarList.empty())
14171 return nullptr;
14172
Michael Kruse01f670d2019-02-22 22:29:42 +000014173 return OMPToClause::Create(
14174 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14175 MVLI.VarComponents, MVLI.UDMapperList,
14176 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014177}
Samuel Antaoec172c62016-05-26 17:49:04 +000014178
14179OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014180 CXXScopeSpec &MapperIdScopeSpec,
14181 DeclarationNameInfo &MapperId,
14182 const OMPVarListLocTy &Locs,
14183 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014184 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014185 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14186 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014187 if (MVLI.ProcessedVarList.empty())
14188 return nullptr;
14189
Michael Kruse0336c752019-02-25 20:34:15 +000014190 return OMPFromClause::Create(
14191 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14192 MVLI.VarComponents, MVLI.UDMapperList,
14193 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014194}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014195
14196OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014197 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014198 MappableVarListInfo MVLI(VarList);
14199 SmallVector<Expr *, 8> PrivateCopies;
14200 SmallVector<Expr *, 8> Inits;
14201
Alexey Bataeve3727102018-04-18 15:57:46 +000014202 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014203 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14204 SourceLocation ELoc;
14205 SourceRange ERange;
14206 Expr *SimpleRefExpr = RefExpr;
14207 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14208 if (Res.second) {
14209 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014210 MVLI.ProcessedVarList.push_back(RefExpr);
14211 PrivateCopies.push_back(nullptr);
14212 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014213 }
14214 ValueDecl *D = Res.first;
14215 if (!D)
14216 continue;
14217
14218 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014219 Type = Type.getNonReferenceType().getUnqualifiedType();
14220
14221 auto *VD = dyn_cast<VarDecl>(D);
14222
14223 // Item should be a pointer or reference to pointer.
14224 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014225 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14226 << 0 << RefExpr->getSourceRange();
14227 continue;
14228 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014229
14230 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014231 auto VDPrivate =
14232 buildVarDecl(*this, ELoc, Type, D->getName(),
14233 D->hasAttrs() ? &D->getAttrs() : nullptr,
14234 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014235 if (VDPrivate->isInvalidDecl())
14236 continue;
14237
14238 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014239 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014240 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14241
14242 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014243 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014244 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014245 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14246 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014247 AddInitializerToDecl(VDPrivate,
14248 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014249 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014250
14251 // If required, build a capture to implement the privatization initialized
14252 // with the current list item value.
14253 DeclRefExpr *Ref = nullptr;
14254 if (!VD)
14255 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14256 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14257 PrivateCopies.push_back(VDPrivateRefExpr);
14258 Inits.push_back(VDInitRefExpr);
14259
14260 // We need to add a data sharing attribute for this variable to make sure it
14261 // is correctly captured. A variable that shows up in a use_device_ptr has
14262 // similar properties of a first private variable.
14263 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14264
14265 // Create a mappable component for the list item. List items in this clause
14266 // only need a component.
14267 MVLI.VarBaseDeclarations.push_back(D);
14268 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14269 MVLI.VarComponents.back().push_back(
14270 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014271 }
14272
Samuel Antaocc10b852016-07-28 14:23:26 +000014273 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014274 return nullptr;
14275
Samuel Antaocc10b852016-07-28 14:23:26 +000014276 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014277 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14278 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014279}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014280
14281OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014282 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014283 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014284 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014285 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014286 SourceLocation ELoc;
14287 SourceRange ERange;
14288 Expr *SimpleRefExpr = RefExpr;
14289 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14290 if (Res.second) {
14291 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014292 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014293 }
14294 ValueDecl *D = Res.first;
14295 if (!D)
14296 continue;
14297
14298 QualType Type = D->getType();
14299 // item should be a pointer or array or reference to pointer or array
14300 if (!Type.getNonReferenceType()->isPointerType() &&
14301 !Type.getNonReferenceType()->isArrayType()) {
14302 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14303 << 0 << RefExpr->getSourceRange();
14304 continue;
14305 }
Samuel Antao6890b092016-07-28 14:25:09 +000014306
14307 // Check if the declaration in the clause does not show up in any data
14308 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014309 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014310 if (isOpenMPPrivate(DVar.CKind)) {
14311 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14312 << getOpenMPClauseName(DVar.CKind)
14313 << getOpenMPClauseName(OMPC_is_device_ptr)
14314 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014315 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014316 continue;
14317 }
14318
Alexey Bataeve3727102018-04-18 15:57:46 +000014319 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014320 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014321 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014322 [&ConflictExpr](
14323 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14324 OpenMPClauseKind) -> bool {
14325 ConflictExpr = R.front().getAssociatedExpression();
14326 return true;
14327 })) {
14328 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14329 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14330 << ConflictExpr->getSourceRange();
14331 continue;
14332 }
14333
14334 // Store the components in the stack so that they can be used to check
14335 // against other clauses later on.
14336 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14337 DSAStack->addMappableExpressionComponents(
14338 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14339
14340 // Record the expression we've just processed.
14341 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14342
14343 // Create a mappable component for the list item. List items in this clause
14344 // only need a component. We use a null declaration to signal fields in
14345 // 'this'.
14346 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14347 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14348 "Unexpected device pointer expression!");
14349 MVLI.VarBaseDeclarations.push_back(
14350 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14351 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14352 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014353 }
14354
Samuel Antao6890b092016-07-28 14:25:09 +000014355 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014356 return nullptr;
14357
Michael Kruse4304e9d2019-02-19 16:38:20 +000014358 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14359 MVLI.VarBaseDeclarations,
14360 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014361}