blob: 32e493ed57cf6080068d2e614963f720620623cc [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 Bataeva495c642019-03-11 19:51:42 +0000150 /// List of globals marked as declare target link in this target region
151 /// (isOpenMPTargetExecutionDirective(Directive) == true).
152 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000153 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000154 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000155 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
156 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000157 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158 };
159
Alexey Bataeve3727102018-04-18 15:57:46 +0000160 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000161
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000162 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000163 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000164 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
165 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000166 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000167 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000168 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000169 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000170 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000171 /// true if all the vaiables in the target executable directives must be
172 /// captured by reference.
173 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000174 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000175
Alexey Bataeve3727102018-04-18 15:57:46 +0000176 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177
Alexey Bataeve3727102018-04-18 15:57:46 +0000178 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000180 /// Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000181 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000182
Alexey Bataev4b465392017-04-26 15:06:24 +0000183 bool isStackEmpty() const {
184 return Stack.empty() ||
185 Stack.back().second != CurrentNonCapturingFunctionScope ||
186 Stack.back().first.empty();
187 }
188
Kelvin Li1408f912018-09-26 04:28:39 +0000189 /// Vector of previously declared requires directives
190 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
191
Alexey Bataev758e55e2013-09-06 18:03:48 +0000192public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000193 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000194
Alexey Bataevaac108a2015-06-23 04:51:00 +0000195 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000196 OpenMPClauseKind getClauseParsingMode() const {
197 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
198 return ClauseKindMode;
199 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000200 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000201
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000202 bool isForceVarCapturing() const { return ForceCapturing; }
203 void setForceVarCapturing(bool V) { ForceCapturing = V; }
204
Alexey Bataev60705422018-10-30 15:50:12 +0000205 void setForceCaptureByReferenceInTargetExecutable(bool V) {
206 ForceCaptureByReferenceInTargetExecutable = V;
207 }
208 bool isForceCaptureByReferenceInTargetExecutable() const {
209 return ForceCaptureByReferenceInTargetExecutable;
210 }
211
Alexey Bataev758e55e2013-09-06 18:03:48 +0000212 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000213 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000214 if (Stack.empty() ||
215 Stack.back().second != CurrentNonCapturingFunctionScope)
216 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
217 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
218 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000219 }
220
221 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000222 assert(!Stack.back().first.empty() &&
223 "Data-sharing attributes stack is empty!");
224 Stack.back().first.pop_back();
225 }
226
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000227 /// Marks that we're started loop parsing.
228 void loopInit() {
229 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
230 "Expected loop-based directive.");
231 Stack.back().first.back().LoopStart = true;
232 }
233 /// Start capturing of the variables in the loop context.
234 void loopStart() {
235 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
236 "Expected loop-based directive.");
237 Stack.back().first.back().LoopStart = false;
238 }
239 /// true, if variables are captured, false otherwise.
240 bool isLoopStarted() const {
241 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
242 "Expected loop-based directive.");
243 return !Stack.back().first.back().LoopStart;
244 }
245 /// Marks (or clears) declaration as possibly loop counter.
246 void resetPossibleLoopCounter(const Decl *D = nullptr) {
247 Stack.back().first.back().PossiblyLoopCounter =
248 D ? D->getCanonicalDecl() : D;
249 }
250 /// Gets the possible loop counter decl.
251 const Decl *getPossiblyLoopCunter() const {
252 return Stack.back().first.back().PossiblyLoopCounter;
253 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000254 /// Start new OpenMP region stack in new non-capturing function.
255 void pushFunction() {
256 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
257 assert(!isa<CapturingScopeInfo>(CurFnScope));
258 CurrentNonCapturingFunctionScope = CurFnScope;
259 }
260 /// Pop region stack for non-capturing function.
261 void popFunction(const FunctionScopeInfo *OldFSI) {
262 if (!Stack.empty() && Stack.back().second == OldFSI) {
263 assert(Stack.back().first.empty());
264 Stack.pop_back();
265 }
266 CurrentNonCapturingFunctionScope = nullptr;
267 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
268 if (!isa<CapturingScopeInfo>(FSI)) {
269 CurrentNonCapturingFunctionScope = FSI;
270 break;
271 }
272 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273 }
274
Alexey Bataeve3727102018-04-18 15:57:46 +0000275 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000276 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000277 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000278 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000279 getCriticalWithHint(const DeclarationNameInfo &Name) const {
280 auto I = Criticals.find(Name.getAsString());
281 if (I != Criticals.end())
282 return I->second;
283 return std::make_pair(nullptr, llvm::APSInt());
284 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000285 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000286 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000287 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000288 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000289
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000290 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000291 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000292 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000293 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000294 /// \return The index of the loop control variable in the list of associated
295 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000296 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000297 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000298 /// parent region.
299 /// \return The index of the loop control variable in the list of associated
300 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000301 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000302 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000303 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000304 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000305
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000306 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000307 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000308 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000309
Alexey Bataevfa312f32017-07-21 18:48:21 +0000310 /// Adds additional information for the reduction items with the reduction id
311 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000312 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000313 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000314 /// Adds additional information for the reduction items with the reduction id
315 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000316 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000317 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000318 /// Returns the location and reduction operation from the innermost parent
319 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000320 const DSAVarData
321 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
322 BinaryOperatorKind &BOK,
323 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000324 /// Returns the location and reduction operation from the innermost parent
325 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000326 const DSAVarData
327 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
328 const Expr *&ReductionRef,
329 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000330 /// Return reduction reference expression for the current taskgroup.
331 Expr *getTaskgroupReductionRef() const {
332 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
333 "taskgroup reference expression requested for non taskgroup "
334 "directive.");
335 return Stack.back().first.back().TaskgroupReductionRef;
336 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000337 /// Checks if the given \p VD declaration is actually a taskgroup reduction
338 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000339 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000340 return Stack.back().first[Level].TaskgroupReductionRef &&
341 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
342 ->getDecl() == VD;
343 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000344
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000345 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000346 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000347 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000348 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000349 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000350 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000351 /// match specified \a CPred predicate in any directive which matches \a DPred
352 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000353 const DSAVarData
354 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
355 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
356 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000357 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000358 /// match specified \a CPred predicate in any innermost directive which
359 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000360 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000361 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000362 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
363 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000364 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000365 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000366 /// attributes which match specified \a CPred predicate at the specified
367 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000368 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000369 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000370 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000371
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000372 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000373 /// specified \a DPred predicate.
374 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000375 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000376 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000379 bool hasDirective(
380 const llvm::function_ref<bool(
381 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
382 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000383 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000384
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000385 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000386 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000387 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000388 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000389 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000390 OpenMPDirectiveKind getDirective(unsigned Level) const {
391 assert(!isStackEmpty() && "No directive at specified level.");
392 return Stack.back().first[Level].Directive;
393 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000394 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000395 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000396 if (isStackEmpty() || Stack.back().first.size() == 1)
397 return OMPD_unknown;
398 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000399 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000400
Kelvin Li1408f912018-09-26 04:28:39 +0000401 /// Add requires decl to internal vector
402 void addRequiresDecl(OMPRequiresDecl *RD) {
403 RequiresDecls.push_back(RD);
404 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000405
Kelvin Li1408f912018-09-26 04:28:39 +0000406 /// Checks for a duplicate clause amongst previously declared requires
407 /// directives
408 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
409 bool IsDuplicate = false;
410 for (OMPClause *CNew : ClauseList) {
411 for (const OMPRequiresDecl *D : RequiresDecls) {
412 for (const OMPClause *CPrev : D->clauselists()) {
413 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
414 SemaRef.Diag(CNew->getBeginLoc(),
415 diag::err_omp_requires_clause_redeclaration)
416 << getOpenMPClauseName(CNew->getClauseKind());
417 SemaRef.Diag(CPrev->getBeginLoc(),
418 diag::note_omp_requires_previous_clause)
419 << getOpenMPClauseName(CPrev->getClauseKind());
420 IsDuplicate = true;
421 }
422 }
423 }
424 }
425 return IsDuplicate;
426 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000427
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000428 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000429 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000430 assert(!isStackEmpty());
431 Stack.back().first.back().DefaultAttr = DSA_none;
432 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000433 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000434 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000435 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000436 assert(!isStackEmpty());
437 Stack.back().first.back().DefaultAttr = DSA_shared;
438 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000439 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000440 /// Set default data mapping attribute to 'tofrom:scalar'.
441 void setDefaultDMAToFromScalar(SourceLocation Loc) {
442 assert(!isStackEmpty());
443 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
444 Stack.back().first.back().DefaultMapAttrLoc = Loc;
445 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000446
447 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000448 return isStackEmpty() ? DSA_unspecified
449 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000450 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000451 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000452 return isStackEmpty() ? SourceLocation()
453 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000454 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000455 DefaultMapAttributes getDefaultDMA() const {
456 return isStackEmpty() ? DMA_unspecified
457 : Stack.back().first.back().DefaultMapAttr;
458 }
459 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
460 return Stack.back().first[Level].DefaultMapAttr;
461 }
462 SourceLocation getDefaultDMALocation() const {
463 return isStackEmpty() ? SourceLocation()
464 : Stack.back().first.back().DefaultMapAttrLoc;
465 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000466
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000467 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000468 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000469 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000470 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000471 }
472
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000473 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000474 void setOrderedRegion(bool IsOrdered, const Expr *Param,
475 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000476 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000477 if (IsOrdered)
478 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
479 else
480 Stack.back().first.back().OrderedRegion.reset();
481 }
482 /// Returns true, if region is ordered (has associated 'ordered' clause),
483 /// false - otherwise.
484 bool isOrderedRegion() const {
485 if (isStackEmpty())
486 return false;
487 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
488 }
489 /// Returns optional parameter for the ordered region.
490 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
491 if (isStackEmpty() ||
492 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
493 return std::make_pair(nullptr, nullptr);
494 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000495 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000496 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000497 /// 'ordered' clause), false - otherwise.
498 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000499 if (isStackEmpty() || Stack.back().first.size() == 1)
500 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000501 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000502 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000504 std::pair<const Expr *, OMPOrderedClause *>
505 getParentOrderedRegionParam() const {
506 if (isStackEmpty() || Stack.back().first.size() == 1 ||
507 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
508 return std::make_pair(nullptr, nullptr);
509 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000510 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000511 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000512 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000513 assert(!isStackEmpty());
514 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000515 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000517 /// 'nowait' clause), false - otherwise.
518 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000519 if (isStackEmpty() || Stack.back().first.size() == 1)
520 return false;
521 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000522 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000523 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000524 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000525 if (!isStackEmpty() && Stack.back().first.size() > 1) {
526 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
527 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
528 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000529 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000530 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000531 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000532 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000533 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000534
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000535 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000536 void setAssociatedLoops(unsigned Val) {
537 assert(!isStackEmpty());
538 Stack.back().first.back().AssociatedLoops = Val;
539 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000540 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000541 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000542 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000543 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000544
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000545 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000546 /// region.
547 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000548 if (!isStackEmpty() && Stack.back().first.size() > 1) {
549 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
550 TeamsRegionLoc;
551 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000552 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000553 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000554 bool hasInnerTeamsRegion() const {
555 return getInnerTeamsRegionLoc().isValid();
556 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000557 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000558 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000559 return isStackEmpty() ? SourceLocation()
560 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000561 }
562
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000563 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000564 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000565 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000566 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000567 return isStackEmpty() ? SourceLocation()
568 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000569 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000570
Samuel Antao4c8035b2016-12-12 18:00:20 +0000571 /// Do the check specified in \a Check to all component lists and return true
572 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000573 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000574 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000575 const llvm::function_ref<
576 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000577 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000578 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000579 if (isStackEmpty())
580 return false;
581 auto SI = Stack.back().first.rbegin();
582 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000583
584 if (SI == SE)
585 return false;
586
Alexey Bataeve3727102018-04-18 15:57:46 +0000587 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000588 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000589 else
590 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000591
592 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000593 auto MI = SI->MappedExprComponents.find(VD);
594 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000595 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
596 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000597 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000598 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000599 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000600 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000601 }
602
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000603 /// Do the check specified in \a Check to all component lists at a given level
604 /// and return true if any issue is found.
605 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000606 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000607 const llvm::function_ref<
608 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000609 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000610 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000611 if (isStackEmpty())
612 return false;
613
614 auto StartI = Stack.back().first.begin();
615 auto EndI = Stack.back().first.end();
616 if (std::distance(StartI, EndI) <= (int)Level)
617 return false;
618 std::advance(StartI, Level);
619
620 auto MI = StartI->MappedExprComponents.find(VD);
621 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000622 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
623 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000624 if (Check(L, MI->second.Kind))
625 return true;
626 return false;
627 }
628
Samuel Antao4c8035b2016-12-12 18:00:20 +0000629 /// Create a new mappable expression component list associated with a given
630 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000631 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000632 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000633 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
634 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000635 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000636 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000637 MappedExprComponentTy &MEC =
638 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000639 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000640 MEC.Components.resize(MEC.Components.size() + 1);
641 MEC.Components.back().append(Components.begin(), Components.end());
642 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000643 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000644
645 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000646 assert(!isStackEmpty());
647 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000648 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000649 void addDoacrossDependClause(OMPDependClause *C,
650 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000651 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000652 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000653 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000654 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000655 }
656 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
657 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000658 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000659 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000660 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000661 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000662 return llvm::make_range(Ref.begin(), Ref.end());
663 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000664 return llvm::make_range(StackElem.DoacrossDepends.end(),
665 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000666 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000667
668 // Store types of classes which have been explicitly mapped
669 void addMappedClassesQualTypes(QualType QT) {
670 SharingMapTy &StackElem = Stack.back().first.back();
671 StackElem.MappedClassesQualTypes.insert(QT);
672 }
673
674 // Return set of mapped classes types
675 bool isClassPreviouslyMapped(QualType QT) const {
676 const SharingMapTy &StackElem = Stack.back().first.back();
677 return StackElem.MappedClassesQualTypes.count(QT) != 0;
678 }
679
Alexey Bataeva495c642019-03-11 19:51:42 +0000680 /// Adds global declare target to the parent target region.
681 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
682 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
683 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
684 "Expected declare target link global.");
685 if (isStackEmpty())
686 return;
687 auto It = Stack.back().first.rbegin();
688 while (It != Stack.back().first.rend() &&
689 !isOpenMPTargetExecutionDirective(It->Directive))
690 ++It;
691 if (It != Stack.back().first.rend()) {
692 assert(isOpenMPTargetExecutionDirective(It->Directive) &&
693 "Expected target executable directive.");
694 It->DeclareTargetLinkVarDecls.push_back(E);
695 }
696 }
697
698 /// Returns the list of globals with declare target link if current directive
699 /// is target.
700 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
701 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
702 "Expected target executable directive.");
703 return Stack.back().first.back().DeclareTargetLinkVarDecls;
704 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000705};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000706
707bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
708 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
709}
710
711bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
712 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000713}
Alexey Bataeve3727102018-04-18 15:57:46 +0000714
Alexey Bataeved09d242014-05-28 05:53:51 +0000715} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000716
Alexey Bataeve3727102018-04-18 15:57:46 +0000717static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000718 if (const auto *FE = dyn_cast<FullExpr>(E))
719 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000720
Alexey Bataeve3727102018-04-18 15:57:46 +0000721 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000722 E = MTE->GetTemporaryExpr();
723
Alexey Bataeve3727102018-04-18 15:57:46 +0000724 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000725 E = Binder->getSubExpr();
726
Alexey Bataeve3727102018-04-18 15:57:46 +0000727 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000728 E = ICE->getSubExprAsWritten();
729 return E->IgnoreParens();
730}
731
Alexey Bataeve3727102018-04-18 15:57:46 +0000732static Expr *getExprAsWritten(Expr *E) {
733 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
734}
735
736static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
737 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
738 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000739 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000740 const auto *VD = dyn_cast<VarDecl>(D);
741 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000742 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000743 VD = VD->getCanonicalDecl();
744 D = VD;
745 } else {
746 assert(FD);
747 FD = FD->getCanonicalDecl();
748 D = FD;
749 }
750 return D;
751}
752
Alexey Bataeve3727102018-04-18 15:57:46 +0000753static ValueDecl *getCanonicalDecl(ValueDecl *D) {
754 return const_cast<ValueDecl *>(
755 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
756}
757
758DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
759 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000760 D = getCanonicalDecl(D);
761 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000762 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000763 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000764 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000765 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
766 // in a region but not in construct]
767 // File-scope or namespace-scope variables referenced in called routines
768 // in the region are shared unless they appear in a threadprivate
769 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000770 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000771 DVar.CKind = OMPC_shared;
772
773 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
774 // in a region but not in construct]
775 // Variables with static storage duration that are declared in called
776 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 if (VD && VD->hasGlobalStorage())
778 DVar.CKind = OMPC_shared;
779
780 // Non-static data members are shared by default.
781 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000782 DVar.CKind = OMPC_shared;
783
Alexey Bataev758e55e2013-09-06 18:03:48 +0000784 return DVar;
785 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000786
Alexey Bataevec3da872014-01-31 05:15:34 +0000787 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
788 // in a Construct, C/C++, predetermined, p.1]
789 // Variables with automatic storage duration that are declared in a scope
790 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000791 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
792 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000793 DVar.CKind = OMPC_private;
794 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000795 }
796
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000797 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000798 // Explicitly specified attributes and local variables with predetermined
799 // attributes.
800 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000801 const DSAInfo &Data = Iter->SharingMap.lookup(D);
802 DVar.RefExpr = Data.RefExpr.getPointer();
803 DVar.PrivateCopy = Data.PrivateCopy;
804 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000805 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000806 return DVar;
807 }
808
809 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
810 // in a Construct, C/C++, implicitly determined, p.1]
811 // In a parallel or task construct, the data-sharing attributes of these
812 // variables are determined by the default clause, if present.
813 switch (Iter->DefaultAttr) {
814 case DSA_shared:
815 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000816 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000817 return DVar;
818 case DSA_none:
819 return DVar;
820 case DSA_unspecified:
821 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
822 // in a Construct, implicitly determined, p.2]
823 // In a parallel construct, if no default clause is present, these
824 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000825 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000826 if (isOpenMPParallelDirective(DVar.DKind) ||
827 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000828 DVar.CKind = OMPC_shared;
829 return DVar;
830 }
831
832 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
833 // in a Construct, implicitly determined, p.4]
834 // In a task construct, if no default clause is present, a variable that in
835 // the enclosing context is determined to be shared by all implicit tasks
836 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000837 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000838 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000839 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000840 do {
841 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000842 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000843 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000844 // In a task construct, if no default clause is present, a variable
845 // whose data-sharing attribute is not determined by the rules above is
846 // firstprivate.
847 DVarTemp = getDSA(I, D);
848 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000849 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000850 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000851 return DVar;
852 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000853 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000854 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000855 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000856 return DVar;
857 }
858 }
859 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
860 // in a Construct, implicitly determined, p.3]
861 // For constructs other than task, if no default clause is present, these
862 // variables inherit their data-sharing attributes from the enclosing
863 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000864 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000865}
866
Alexey Bataeve3727102018-04-18 15:57:46 +0000867const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
868 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000869 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000870 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000871 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000872 auto It = StackElem.AlignedMap.find(D);
873 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000874 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000875 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000876 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000877 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000878 assert(It->second && "Unexpected nullptr expr in the aligned map");
879 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000880}
881
Alexey Bataeve3727102018-04-18 15:57:46 +0000882void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000883 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000884 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000885 SharingMapTy &StackElem = Stack.back().first.back();
886 StackElem.LCVMap.try_emplace(
887 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000888}
889
Alexey Bataeve3727102018-04-18 15:57:46 +0000890const DSAStackTy::LCDeclInfo
891DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000892 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000893 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000894 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000895 auto It = StackElem.LCVMap.find(D);
896 if (It != StackElem.LCVMap.end())
897 return It->second;
898 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000899}
900
Alexey Bataeve3727102018-04-18 15:57:46 +0000901const DSAStackTy::LCDeclInfo
902DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000903 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
904 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000905 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000906 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000907 auto It = StackElem.LCVMap.find(D);
908 if (It != StackElem.LCVMap.end())
909 return It->second;
910 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000911}
912
Alexey Bataeve3727102018-04-18 15:57:46 +0000913const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000914 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
915 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000916 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000917 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000918 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000919 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000920 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000921 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000922 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000923}
924
Alexey Bataeve3727102018-04-18 15:57:46 +0000925void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000926 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000927 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000928 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000929 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000930 Data.Attributes = A;
931 Data.RefExpr.setPointer(E);
932 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000933 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000934 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000935 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000936 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
937 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
938 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
939 (isLoopControlVariable(D).first && A == OMPC_private));
940 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
941 Data.RefExpr.setInt(/*IntVal=*/true);
942 return;
943 }
944 const bool IsLastprivate =
945 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
946 Data.Attributes = A;
947 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
948 Data.PrivateCopy = PrivateCopy;
949 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000950 DSAInfo &Data =
951 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000952 Data.Attributes = A;
953 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
954 Data.PrivateCopy = nullptr;
955 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000956 }
957}
958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000959/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000960static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000961 StringRef Name, const AttrVec *Attrs = nullptr,
962 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000963 DeclContext *DC = SemaRef.CurContext;
964 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
965 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000966 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000967 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
968 if (Attrs) {
969 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
970 I != E; ++I)
971 Decl->addAttr(*I);
972 }
973 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000974 if (OrigRef) {
975 Decl->addAttr(
976 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
977 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000978 return Decl;
979}
980
981static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
982 SourceLocation Loc,
983 bool RefersToCapture = false) {
984 D->setReferenced();
985 D->markUsed(S.Context);
986 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
987 SourceLocation(), D, RefersToCapture, Loc, Ty,
988 VK_LValue);
989}
990
Alexey Bataeve3727102018-04-18 15:57:46 +0000991void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000992 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000993 D = getCanonicalDecl(D);
994 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000995 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000996 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000997 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000998 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000999 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001000 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001001 "Additional reduction info may be specified only once for reduction "
1002 "items.");
1003 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001004 Expr *&TaskgroupReductionRef =
1005 Stack.back().first.back().TaskgroupReductionRef;
1006 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001007 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1008 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001009 TaskgroupReductionRef =
1010 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001011 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001012}
1013
Alexey Bataeve3727102018-04-18 15:57:46 +00001014void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001015 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001016 D = getCanonicalDecl(D);
1017 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001018 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001019 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001020 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001021 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001022 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001023 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001024 "Additional reduction info may be specified only once for reduction "
1025 "items.");
1026 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001027 Expr *&TaskgroupReductionRef =
1028 Stack.back().first.back().TaskgroupReductionRef;
1029 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001030 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1031 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001032 TaskgroupReductionRef =
1033 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001034 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001035}
1036
Alexey Bataeve3727102018-04-18 15:57:46 +00001037const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1038 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1039 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001040 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001041 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1042 if (Stack.back().first.empty())
1043 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001044 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1045 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001046 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001047 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001048 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001049 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001050 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001051 if (!ReductionData.ReductionOp ||
1052 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001053 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001054 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001055 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001056 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1057 "expression for the descriptor is not "
1058 "set.");
1059 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001060 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1061 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001062 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001063 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001064}
1065
Alexey Bataeve3727102018-04-18 15:57:46 +00001066const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1067 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1068 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001069 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001070 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1071 if (Stack.back().first.empty())
1072 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001073 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1074 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001075 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001076 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001077 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001078 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001079 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001080 if (!ReductionData.ReductionOp ||
1081 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001082 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001083 SR = ReductionData.ReductionRange;
1084 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001085 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1086 "expression for the descriptor is not "
1087 "set.");
1088 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001089 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1090 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001091 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001092 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001093}
1094
Alexey Bataeve3727102018-04-18 15:57:46 +00001095bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001096 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001097 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001098 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001099 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001100 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001101 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001102 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001103 if (I == E)
1104 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001105 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001106 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001107 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001108 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001109 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001111 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001112}
1113
Joel E. Dennyd2649292019-01-04 22:11:56 +00001114static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1115 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001116 bool *IsClassType = nullptr) {
1117 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001118 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001119 bool IsConstant = Type.isConstant(Context);
1120 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001121 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1122 ? Type->getAsCXXRecordDecl()
1123 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001124 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1125 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1126 RD = CTD->getTemplatedDecl();
1127 if (IsClassType)
1128 *IsClassType = RD;
1129 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1130 RD->hasDefinition() && RD->hasMutableFields());
1131}
1132
Joel E. Dennyd2649292019-01-04 22:11:56 +00001133static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1134 QualType Type, OpenMPClauseKind CKind,
1135 SourceLocation ELoc,
1136 bool AcceptIfMutable = true,
1137 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001138 ASTContext &Context = SemaRef.getASTContext();
1139 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001140 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1141 unsigned Diag = ListItemNotVar
1142 ? diag::err_omp_const_list_item
1143 : IsClassType ? diag::err_omp_const_not_mutable_variable
1144 : diag::err_omp_const_variable;
1145 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1146 if (!ListItemNotVar && D) {
1147 const VarDecl *VD = dyn_cast<VarDecl>(D);
1148 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1149 VarDecl::DeclarationOnly;
1150 SemaRef.Diag(D->getLocation(),
1151 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1152 << D;
1153 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001154 return true;
1155 }
1156 return false;
1157}
1158
Alexey Bataeve3727102018-04-18 15:57:46 +00001159const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1160 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001161 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001162 DSAVarData DVar;
1163
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001164 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001165 auto TI = Threadprivates.find(D);
1166 if (TI != Threadprivates.end()) {
1167 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001168 DVar.CKind = OMPC_threadprivate;
1169 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001170 }
1171 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001172 DVar.RefExpr = buildDeclRefExpr(
1173 SemaRef, VD, D->getType().getNonReferenceType(),
1174 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1175 DVar.CKind = OMPC_threadprivate;
1176 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001177 return DVar;
1178 }
1179 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1180 // in a Construct, C/C++, predetermined, p.1]
1181 // Variables appearing in threadprivate directives are threadprivate.
1182 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1183 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1184 SemaRef.getLangOpts().OpenMPUseTLS &&
1185 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1186 (VD && VD->getStorageClass() == SC_Register &&
1187 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1188 DVar.RefExpr = buildDeclRefExpr(
1189 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1190 DVar.CKind = OMPC_threadprivate;
1191 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1192 return DVar;
1193 }
1194 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1195 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1196 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001197 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001198 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1199 [](const SharingMapTy &Data) {
1200 return isOpenMPTargetExecutionDirective(Data.Directive);
1201 });
1202 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001203 iterator ParentIterTarget = std::next(IterTarget, 1);
1204 for (iterator Iter = Stack.back().first.rbegin();
1205 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001206 if (isOpenMPLocal(VD, Iter)) {
1207 DVar.RefExpr =
1208 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1209 D->getLocation());
1210 DVar.CKind = OMPC_threadprivate;
1211 return DVar;
1212 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001213 }
1214 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1215 auto DSAIter = IterTarget->SharingMap.find(D);
1216 if (DSAIter != IterTarget->SharingMap.end() &&
1217 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1218 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1219 DVar.CKind = OMPC_threadprivate;
1220 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001221 }
1222 iterator End = Stack.back().first.rend();
1223 if (!SemaRef.isOpenMPCapturedByRef(
1224 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001225 DVar.RefExpr =
1226 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1227 IterTarget->ConstructLoc);
1228 DVar.CKind = OMPC_threadprivate;
1229 return DVar;
1230 }
1231 }
1232 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001233 }
1234
Alexey Bataev4b465392017-04-26 15:06:24 +00001235 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001236 // Not in OpenMP execution region and top scope was already checked.
1237 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001238
Alexey Bataev758e55e2013-09-06 18:03:48 +00001239 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001240 // in a Construct, C/C++, predetermined, p.4]
1241 // Static data members are shared.
1242 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1243 // in a Construct, C/C++, predetermined, p.7]
1244 // Variables with static storage duration that are declared in a scope
1245 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001246 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001247 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001248 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001249 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001250 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001251
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001252 DVar.CKind = OMPC_shared;
1253 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001254 }
1255
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001256 // The predetermined shared attribute for const-qualified types having no
1257 // mutable members was removed after OpenMP 3.1.
1258 if (SemaRef.LangOpts.OpenMP <= 31) {
1259 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1260 // in a Construct, C/C++, predetermined, p.6]
1261 // Variables with const qualified type having no mutable member are
1262 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001263 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001264 // Variables with const-qualified type having no mutable member may be
1265 // listed in a firstprivate clause, even if they are static data members.
1266 DSAVarData DVarTemp = hasInnermostDSA(
1267 D,
1268 [](OpenMPClauseKind C) {
1269 return C == OMPC_firstprivate || C == OMPC_shared;
1270 },
1271 MatchesAlways, FromParent);
1272 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1273 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001274
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001275 DVar.CKind = OMPC_shared;
1276 return DVar;
1277 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001278 }
1279
Alexey Bataev758e55e2013-09-06 18:03:48 +00001280 // Explicitly specified attributes and local variables with predetermined
1281 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001282 iterator I = Stack.back().first.rbegin();
1283 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001284 if (FromParent && I != EndI)
1285 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001286 auto It = I->SharingMap.find(D);
1287 if (It != I->SharingMap.end()) {
1288 const DSAInfo &Data = It->getSecond();
1289 DVar.RefExpr = Data.RefExpr.getPointer();
1290 DVar.PrivateCopy = Data.PrivateCopy;
1291 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001292 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001293 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001294 }
1295
1296 return DVar;
1297}
1298
Alexey Bataeve3727102018-04-18 15:57:46 +00001299const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1300 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001301 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001302 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001303 return getDSA(I, D);
1304 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001305 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001306 iterator StartI = Stack.back().first.rbegin();
1307 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001308 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001309 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001310 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001311}
1312
Alexey Bataeve3727102018-04-18 15:57:46 +00001313const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001314DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001315 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1316 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001317 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001318 if (isStackEmpty())
1319 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001320 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001321 iterator I = Stack.back().first.rbegin();
1322 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001323 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001324 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001325 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001326 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001327 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001328 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001329 DSAVarData DVar = getDSA(NewI, D);
1330 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001331 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001332 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001333 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001334}
1335
Alexey Bataeve3727102018-04-18 15:57:46 +00001336const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001337 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1338 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001339 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001340 if (isStackEmpty())
1341 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001342 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001343 iterator StartI = Stack.back().first.rbegin();
1344 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001345 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001346 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001347 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001348 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001349 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001350 DSAVarData DVar = getDSA(NewI, D);
1351 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001352}
1353
Alexey Bataevaac108a2015-06-23 04:51:00 +00001354bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001355 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1356 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001357 if (isStackEmpty())
1358 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001359 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001360 auto StartI = Stack.back().first.begin();
1361 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001362 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001363 return false;
1364 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001365 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001366 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001367 I->getSecond().RefExpr.getPointer() &&
1368 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001369 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1370 return true;
1371 // Check predetermined rules for the loop control variables.
1372 auto LI = StartI->LCVMap.find(D);
1373 if (LI != StartI->LCVMap.end())
1374 return CPred(OMPC_private);
1375 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001376}
1377
Samuel Antao4be30e92015-10-02 17:14:03 +00001378bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001379 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1380 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001381 if (isStackEmpty())
1382 return false;
1383 auto StartI = Stack.back().first.begin();
1384 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001385 if (std::distance(StartI, EndI) <= (int)Level)
1386 return false;
1387 std::advance(StartI, Level);
1388 return DPred(StartI->Directive);
1389}
1390
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001391bool DSAStackTy::hasDirective(
1392 const llvm::function_ref<bool(OpenMPDirectiveKind,
1393 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001394 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001395 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001396 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001397 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001398 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001399 auto StartI = std::next(Stack.back().first.rbegin());
1400 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001401 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001402 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001403 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1404 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1405 return true;
1406 }
1407 return false;
1408}
1409
Alexey Bataev758e55e2013-09-06 18:03:48 +00001410void Sema::InitDataSharingAttributesStack() {
1411 VarDataSharingAttributesStack = new DSAStackTy(*this);
1412}
1413
1414#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1415
Alexey Bataev4b465392017-04-26 15:06:24 +00001416void Sema::pushOpenMPFunctionRegion() {
1417 DSAStack->pushFunction();
1418}
1419
1420void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1421 DSAStack->popFunction(OldFSI);
1422}
1423
Alexey Bataevc416e642019-02-08 18:02:25 +00001424static bool isOpenMPDeviceDelayedContext(Sema &S) {
1425 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1426 "Expected OpenMP device compilation.");
1427 return !S.isInOpenMPTargetExecutionDirective() &&
1428 !S.isInOpenMPDeclareTargetContext();
1429}
1430
1431/// Do we know that we will eventually codegen the given function?
1432static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1433 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1434 "Expected OpenMP device compilation.");
1435 // Templates are emitted when they're instantiated.
1436 if (FD->isDependentContext())
1437 return false;
1438
1439 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1440 FD->getCanonicalDecl()))
1441 return true;
1442
1443 // Otherwise, the function is known-emitted if it's in our set of
1444 // known-emitted functions.
1445 return S.DeviceKnownEmittedFns.count(FD) > 0;
1446}
1447
1448Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1449 unsigned DiagID) {
1450 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1451 "Expected OpenMP device compilation.");
1452 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1453 !isKnownEmitted(*this, getCurFunctionDecl()))
1454 ? DeviceDiagBuilder::K_Deferred
1455 : DeviceDiagBuilder::K_Immediate,
1456 Loc, DiagID, getCurFunctionDecl(), *this);
1457}
1458
1459void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1460 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1461 "Expected OpenMP device compilation.");
1462 assert(Callee && "Callee may not be null.");
1463 FunctionDecl *Caller = getCurFunctionDecl();
1464
1465 // If the caller is known-emitted, mark the callee as known-emitted.
1466 // Otherwise, mark the call in our call graph so we can traverse it later.
1467 if (!isOpenMPDeviceDelayedContext(*this) ||
1468 (Caller && isKnownEmitted(*this, Caller)))
1469 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1470 else if (Caller)
1471 DeviceCallGraph[Caller].insert({Callee, Loc});
1472}
1473
Alexey Bataev123ad192019-02-27 20:29:45 +00001474void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1475 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1476 "OpenMP device compilation mode is expected.");
1477 QualType Ty = E->getType();
1478 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1479 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1480 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1481 !Context.getTargetInfo().hasInt128Type()))
1482 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1483 << Ty << E->getSourceRange();
1484}
1485
Alexey Bataeve3727102018-04-18 15:57:46 +00001486bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001487 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1488
Alexey Bataeve3727102018-04-18 15:57:46 +00001489 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001490 bool IsByRef = true;
1491
1492 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001493 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001494 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001495
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001496 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001497 // This table summarizes how a given variable should be passed to the device
1498 // given its type and the clauses where it appears. This table is based on
1499 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1500 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1501 //
1502 // =========================================================================
1503 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1504 // | |(tofrom:scalar)| | pvt | | | |
1505 // =========================================================================
1506 // | scl | | | | - | | bycopy|
1507 // | scl | | - | x | - | - | bycopy|
1508 // | scl | | x | - | - | - | null |
1509 // | scl | x | | | - | | byref |
1510 // | scl | x | - | x | - | - | bycopy|
1511 // | scl | x | x | - | - | - | null |
1512 // | scl | | - | - | - | x | byref |
1513 // | scl | x | - | - | - | x | byref |
1514 //
1515 // | agg | n.a. | | | - | | byref |
1516 // | agg | n.a. | - | x | - | - | byref |
1517 // | agg | n.a. | x | - | - | - | null |
1518 // | agg | n.a. | - | - | - | x | byref |
1519 // | agg | n.a. | - | - | - | x[] | byref |
1520 //
1521 // | ptr | n.a. | | | - | | bycopy|
1522 // | ptr | n.a. | - | x | - | - | bycopy|
1523 // | ptr | n.a. | x | - | - | - | null |
1524 // | ptr | n.a. | - | - | - | x | byref |
1525 // | ptr | n.a. | - | - | - | x[] | bycopy|
1526 // | ptr | n.a. | - | - | x | | bycopy|
1527 // | ptr | n.a. | - | - | x | x | bycopy|
1528 // | ptr | n.a. | - | - | x | x[] | bycopy|
1529 // =========================================================================
1530 // Legend:
1531 // scl - scalar
1532 // ptr - pointer
1533 // agg - aggregate
1534 // x - applies
1535 // - - invalid in this combination
1536 // [] - mapped with an array section
1537 // byref - should be mapped by reference
1538 // byval - should be mapped by value
1539 // null - initialize a local variable to null on the device
1540 //
1541 // Observations:
1542 // - All scalar declarations that show up in a map clause have to be passed
1543 // by reference, because they may have been mapped in the enclosing data
1544 // environment.
1545 // - If the scalar value does not fit the size of uintptr, it has to be
1546 // passed by reference, regardless the result in the table above.
1547 // - For pointers mapped by value that have either an implicit map or an
1548 // array section, the runtime library may pass the NULL value to the
1549 // device instead of the value passed to it by the compiler.
1550
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001551 if (Ty->isReferenceType())
1552 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001553
1554 // Locate map clauses and see if the variable being captured is referred to
1555 // in any of those clauses. Here we only care about variables, not fields,
1556 // because fields are part of aggregates.
1557 bool IsVariableUsedInMapClause = false;
1558 bool IsVariableAssociatedWithSection = false;
1559
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001560 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001561 D, Level,
1562 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1563 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001564 MapExprComponents,
1565 OpenMPClauseKind WhereFoundClauseKind) {
1566 // Only the map clause information influences how a variable is
1567 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001568 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001569 if (WhereFoundClauseKind != OMPC_map)
1570 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001571
1572 auto EI = MapExprComponents.rbegin();
1573 auto EE = MapExprComponents.rend();
1574
1575 assert(EI != EE && "Invalid map expression!");
1576
1577 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1578 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1579
1580 ++EI;
1581 if (EI == EE)
1582 return false;
1583
1584 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1585 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1586 isa<MemberExpr>(EI->getAssociatedExpression())) {
1587 IsVariableAssociatedWithSection = true;
1588 // There is nothing more we need to know about this variable.
1589 return true;
1590 }
1591
1592 // Keep looking for more map info.
1593 return false;
1594 });
1595
1596 if (IsVariableUsedInMapClause) {
1597 // If variable is identified in a map clause it is always captured by
1598 // reference except if it is a pointer that is dereferenced somehow.
1599 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1600 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001601 // By default, all the data that has a scalar type is mapped by copy
1602 // (except for reduction variables).
1603 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001604 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1605 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001606 !Ty->isScalarType() ||
1607 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1608 DSAStack->hasExplicitDSA(
1609 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001610 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001611 }
1612
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001613 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001614 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001615 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1616 !Ty->isAnyPointerType()) ||
1617 !DSAStack->hasExplicitDSA(
1618 D,
1619 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1620 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001621 // If the variable is artificial and must be captured by value - try to
1622 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001623 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1624 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001625 }
1626
Samuel Antao86ace552016-04-27 22:40:57 +00001627 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001628 // and alignment, because the runtime library only deals with uintptr types.
1629 // If it does not fit the uintptr size, we need to pass the data by reference
1630 // instead.
1631 if (!IsByRef &&
1632 (Ctx.getTypeSizeInChars(Ty) >
1633 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001634 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001635 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001636 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001637
1638 return IsByRef;
1639}
1640
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001641unsigned Sema::getOpenMPNestingLevel() const {
1642 assert(getLangOpts().OpenMP);
1643 return DSAStack->getNestingLevel();
1644}
1645
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001646bool Sema::isInOpenMPTargetExecutionDirective() const {
1647 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1648 !DSAStack->isClauseParsingMode()) ||
1649 DSAStack->hasDirective(
1650 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1651 SourceLocation) -> bool {
1652 return isOpenMPTargetExecutionDirective(K);
1653 },
1654 false);
1655}
1656
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001657VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001658 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001659 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001660
1661 // If we are attempting to capture a global variable in a directive with
1662 // 'target' we return true so that this global is also mapped to the device.
1663 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001664 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001665 if (VD && !VD->hasLocalStorage()) {
1666 if (isInOpenMPDeclareTargetContext() &&
1667 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1668 // Try to mark variable as declare target if it is used in capturing
1669 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001670 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001671 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001672 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001673 } else if (isInOpenMPTargetExecutionDirective()) {
1674 // If the declaration is enclosed in a 'declare target' directive,
1675 // then it should not be captured.
1676 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001677 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001678 return nullptr;
1679 return VD;
1680 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001681 }
Alexey Bataev60705422018-10-30 15:50:12 +00001682 // Capture variables captured by reference in lambdas for target-based
1683 // directives.
1684 if (VD && !DSAStack->isClauseParsingMode()) {
1685 if (const auto *RD = VD->getType()
1686 .getCanonicalType()
1687 .getNonReferenceType()
1688 ->getAsCXXRecordDecl()) {
1689 bool SavedForceCaptureByReferenceInTargetExecutable =
1690 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1691 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001692 if (RD->isLambda()) {
1693 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1694 FieldDecl *ThisCapture;
1695 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001696 for (const LambdaCapture &LC : RD->captures()) {
1697 if (LC.getCaptureKind() == LCK_ByRef) {
1698 VarDecl *VD = LC.getCapturedVar();
1699 DeclContext *VDC = VD->getDeclContext();
1700 if (!VDC->Encloses(CurContext))
1701 continue;
1702 DSAStackTy::DSAVarData DVarPrivate =
1703 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1704 // Do not capture already captured variables.
1705 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1706 DVarPrivate.CKind == OMPC_unknown &&
1707 !DSAStack->checkMappableExprComponentListsForDecl(
1708 D, /*CurrentRegionOnly=*/true,
1709 [](OMPClauseMappableExprCommon::
1710 MappableExprComponentListRef,
1711 OpenMPClauseKind) { return true; }))
1712 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1713 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001714 QualType ThisTy = getCurrentThisType();
1715 if (!ThisTy.isNull() &&
1716 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1717 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001718 }
1719 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001720 }
Alexey Bataev60705422018-10-30 15:50:12 +00001721 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1722 SavedForceCaptureByReferenceInTargetExecutable);
1723 }
1724 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001725
Alexey Bataev48977c32015-08-04 08:10:48 +00001726 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1727 (!DSAStack->isClauseParsingMode() ||
1728 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001729 auto &&Info = DSAStack->isLoopControlVariable(D);
1730 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001731 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001732 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001733 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001734 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001735 DSAStackTy::DSAVarData DVarPrivate =
1736 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001737 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001738 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001739 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1740 [](OpenMPDirectiveKind) { return true; },
1741 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001742 if (DVarPrivate.CKind != OMPC_unknown)
1743 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001744 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001745 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001746}
1747
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001748void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1749 unsigned Level) const {
1750 SmallVector<OpenMPDirectiveKind, 4> Regions;
1751 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1752 FunctionScopesIndex -= Regions.size();
1753}
1754
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001755void Sema::startOpenMPLoop() {
1756 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1757 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1758 DSAStack->loopInit();
1759}
1760
Alexey Bataeve3727102018-04-18 15:57:46 +00001761bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001762 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001763 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1764 if (DSAStack->getAssociatedLoops() > 0 &&
1765 !DSAStack->isLoopStarted()) {
1766 DSAStack->resetPossibleLoopCounter(D);
1767 DSAStack->loopStart();
1768 return true;
1769 }
1770 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1771 DSAStack->isLoopControlVariable(D).first) &&
1772 !DSAStack->hasExplicitDSA(
1773 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1774 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1775 return true;
1776 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001777 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001778 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001779 (DSAStack->isClauseParsingMode() &&
1780 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001781 // Consider taskgroup reduction descriptor variable a private to avoid
1782 // possible capture in the region.
1783 (DSAStack->hasExplicitDirective(
1784 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1785 Level) &&
1786 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001787}
1788
Alexey Bataeve3727102018-04-18 15:57:46 +00001789void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1790 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001791 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1792 D = getCanonicalDecl(D);
1793 OpenMPClauseKind OMPC = OMPC_unknown;
1794 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1795 const unsigned NewLevel = I - 1;
1796 if (DSAStack->hasExplicitDSA(D,
1797 [&OMPC](const OpenMPClauseKind K) {
1798 if (isOpenMPPrivate(K)) {
1799 OMPC = K;
1800 return true;
1801 }
1802 return false;
1803 },
1804 NewLevel))
1805 break;
1806 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1807 D, NewLevel,
1808 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1809 OpenMPClauseKind) { return true; })) {
1810 OMPC = OMPC_map;
1811 break;
1812 }
1813 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1814 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001815 OMPC = OMPC_map;
1816 if (D->getType()->isScalarType() &&
1817 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1818 DefaultMapAttributes::DMA_tofrom_scalar)
1819 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001820 break;
1821 }
1822 }
1823 if (OMPC != OMPC_unknown)
1824 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1825}
1826
Alexey Bataeve3727102018-04-18 15:57:46 +00001827bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1828 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001829 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1830 // Return true if the current level is no longer enclosed in a target region.
1831
Alexey Bataeve3727102018-04-18 15:57:46 +00001832 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001833 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001834 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1835 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001836}
1837
Alexey Bataeved09d242014-05-28 05:53:51 +00001838void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001839
1840void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1841 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001842 Scope *CurScope, SourceLocation Loc) {
1843 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001844 PushExpressionEvaluationContext(
1845 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001846}
1847
Alexey Bataevaac108a2015-06-23 04:51:00 +00001848void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1849 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001850}
1851
Alexey Bataevaac108a2015-06-23 04:51:00 +00001852void Sema::EndOpenMPClause() {
1853 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001854}
1855
Alexey Bataev758e55e2013-09-06 18:03:48 +00001856void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001857 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1858 // A variable of class type (or array thereof) that appears in a lastprivate
1859 // clause requires an accessible, unambiguous default constructor for the
1860 // class type, unless the list item is also specified in a firstprivate
1861 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001862 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1863 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001864 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1865 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001866 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001867 if (DE->isValueDependent() || DE->isTypeDependent()) {
1868 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001869 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001870 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001871 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001872 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001873 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001874 const DSAStackTy::DSAVarData DVar =
1875 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001876 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001877 // Generate helper private variable and initialize it with the
1878 // default value. The address of the original variable is replaced
1879 // by the address of the new private variable in CodeGen. This new
1880 // variable is not added to IdResolver, so the code in the OpenMP
1881 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001882 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001883 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001884 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001885 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001886 if (VDPrivate->isInvalidDecl())
1887 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001888 PrivateCopies.push_back(buildDeclRefExpr(
1889 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001890 } else {
1891 // The variable is also a firstprivate, so initialization sequence
1892 // for private copy is generated already.
1893 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001894 }
1895 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001896 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001897 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001898 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001899 }
1900 }
1901 }
1902
Alexey Bataev758e55e2013-09-06 18:03:48 +00001903 DSAStack->pop();
1904 DiscardCleanupsInEvaluationContext();
1905 PopExpressionEvaluationContext();
1906}
1907
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001908static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1909 Expr *NumIterations, Sema &SemaRef,
1910 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001911
Alexey Bataeva769e072013-03-22 06:34:35 +00001912namespace {
1913
Alexey Bataeve3727102018-04-18 15:57:46 +00001914class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001915private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001916 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001917
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001918public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001919 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001920 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001921 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001922 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001923 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001924 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1925 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001926 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001927 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001928 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001929};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001930
Alexey Bataeve3727102018-04-18 15:57:46 +00001931class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001932private:
1933 Sema &SemaRef;
1934
1935public:
1936 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1937 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1938 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001939 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
1940 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001941 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1942 SemaRef.getCurScope());
1943 }
1944 return false;
1945 }
1946};
1947
Alexey Bataeved09d242014-05-28 05:53:51 +00001948} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001949
1950ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1951 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001952 const DeclarationNameInfo &Id,
1953 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001954 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1955 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1956
1957 if (Lookup.isAmbiguous())
1958 return ExprError();
1959
1960 VarDecl *VD;
1961 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001962 if (TypoCorrection Corrected = CorrectTypo(
1963 Id, LookupOrdinaryName, CurScope, nullptr,
1964 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001965 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001966 PDiag(Lookup.empty()
1967 ? diag::err_undeclared_var_use_suggest
1968 : diag::err_omp_expected_var_arg_suggest)
1969 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001970 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001971 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001972 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1973 : diag::err_omp_expected_var_arg)
1974 << Id.getName();
1975 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001976 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001977 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1978 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1979 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1980 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001981 }
1982 Lookup.suppressDiagnostics();
1983
1984 // OpenMP [2.9.2, Syntax, C/C++]
1985 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001986 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001987 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001988 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00001989 bool IsDecl =
1990 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001991 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001992 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1993 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001994 return ExprError();
1995 }
1996
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001997 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001998 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001999 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2000 // A threadprivate directive for file-scope variables must appear outside
2001 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002002 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2003 !getCurLexicalContext()->isTranslationUnit()) {
2004 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002005 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002006 bool IsDecl =
2007 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2008 Diag(VD->getLocation(),
2009 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2010 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002011 return ExprError();
2012 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002013 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2014 // A threadprivate directive for static class member variables must appear
2015 // in the class definition, in the same scope in which the member
2016 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002017 if (CanonicalVD->isStaticDataMember() &&
2018 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2019 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002020 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002021 bool IsDecl =
2022 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2023 Diag(VD->getLocation(),
2024 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2025 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002026 return ExprError();
2027 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002028 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2029 // A threadprivate directive for namespace-scope variables must appear
2030 // outside any definition or declaration other than the namespace
2031 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002032 if (CanonicalVD->getDeclContext()->isNamespace() &&
2033 (!getCurLexicalContext()->isFileContext() ||
2034 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2035 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002036 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002037 bool IsDecl =
2038 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2039 Diag(VD->getLocation(),
2040 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2041 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002042 return ExprError();
2043 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002044 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2045 // A threadprivate directive for static block-scope variables must appear
2046 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002047 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002048 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002049 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002050 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002051 bool IsDecl =
2052 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2053 Diag(VD->getLocation(),
2054 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2055 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002056 return ExprError();
2057 }
2058
2059 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2060 // A threadprivate directive must lexically precede all references to any
2061 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002062 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2063 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002064 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002065 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002066 return ExprError();
2067 }
2068
2069 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002070 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2071 SourceLocation(), VD,
2072 /*RefersToEnclosingVariableOrCapture=*/false,
2073 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002074}
2075
Alexey Bataeved09d242014-05-28 05:53:51 +00002076Sema::DeclGroupPtrTy
2077Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2078 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002079 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002080 CurContext->addDecl(D);
2081 return DeclGroupPtrTy::make(DeclGroupRef(D));
2082 }
David Blaikie0403cb12016-01-15 23:43:25 +00002083 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002084}
2085
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002086namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002087class LocalVarRefChecker final
2088 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002089 Sema &SemaRef;
2090
2091public:
2092 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002093 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002094 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002095 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002096 diag::err_omp_local_var_in_threadprivate_init)
2097 << E->getSourceRange();
2098 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2099 << VD << VD->getSourceRange();
2100 return true;
2101 }
2102 }
2103 return false;
2104 }
2105 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002106 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002107 if (Child && Visit(Child))
2108 return true;
2109 }
2110 return false;
2111 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002112 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002113};
2114} // namespace
2115
Alexey Bataeved09d242014-05-28 05:53:51 +00002116OMPThreadPrivateDecl *
2117Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002118 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002119 for (Expr *RefExpr : VarList) {
2120 auto *DE = cast<DeclRefExpr>(RefExpr);
2121 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002122 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002123
Alexey Bataev376b4a42016-02-09 09:41:09 +00002124 // Mark variable as used.
2125 VD->setReferenced();
2126 VD->markUsed(Context);
2127
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002128 QualType QType = VD->getType();
2129 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2130 // It will be analyzed later.
2131 Vars.push_back(DE);
2132 continue;
2133 }
2134
Alexey Bataeva769e072013-03-22 06:34:35 +00002135 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2136 // A threadprivate variable must not have an incomplete type.
2137 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002138 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002139 continue;
2140 }
2141
2142 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2143 // A threadprivate variable must not have a reference type.
2144 if (VD->getType()->isReferenceType()) {
2145 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002146 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2147 bool IsDecl =
2148 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2149 Diag(VD->getLocation(),
2150 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2151 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002152 continue;
2153 }
2154
Samuel Antaof8b50122015-07-13 22:54:53 +00002155 // Check if this is a TLS variable. If TLS is not being supported, produce
2156 // the corresponding diagnostic.
2157 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2158 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2159 getLangOpts().OpenMPUseTLS &&
2160 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002161 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2162 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002163 Diag(ILoc, diag::err_omp_var_thread_local)
2164 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002165 bool IsDecl =
2166 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2167 Diag(VD->getLocation(),
2168 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2169 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002170 continue;
2171 }
2172
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002173 // Check if initial value of threadprivate variable reference variable with
2174 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002175 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002176 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002177 if (Checker.Visit(Init))
2178 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002179 }
2180
Alexey Bataeved09d242014-05-28 05:53:51 +00002181 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002182 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002183 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2184 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002185 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002186 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002187 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002188 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002189 if (!Vars.empty()) {
2190 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2191 Vars);
2192 D->setAccess(AS_public);
2193 }
2194 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002195}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002196
Kelvin Li1408f912018-09-26 04:28:39 +00002197Sema::DeclGroupPtrTy
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002198Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
2199 DeclContext *Owner) {
2200 SmallVector<Expr *, 8> Vars;
2201 for (Expr *RefExpr : VarList) {
2202 auto *DE = cast<DeclRefExpr>(RefExpr);
2203 auto *VD = cast<VarDecl>(DE->getDecl());
2204
2205 // Check if this is a TLS variable or global register.
2206 if (VD->getTLSKind() != VarDecl::TLS_None ||
2207 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2208 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2209 !VD->isLocalVarDecl()))
2210 continue;
2211 // Do not apply for parameters.
2212 if (isa<ParmVarDecl>(VD))
2213 continue;
2214
2215 Vars.push_back(RefExpr);
2216 VD->addAttr(
2217 OMPAllocateDeclAttr::CreateImplicit(Context, DE->getSourceRange()));
2218 if (ASTMutationListener *ML = Context.getASTMutationListener())
2219 ML->DeclarationMarkedOpenMPAllocate(VD,
2220 VD->getAttr<OMPAllocateDeclAttr>());
2221 }
2222 if (Vars.empty())
2223 return nullptr;
2224 if (!Owner)
2225 Owner = getCurLexicalContext();
2226 OMPAllocateDecl *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars);
2227 D->setAccess(AS_public);
2228 Owner->addDecl(D);
2229 return DeclGroupPtrTy::make(DeclGroupRef(D));
2230}
2231
2232Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002233Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2234 ArrayRef<OMPClause *> ClauseList) {
2235 OMPRequiresDecl *D = nullptr;
2236 if (!CurContext->isFileContext()) {
2237 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2238 } else {
2239 D = CheckOMPRequiresDecl(Loc, ClauseList);
2240 if (D) {
2241 CurContext->addDecl(D);
2242 DSAStack->addRequiresDecl(D);
2243 }
2244 }
2245 return DeclGroupPtrTy::make(DeclGroupRef(D));
2246}
2247
2248OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2249 ArrayRef<OMPClause *> ClauseList) {
2250 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2251 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2252 ClauseList);
2253 return nullptr;
2254}
2255
Alexey Bataeve3727102018-04-18 15:57:46 +00002256static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2257 const ValueDecl *D,
2258 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002259 bool IsLoopIterVar = false) {
2260 if (DVar.RefExpr) {
2261 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2262 << getOpenMPClauseName(DVar.CKind);
2263 return;
2264 }
2265 enum {
2266 PDSA_StaticMemberShared,
2267 PDSA_StaticLocalVarShared,
2268 PDSA_LoopIterVarPrivate,
2269 PDSA_LoopIterVarLinear,
2270 PDSA_LoopIterVarLastprivate,
2271 PDSA_ConstVarShared,
2272 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002273 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002274 PDSA_LocalVarPrivate,
2275 PDSA_Implicit
2276 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002277 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002278 auto ReportLoc = D->getLocation();
2279 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002280 if (IsLoopIterVar) {
2281 if (DVar.CKind == OMPC_private)
2282 Reason = PDSA_LoopIterVarPrivate;
2283 else if (DVar.CKind == OMPC_lastprivate)
2284 Reason = PDSA_LoopIterVarLastprivate;
2285 else
2286 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002287 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2288 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002289 Reason = PDSA_TaskVarFirstprivate;
2290 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002291 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002292 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002293 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002294 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002295 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002296 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002297 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002298 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002299 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002300 ReportHint = true;
2301 Reason = PDSA_LocalVarPrivate;
2302 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002303 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002304 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002305 << Reason << ReportHint
2306 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2307 } else if (DVar.ImplicitDSALoc.isValid()) {
2308 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2309 << getOpenMPClauseName(DVar.CKind);
2310 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002311}
2312
Alexey Bataev758e55e2013-09-06 18:03:48 +00002313namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002314class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002315 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002316 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002317 bool ErrorFound = false;
2318 CapturedStmt *CS = nullptr;
2319 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2320 llvm::SmallVector<Expr *, 4> ImplicitMap;
2321 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2322 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002323
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002324 void VisitSubCaptures(OMPExecutableDirective *S) {
2325 // Check implicitly captured variables.
2326 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2327 return;
2328 for (const CapturedStmt::Capture &Cap :
2329 S->getInnermostCapturedStmt()->captures()) {
2330 if (!Cap.capturesVariable())
2331 continue;
2332 VarDecl *VD = Cap.getCapturedVar();
2333 // Do not try to map the variable if it or its sub-component was mapped
2334 // already.
2335 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2336 Stack->checkMappableExprComponentListsForDecl(
2337 VD, /*CurrentRegionOnly=*/true,
2338 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2339 OpenMPClauseKind) { return true; }))
2340 continue;
2341 DeclRefExpr *DRE = buildDeclRefExpr(
2342 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2343 Cap.getLocation(), /*RefersToCapture=*/true);
2344 Visit(DRE);
2345 }
2346 }
2347
Alexey Bataev758e55e2013-09-06 18:03:48 +00002348public:
2349 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002350 if (E->isTypeDependent() || E->isValueDependent() ||
2351 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2352 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002353 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002354 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002355 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002356 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002357 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002358
Alexey Bataeve3727102018-04-18 15:57:46 +00002359 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002360 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002361 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002362 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002363
Alexey Bataevafe50572017-10-06 17:00:28 +00002364 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002365 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002366 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002367 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2368 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002369 return;
2370
Alexey Bataeve3727102018-04-18 15:57:46 +00002371 SourceLocation ELoc = E->getExprLoc();
2372 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002373 // The default(none) clause requires that each variable that is referenced
2374 // in the construct, and does not have a predetermined data-sharing
2375 // attribute, must have its data-sharing attribute explicitly determined
2376 // by being listed in a data-sharing attribute clause.
2377 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002378 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002379 VarsWithInheritedDSA.count(VD) == 0) {
2380 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002381 return;
2382 }
2383
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002384 if (isOpenMPTargetExecutionDirective(DKind) &&
2385 !Stack->isLoopControlVariable(VD).first) {
2386 if (!Stack->checkMappableExprComponentListsForDecl(
2387 VD, /*CurrentRegionOnly=*/true,
2388 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2389 StackComponents,
2390 OpenMPClauseKind) {
2391 // Variable is used if it has been marked as an array, array
2392 // section or the variable iself.
2393 return StackComponents.size() == 1 ||
2394 std::all_of(
2395 std::next(StackComponents.rbegin()),
2396 StackComponents.rend(),
2397 [](const OMPClauseMappableExprCommon::
2398 MappableComponent &MC) {
2399 return MC.getAssociatedDeclaration() ==
2400 nullptr &&
2401 (isa<OMPArraySectionExpr>(
2402 MC.getAssociatedExpression()) ||
2403 isa<ArraySubscriptExpr>(
2404 MC.getAssociatedExpression()));
2405 });
2406 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002407 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002408 // By default lambdas are captured as firstprivates.
2409 if (const auto *RD =
2410 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002411 IsFirstprivate = RD->isLambda();
2412 IsFirstprivate =
2413 IsFirstprivate ||
2414 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002415 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002416 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002417 ImplicitFirstprivate.emplace_back(E);
2418 else
2419 ImplicitMap.emplace_back(E);
2420 return;
2421 }
2422 }
2423
Alexey Bataev758e55e2013-09-06 18:03:48 +00002424 // OpenMP [2.9.3.6, Restrictions, p.2]
2425 // A list item that appears in a reduction clause of the innermost
2426 // enclosing worksharing or parallel construct may not be accessed in an
2427 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002428 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002429 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2430 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002431 return isOpenMPParallelDirective(K) ||
2432 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2433 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002434 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002435 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002436 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002437 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002438 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002439 return;
2440 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002441
2442 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002443 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002444 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002445 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002446 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002447 return;
2448 }
2449
2450 // Store implicitly used globals with declare target link for parent
2451 // target.
2452 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2453 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2454 Stack->addToParentTargetRegionLinkGlobals(E);
2455 return;
2456 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002457 }
2458 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002459 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002460 if (E->isTypeDependent() || E->isValueDependent() ||
2461 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2462 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002463 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002464 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002465 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002466 if (!FD)
2467 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002468 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002469 // Check if the variable has explicit DSA set and stop analysis if it
2470 // so.
2471 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2472 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002473
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002474 if (isOpenMPTargetExecutionDirective(DKind) &&
2475 !Stack->isLoopControlVariable(FD).first &&
2476 !Stack->checkMappableExprComponentListsForDecl(
2477 FD, /*CurrentRegionOnly=*/true,
2478 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2479 StackComponents,
2480 OpenMPClauseKind) {
2481 return isa<CXXThisExpr>(
2482 cast<MemberExpr>(
2483 StackComponents.back().getAssociatedExpression())
2484 ->getBase()
2485 ->IgnoreParens());
2486 })) {
2487 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2488 // A bit-field cannot appear in a map clause.
2489 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002490 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002491 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002492
2493 // Check to see if the member expression is referencing a class that
2494 // has already been explicitly mapped
2495 if (Stack->isClassPreviouslyMapped(TE->getType()))
2496 return;
2497
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002498 ImplicitMap.emplace_back(E);
2499 return;
2500 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002501
Alexey Bataeve3727102018-04-18 15:57:46 +00002502 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002503 // OpenMP [2.9.3.6, Restrictions, p.2]
2504 // A list item that appears in a reduction clause of the innermost
2505 // enclosing worksharing or parallel construct may not be accessed in
2506 // an explicit task.
2507 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002508 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2509 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002510 return isOpenMPParallelDirective(K) ||
2511 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2512 },
2513 /*FromParent=*/true);
2514 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2515 ErrorFound = true;
2516 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002517 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002518 return;
2519 }
2520
2521 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002522 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002523 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002524 !Stack->isLoopControlVariable(FD).first) {
2525 // Check if there is a captured expression for the current field in the
2526 // region. Do not mark it as firstprivate unless there is no captured
2527 // expression.
2528 // TODO: try to make it firstprivate.
2529 if (DVar.CKind != OMPC_unknown)
2530 ImplicitFirstprivate.push_back(E);
2531 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002532 return;
2533 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002534 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002535 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002536 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002537 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002538 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002539 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002540 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2541 if (!Stack->checkMappableExprComponentListsForDecl(
2542 VD, /*CurrentRegionOnly=*/true,
2543 [&CurComponents](
2544 OMPClauseMappableExprCommon::MappableExprComponentListRef
2545 StackComponents,
2546 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002547 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002548 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002549 for (const auto &SC : llvm::reverse(StackComponents)) {
2550 // Do both expressions have the same kind?
2551 if (CCI->getAssociatedExpression()->getStmtClass() !=
2552 SC.getAssociatedExpression()->getStmtClass())
2553 if (!(isa<OMPArraySectionExpr>(
2554 SC.getAssociatedExpression()) &&
2555 isa<ArraySubscriptExpr>(
2556 CCI->getAssociatedExpression())))
2557 return false;
2558
Alexey Bataeve3727102018-04-18 15:57:46 +00002559 const Decl *CCD = CCI->getAssociatedDeclaration();
2560 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002561 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2562 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2563 if (SCD != CCD)
2564 return false;
2565 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002566 if (CCI == CCE)
2567 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002568 }
2569 return true;
2570 })) {
2571 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002572 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002573 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002574 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002575 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002576 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002577 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002578 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002579 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002580 // for task|target directives.
2581 // Skip analysis of arguments of implicitly defined map clause for target
2582 // directives.
2583 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2584 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002585 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002586 if (CC)
2587 Visit(CC);
2588 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002589 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002590 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002591 // Check implicitly captured variables.
2592 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002593 }
2594 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002595 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002596 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002597 // Check implicitly captured variables in the task-based directives to
2598 // check if they must be firstprivatized.
2599 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002600 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002601 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002602 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002603
Alexey Bataeve3727102018-04-18 15:57:46 +00002604 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002605 ArrayRef<Expr *> getImplicitFirstprivate() const {
2606 return ImplicitFirstprivate;
2607 }
2608 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002609 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002610 return VarsWithInheritedDSA;
2611 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002612
Alexey Bataev7ff55242014-06-19 09:13:45 +00002613 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002614 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2615 // Process declare target link variables for the target directives.
2616 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2617 for (DeclRefExpr *E : Stack->getLinkGlobals())
2618 Visit(E);
2619 }
2620 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002621};
Alexey Bataeved09d242014-05-28 05:53:51 +00002622} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002623
Alexey Bataevbae9a792014-06-27 10:37:06 +00002624void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002625 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002626 case OMPD_parallel:
2627 case OMPD_parallel_for:
2628 case OMPD_parallel_for_simd:
2629 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002630 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002631 case OMPD_teams_distribute:
2632 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002633 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002634 QualType KmpInt32PtrTy =
2635 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002636 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002637 std::make_pair(".global_tid.", KmpInt32PtrTy),
2638 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2639 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002640 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002641 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2642 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002643 break;
2644 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002645 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002646 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002647 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002648 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002649 case OMPD_target_teams_distribute:
2650 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002651 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2652 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2653 QualType KmpInt32PtrTy =
2654 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2655 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002656 FunctionProtoType::ExtProtoInfo EPI;
2657 EPI.Variadic = true;
2658 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2659 Sema::CapturedParamNameType Params[] = {
2660 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002661 std::make_pair(".part_id.", KmpInt32PtrTy),
2662 std::make_pair(".privates.", VoidPtrTy),
2663 std::make_pair(
2664 ".copy_fn.",
2665 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002666 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2667 std::make_pair(StringRef(), QualType()) // __context with shared vars
2668 };
2669 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2670 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002671 // Mark this captured region as inlined, because we don't use outlined
2672 // function directly.
2673 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2674 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002675 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002676 Sema::CapturedParamNameType ParamsTarget[] = {
2677 std::make_pair(StringRef(), QualType()) // __context with shared vars
2678 };
2679 // Start a captured region for 'target' with no implicit parameters.
2680 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2681 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002682 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002683 std::make_pair(".global_tid.", KmpInt32PtrTy),
2684 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2685 std::make_pair(StringRef(), QualType()) // __context with shared vars
2686 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002687 // Start a captured region for 'teams' or 'parallel'. Both regions have
2688 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002689 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002690 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002691 break;
2692 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002693 case OMPD_target:
2694 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002695 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2696 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2697 QualType KmpInt32PtrTy =
2698 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2699 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002700 FunctionProtoType::ExtProtoInfo EPI;
2701 EPI.Variadic = true;
2702 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2703 Sema::CapturedParamNameType Params[] = {
2704 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002705 std::make_pair(".part_id.", KmpInt32PtrTy),
2706 std::make_pair(".privates.", VoidPtrTy),
2707 std::make_pair(
2708 ".copy_fn.",
2709 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002710 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2711 std::make_pair(StringRef(), QualType()) // __context with shared vars
2712 };
2713 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2714 Params);
2715 // Mark this captured region as inlined, because we don't use outlined
2716 // function directly.
2717 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2718 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002719 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002720 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2721 std::make_pair(StringRef(), QualType()));
2722 break;
2723 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002724 case OMPD_simd:
2725 case OMPD_for:
2726 case OMPD_for_simd:
2727 case OMPD_sections:
2728 case OMPD_section:
2729 case OMPD_single:
2730 case OMPD_master:
2731 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002732 case OMPD_taskgroup:
2733 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002734 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002735 case OMPD_ordered:
2736 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002737 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002738 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002739 std::make_pair(StringRef(), QualType()) // __context with shared vars
2740 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002741 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2742 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002743 break;
2744 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002745 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002746 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2747 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2748 QualType KmpInt32PtrTy =
2749 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2750 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002751 FunctionProtoType::ExtProtoInfo EPI;
2752 EPI.Variadic = true;
2753 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002754 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002755 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002756 std::make_pair(".part_id.", KmpInt32PtrTy),
2757 std::make_pair(".privates.", VoidPtrTy),
2758 std::make_pair(
2759 ".copy_fn.",
2760 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002761 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002762 std::make_pair(StringRef(), QualType()) // __context with shared vars
2763 };
2764 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2765 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002766 // Mark this captured region as inlined, because we don't use outlined
2767 // function directly.
2768 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2769 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002770 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002771 break;
2772 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002773 case OMPD_taskloop:
2774 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002775 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002776 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2777 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002778 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002779 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2780 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002781 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002782 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2783 .withConst();
2784 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2785 QualType KmpInt32PtrTy =
2786 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2787 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002788 FunctionProtoType::ExtProtoInfo EPI;
2789 EPI.Variadic = true;
2790 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002791 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002792 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002793 std::make_pair(".part_id.", KmpInt32PtrTy),
2794 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002795 std::make_pair(
2796 ".copy_fn.",
2797 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2798 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2799 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002800 std::make_pair(".ub.", KmpUInt64Ty),
2801 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002802 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002803 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002804 std::make_pair(StringRef(), QualType()) // __context with shared vars
2805 };
2806 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2807 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002808 // Mark this captured region as inlined, because we don't use outlined
2809 // function directly.
2810 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2811 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002812 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002813 break;
2814 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002815 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002816 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002817 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002818 QualType KmpInt32PtrTy =
2819 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2820 Sema::CapturedParamNameType Params[] = {
2821 std::make_pair(".global_tid.", KmpInt32PtrTy),
2822 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002823 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2824 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002825 std::make_pair(StringRef(), QualType()) // __context with shared vars
2826 };
2827 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2828 Params);
2829 break;
2830 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002831 case OMPD_target_teams_distribute_parallel_for:
2832 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002833 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002834 QualType KmpInt32PtrTy =
2835 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002836 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002837
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002838 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002839 FunctionProtoType::ExtProtoInfo EPI;
2840 EPI.Variadic = true;
2841 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2842 Sema::CapturedParamNameType Params[] = {
2843 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002844 std::make_pair(".part_id.", KmpInt32PtrTy),
2845 std::make_pair(".privates.", VoidPtrTy),
2846 std::make_pair(
2847 ".copy_fn.",
2848 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002849 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2850 std::make_pair(StringRef(), QualType()) // __context with shared vars
2851 };
2852 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2853 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002854 // Mark this captured region as inlined, because we don't use outlined
2855 // function directly.
2856 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2857 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002858 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002859 Sema::CapturedParamNameType ParamsTarget[] = {
2860 std::make_pair(StringRef(), QualType()) // __context with shared vars
2861 };
2862 // Start a captured region for 'target' with no implicit parameters.
2863 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2864 ParamsTarget);
2865
2866 Sema::CapturedParamNameType ParamsTeams[] = {
2867 std::make_pair(".global_tid.", KmpInt32PtrTy),
2868 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2869 std::make_pair(StringRef(), QualType()) // __context with shared vars
2870 };
2871 // Start a captured region for 'target' with no implicit parameters.
2872 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2873 ParamsTeams);
2874
2875 Sema::CapturedParamNameType ParamsParallel[] = {
2876 std::make_pair(".global_tid.", KmpInt32PtrTy),
2877 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002878 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2879 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002880 std::make_pair(StringRef(), QualType()) // __context with shared vars
2881 };
2882 // Start a captured region for 'teams' or 'parallel'. Both regions have
2883 // the same implicit parameters.
2884 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2885 ParamsParallel);
2886 break;
2887 }
2888
Alexey Bataev46506272017-12-05 17:41:34 +00002889 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002890 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002891 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002892 QualType KmpInt32PtrTy =
2893 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2894
2895 Sema::CapturedParamNameType ParamsTeams[] = {
2896 std::make_pair(".global_tid.", KmpInt32PtrTy),
2897 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2898 std::make_pair(StringRef(), QualType()) // __context with shared vars
2899 };
2900 // Start a captured region for 'target' with no implicit parameters.
2901 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2902 ParamsTeams);
2903
2904 Sema::CapturedParamNameType ParamsParallel[] = {
2905 std::make_pair(".global_tid.", KmpInt32PtrTy),
2906 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002907 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2908 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00002909 std::make_pair(StringRef(), QualType()) // __context with shared vars
2910 };
2911 // Start a captured region for 'teams' or 'parallel'. Both regions have
2912 // the same implicit parameters.
2913 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2914 ParamsParallel);
2915 break;
2916 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002917 case OMPD_target_update:
2918 case OMPD_target_enter_data:
2919 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002920 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2921 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2922 QualType KmpInt32PtrTy =
2923 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2924 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00002925 FunctionProtoType::ExtProtoInfo EPI;
2926 EPI.Variadic = true;
2927 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2928 Sema::CapturedParamNameType Params[] = {
2929 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002930 std::make_pair(".part_id.", KmpInt32PtrTy),
2931 std::make_pair(".privates.", VoidPtrTy),
2932 std::make_pair(
2933 ".copy_fn.",
2934 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00002935 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2936 std::make_pair(StringRef(), QualType()) // __context with shared vars
2937 };
2938 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2939 Params);
2940 // Mark this captured region as inlined, because we don't use outlined
2941 // function directly.
2942 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2943 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002944 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00002945 break;
2946 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002947 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002948 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002949 case OMPD_taskyield:
2950 case OMPD_barrier:
2951 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002952 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002953 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002954 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002955 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00002956 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002957 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002958 case OMPD_declare_target:
2959 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00002960 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00002961 llvm_unreachable("OpenMP Directive is not allowed");
2962 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002963 llvm_unreachable("Unknown OpenMP directive");
2964 }
2965}
2966
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002967int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2968 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2969 getOpenMPCaptureRegions(CaptureRegions, DKind);
2970 return CaptureRegions.size();
2971}
2972
Alexey Bataev3392d762016-02-16 11:18:12 +00002973static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002974 Expr *CaptureExpr, bool WithInit,
2975 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002976 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002977 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002978 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002979 QualType Ty = Init->getType();
2980 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002981 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002982 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002983 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002984 Ty = C.getPointerType(Ty);
2985 ExprResult Res =
2986 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2987 if (!Res.isUsable())
2988 return nullptr;
2989 Init = Res.get();
2990 }
Alexey Bataev61205072016-03-02 04:57:40 +00002991 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002992 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002993 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002994 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002995 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00002996 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00002997 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002998 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002999 return CED;
3000}
3001
Alexey Bataev61205072016-03-02 04:57:40 +00003002static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3003 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003004 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003005 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003006 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003007 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003008 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3009 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003010 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003011 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003012}
3013
Alexey Bataev5a3af132016-03-29 08:58:54 +00003014static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003015 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003016 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003017 OMPCapturedExprDecl *CD = buildCaptureDecl(
3018 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3019 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003020 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3021 CaptureExpr->getExprLoc());
3022 }
3023 ExprResult Res = Ref;
3024 if (!S.getLangOpts().CPlusPlus &&
3025 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003026 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003027 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003028 if (!Res.isUsable())
3029 return ExprError();
3030 }
3031 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003032}
3033
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003034namespace {
3035// OpenMP directives parsed in this section are represented as a
3036// CapturedStatement with an associated statement. If a syntax error
3037// is detected during the parsing of the associated statement, the
3038// compiler must abort processing and close the CapturedStatement.
3039//
3040// Combined directives such as 'target parallel' have more than one
3041// nested CapturedStatements. This RAII ensures that we unwind out
3042// of all the nested CapturedStatements when an error is found.
3043class CaptureRegionUnwinderRAII {
3044private:
3045 Sema &S;
3046 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003047 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003048
3049public:
3050 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3051 OpenMPDirectiveKind DKind)
3052 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3053 ~CaptureRegionUnwinderRAII() {
3054 if (ErrorFound) {
3055 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3056 while (--ThisCaptureLevel >= 0)
3057 S.ActOnCapturedRegionError();
3058 }
3059 }
3060};
3061} // namespace
3062
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003063StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3064 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003065 bool ErrorFound = false;
3066 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3067 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003068 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003069 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003070 return StmtError();
3071 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003072
Alexey Bataev2ba67042017-11-28 21:11:44 +00003073 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3074 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003075 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003076 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003077 SmallVector<const OMPLinearClause *, 4> LCs;
3078 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003079 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003080 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003081 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3082 Clause->getClauseKind() == OMPC_in_reduction) {
3083 // Capture taskgroup task_reduction descriptors inside the tasking regions
3084 // with the corresponding in_reduction items.
3085 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003086 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003087 if (E)
3088 MarkDeclarationsReferencedInExpr(E);
3089 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003090 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003091 Clause->getClauseKind() == OMPC_copyprivate ||
3092 (getLangOpts().OpenMPUseTLS &&
3093 getASTContext().getTargetInfo().isTLSSupported() &&
3094 Clause->getClauseKind() == OMPC_copyin)) {
3095 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003096 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003097 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003098 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003099 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003100 }
3101 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003102 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003103 } else if (CaptureRegions.size() > 1 ||
3104 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003105 if (auto *C = OMPClauseWithPreInit::get(Clause))
3106 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003107 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003108 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003109 MarkDeclarationsReferencedInExpr(E);
3110 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003111 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003112 if (Clause->getClauseKind() == OMPC_schedule)
3113 SC = cast<OMPScheduleClause>(Clause);
3114 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003115 OC = cast<OMPOrderedClause>(Clause);
3116 else if (Clause->getClauseKind() == OMPC_linear)
3117 LCs.push_back(cast<OMPLinearClause>(Clause));
3118 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003119 // OpenMP, 2.7.1 Loop Construct, Restrictions
3120 // The nonmonotonic modifier cannot be specified if an ordered clause is
3121 // specified.
3122 if (SC &&
3123 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3124 SC->getSecondScheduleModifier() ==
3125 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3126 OC) {
3127 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3128 ? SC->getFirstScheduleModifierLoc()
3129 : SC->getSecondScheduleModifierLoc(),
3130 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003131 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003132 ErrorFound = true;
3133 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003134 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003135 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003136 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003137 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003138 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003139 ErrorFound = true;
3140 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003141 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3142 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3143 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003144 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003145 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3146 ErrorFound = true;
3147 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003148 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003149 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003150 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003151 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003152 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003153 // Mark all variables in private list clauses as used in inner region.
3154 // Required for proper codegen of combined directives.
3155 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003156 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003157 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003158 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3159 // Find the particular capture region for the clause if the
3160 // directive is a combined one with multiple capture regions.
3161 // If the directive is not a combined one, the capture region
3162 // associated with the clause is OMPD_unknown and is generated
3163 // only once.
3164 if (CaptureRegion == ThisCaptureRegion ||
3165 CaptureRegion == OMPD_unknown) {
3166 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003167 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003168 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3169 }
3170 }
3171 }
3172 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003173 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003174 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003175 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003176}
3177
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003178static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3179 OpenMPDirectiveKind CancelRegion,
3180 SourceLocation StartLoc) {
3181 // CancelRegion is only needed for cancel and cancellation_point.
3182 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3183 return false;
3184
3185 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3186 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3187 return false;
3188
3189 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3190 << getOpenMPDirectiveName(CancelRegion);
3191 return true;
3192}
3193
Alexey Bataeve3727102018-04-18 15:57:46 +00003194static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003195 OpenMPDirectiveKind CurrentRegion,
3196 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003197 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003198 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003199 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003200 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3201 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003202 bool NestingProhibited = false;
3203 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003204 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003205 enum {
3206 NoRecommend,
3207 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003208 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003209 ShouldBeInTargetRegion,
3210 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003211 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003212 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003213 // OpenMP [2.16, Nesting of Regions]
3214 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003215 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003216 // An ordered construct with the simd clause is the only OpenMP
3217 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003218 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003219 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3220 // message.
3221 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3222 ? diag::err_omp_prohibited_region_simd
3223 : diag::warn_omp_nesting_simd);
3224 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003225 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003226 if (ParentRegion == OMPD_atomic) {
3227 // OpenMP [2.16, Nesting of Regions]
3228 // OpenMP constructs may not be nested inside an atomic region.
3229 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3230 return true;
3231 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003232 if (CurrentRegion == OMPD_section) {
3233 // OpenMP [2.7.2, sections Construct, Restrictions]
3234 // Orphaned section directives are prohibited. That is, the section
3235 // directives must appear within the sections construct and must not be
3236 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003237 if (ParentRegion != OMPD_sections &&
3238 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003239 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3240 << (ParentRegion != OMPD_unknown)
3241 << getOpenMPDirectiveName(ParentRegion);
3242 return true;
3243 }
3244 return false;
3245 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003246 // Allow some constructs (except teams and cancellation constructs) to be
3247 // orphaned (they could be used in functions, called from OpenMP regions
3248 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003249 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003250 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3251 CurrentRegion != OMPD_cancellation_point &&
3252 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003253 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003254 if (CurrentRegion == OMPD_cancellation_point ||
3255 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003256 // OpenMP [2.16, Nesting of Regions]
3257 // A cancellation point construct for which construct-type-clause is
3258 // taskgroup must be nested inside a task construct. A cancellation
3259 // point construct for which construct-type-clause is not taskgroup must
3260 // be closely nested inside an OpenMP construct that matches the type
3261 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003262 // A cancel construct for which construct-type-clause is taskgroup must be
3263 // nested inside a task construct. A cancel construct for which
3264 // construct-type-clause is not taskgroup must be closely nested inside an
3265 // OpenMP construct that matches the type specified in
3266 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003267 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003268 !((CancelRegion == OMPD_parallel &&
3269 (ParentRegion == OMPD_parallel ||
3270 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003271 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003272 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003273 ParentRegion == OMPD_target_parallel_for ||
3274 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003275 ParentRegion == OMPD_teams_distribute_parallel_for ||
3276 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003277 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3278 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003279 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3280 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003281 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003282 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003283 // OpenMP [2.16, Nesting of Regions]
3284 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003285 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003286 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003287 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003288 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3289 // OpenMP [2.16, Nesting of Regions]
3290 // A critical region may not be nested (closely or otherwise) inside a
3291 // critical region with the same name. Note that this restriction is not
3292 // sufficient to prevent deadlock.
3293 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003294 bool DeadLock = Stack->hasDirective(
3295 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3296 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003297 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003298 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3299 PreviousCriticalLoc = Loc;
3300 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003301 }
3302 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003303 },
3304 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003305 if (DeadLock) {
3306 SemaRef.Diag(StartLoc,
3307 diag::err_omp_prohibited_region_critical_same_name)
3308 << CurrentName.getName();
3309 if (PreviousCriticalLoc.isValid())
3310 SemaRef.Diag(PreviousCriticalLoc,
3311 diag::note_omp_previous_critical_region);
3312 return true;
3313 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003314 } else if (CurrentRegion == OMPD_barrier) {
3315 // OpenMP [2.16, Nesting of Regions]
3316 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003317 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003318 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3319 isOpenMPTaskingDirective(ParentRegion) ||
3320 ParentRegion == OMPD_master ||
3321 ParentRegion == OMPD_critical ||
3322 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003323 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003324 !isOpenMPParallelDirective(CurrentRegion) &&
3325 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003326 // OpenMP [2.16, Nesting of Regions]
3327 // A worksharing region may not be closely nested inside a worksharing,
3328 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003329 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3330 isOpenMPTaskingDirective(ParentRegion) ||
3331 ParentRegion == OMPD_master ||
3332 ParentRegion == OMPD_critical ||
3333 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003334 Recommend = ShouldBeInParallelRegion;
3335 } else if (CurrentRegion == OMPD_ordered) {
3336 // OpenMP [2.16, Nesting of Regions]
3337 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003338 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003339 // An ordered region must be closely nested inside a loop region (or
3340 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003341 // OpenMP [2.8.1,simd Construct, Restrictions]
3342 // An ordered construct with the simd clause is the only OpenMP construct
3343 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003344 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003345 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003346 !(isOpenMPSimdDirective(ParentRegion) ||
3347 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003348 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003349 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003350 // OpenMP [2.16, Nesting of Regions]
3351 // If specified, a teams construct must be contained within a target
3352 // construct.
3353 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003354 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003355 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003356 }
Kelvin Libf594a52016-12-17 05:48:59 +00003357 if (!NestingProhibited &&
3358 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3359 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3360 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003361 // OpenMP [2.16, Nesting of Regions]
3362 // distribute, parallel, parallel sections, parallel workshare, and the
3363 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3364 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003365 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3366 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003367 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003368 }
David Majnemer9d168222016-08-05 17:44:54 +00003369 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003370 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003371 // OpenMP 4.5 [2.17 Nesting of Regions]
3372 // The region associated with the distribute construct must be strictly
3373 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003374 NestingProhibited =
3375 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003376 Recommend = ShouldBeInTeamsRegion;
3377 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003378 if (!NestingProhibited &&
3379 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3380 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3381 // OpenMP 4.5 [2.17 Nesting of Regions]
3382 // If a target, target update, target data, target enter data, or
3383 // target exit data construct is encountered during execution of a
3384 // target region, the behavior is unspecified.
3385 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003386 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003387 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003388 if (isOpenMPTargetExecutionDirective(K)) {
3389 OffendingRegion = K;
3390 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003391 }
3392 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003393 },
3394 false /* don't skip top directive */);
3395 CloseNesting = false;
3396 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003397 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003398 if (OrphanSeen) {
3399 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3400 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3401 } else {
3402 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3403 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3404 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3405 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003406 return true;
3407 }
3408 }
3409 return false;
3410}
3411
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003412static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3413 ArrayRef<OMPClause *> Clauses,
3414 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3415 bool ErrorFound = false;
3416 unsigned NamedModifiersNumber = 0;
3417 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3418 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003419 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003420 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003421 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3422 // At most one if clause without a directive-name-modifier can appear on
3423 // the directive.
3424 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3425 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003426 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003427 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3428 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3429 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003430 } else if (CurNM != OMPD_unknown) {
3431 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003432 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003433 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003434 FoundNameModifiers[CurNM] = IC;
3435 if (CurNM == OMPD_unknown)
3436 continue;
3437 // Check if the specified name modifier is allowed for the current
3438 // directive.
3439 // At most one if clause with the particular directive-name-modifier can
3440 // appear on the directive.
3441 bool MatchFound = false;
3442 for (auto NM : AllowedNameModifiers) {
3443 if (CurNM == NM) {
3444 MatchFound = true;
3445 break;
3446 }
3447 }
3448 if (!MatchFound) {
3449 S.Diag(IC->getNameModifierLoc(),
3450 diag::err_omp_wrong_if_directive_name_modifier)
3451 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3452 ErrorFound = true;
3453 }
3454 }
3455 }
3456 // If any if clause on the directive includes a directive-name-modifier then
3457 // all if clauses on the directive must include a directive-name-modifier.
3458 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3459 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003460 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003461 diag::err_omp_no_more_if_clause);
3462 } else {
3463 std::string Values;
3464 std::string Sep(", ");
3465 unsigned AllowedCnt = 0;
3466 unsigned TotalAllowedNum =
3467 AllowedNameModifiers.size() - NamedModifiersNumber;
3468 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3469 ++Cnt) {
3470 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3471 if (!FoundNameModifiers[NM]) {
3472 Values += "'";
3473 Values += getOpenMPDirectiveName(NM);
3474 Values += "'";
3475 if (AllowedCnt + 2 == TotalAllowedNum)
3476 Values += " or ";
3477 else if (AllowedCnt + 1 != TotalAllowedNum)
3478 Values += Sep;
3479 ++AllowedCnt;
3480 }
3481 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003482 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003483 diag::err_omp_unnamed_if_clause)
3484 << (TotalAllowedNum > 1) << Values;
3485 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003486 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003487 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3488 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003489 ErrorFound = true;
3490 }
3491 return ErrorFound;
3492}
3493
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003494StmtResult Sema::ActOnOpenMPExecutableDirective(
3495 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3496 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3497 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003498 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003499 // First check CancelRegion which is then used in checkNestingOfRegions.
3500 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3501 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003502 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003503 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003504
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003505 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003506 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003507 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003508 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003509 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003510 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3511
3512 // Check default data sharing attributes for referenced variables.
3513 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003514 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3515 Stmt *S = AStmt;
3516 while (--ThisCaptureLevel >= 0)
3517 S = cast<CapturedStmt>(S)->getCapturedStmt();
3518 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003519 if (DSAChecker.isErrorFound())
3520 return StmtError();
3521 // Generate list of implicitly defined firstprivate variables.
3522 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003523
Alexey Bataev88202be2017-07-27 13:20:36 +00003524 SmallVector<Expr *, 4> ImplicitFirstprivates(
3525 DSAChecker.getImplicitFirstprivate().begin(),
3526 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003527 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3528 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003529 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003530 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003531 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003532 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003533 if (E)
3534 ImplicitFirstprivates.emplace_back(E);
3535 }
3536 }
3537 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003538 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003539 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3540 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003541 ClausesWithImplicit.push_back(Implicit);
3542 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003543 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003544 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003545 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003546 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003547 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003548 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003549 CXXScopeSpec MapperIdScopeSpec;
3550 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003551 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003552 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3553 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3554 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003555 ClausesWithImplicit.emplace_back(Implicit);
3556 ErrorFound |=
3557 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003558 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003559 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003560 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003561 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003562 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003563
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003564 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003565 switch (Kind) {
3566 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003567 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3568 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003569 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003570 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003571 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003572 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3573 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003574 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003575 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003576 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3577 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003578 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003579 case OMPD_for_simd:
3580 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3581 EndLoc, VarsWithInheritedDSA);
3582 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003583 case OMPD_sections:
3584 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3585 EndLoc);
3586 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003587 case OMPD_section:
3588 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003589 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003590 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3591 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003592 case OMPD_single:
3593 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3594 EndLoc);
3595 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003596 case OMPD_master:
3597 assert(ClausesWithImplicit.empty() &&
3598 "No clauses are allowed for 'omp master' directive");
3599 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3600 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003601 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003602 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3603 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003604 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003605 case OMPD_parallel_for:
3606 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3607 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003608 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003609 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003610 case OMPD_parallel_for_simd:
3611 Res = ActOnOpenMPParallelForSimdDirective(
3612 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003613 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003614 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003615 case OMPD_parallel_sections:
3616 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3617 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003618 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003619 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003620 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003621 Res =
3622 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003623 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003624 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003625 case OMPD_taskyield:
3626 assert(ClausesWithImplicit.empty() &&
3627 "No clauses are allowed for 'omp taskyield' directive");
3628 assert(AStmt == nullptr &&
3629 "No associated statement allowed for 'omp taskyield' directive");
3630 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3631 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003632 case OMPD_barrier:
3633 assert(ClausesWithImplicit.empty() &&
3634 "No clauses are allowed for 'omp barrier' directive");
3635 assert(AStmt == nullptr &&
3636 "No associated statement allowed for 'omp barrier' directive");
3637 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3638 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003639 case OMPD_taskwait:
3640 assert(ClausesWithImplicit.empty() &&
3641 "No clauses are allowed for 'omp taskwait' directive");
3642 assert(AStmt == nullptr &&
3643 "No associated statement allowed for 'omp taskwait' directive");
3644 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3645 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003646 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003647 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3648 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003649 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003650 case OMPD_flush:
3651 assert(AStmt == nullptr &&
3652 "No associated statement allowed for 'omp flush' directive");
3653 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3654 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003655 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003656 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3657 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003658 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003659 case OMPD_atomic:
3660 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3661 EndLoc);
3662 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003663 case OMPD_teams:
3664 Res =
3665 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3666 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003667 case OMPD_target:
3668 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3669 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003670 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003671 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003672 case OMPD_target_parallel:
3673 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3674 StartLoc, EndLoc);
3675 AllowedNameModifiers.push_back(OMPD_target);
3676 AllowedNameModifiers.push_back(OMPD_parallel);
3677 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003678 case OMPD_target_parallel_for:
3679 Res = ActOnOpenMPTargetParallelForDirective(
3680 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3681 AllowedNameModifiers.push_back(OMPD_target);
3682 AllowedNameModifiers.push_back(OMPD_parallel);
3683 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003684 case OMPD_cancellation_point:
3685 assert(ClausesWithImplicit.empty() &&
3686 "No clauses are allowed for 'omp cancellation point' directive");
3687 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3688 "cancellation point' directive");
3689 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3690 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003691 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003692 assert(AStmt == nullptr &&
3693 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003694 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3695 CancelRegion);
3696 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003697 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003698 case OMPD_target_data:
3699 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3700 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003701 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003702 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003703 case OMPD_target_enter_data:
3704 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003705 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003706 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3707 break;
Samuel Antao72590762016-01-19 20:04:50 +00003708 case OMPD_target_exit_data:
3709 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003710 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003711 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3712 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003713 case OMPD_taskloop:
3714 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3715 EndLoc, VarsWithInheritedDSA);
3716 AllowedNameModifiers.push_back(OMPD_taskloop);
3717 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003718 case OMPD_taskloop_simd:
3719 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3720 EndLoc, VarsWithInheritedDSA);
3721 AllowedNameModifiers.push_back(OMPD_taskloop);
3722 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003723 case OMPD_distribute:
3724 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3725 EndLoc, VarsWithInheritedDSA);
3726 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003727 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003728 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3729 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003730 AllowedNameModifiers.push_back(OMPD_target_update);
3731 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003732 case OMPD_distribute_parallel_for:
3733 Res = ActOnOpenMPDistributeParallelForDirective(
3734 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3735 AllowedNameModifiers.push_back(OMPD_parallel);
3736 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003737 case OMPD_distribute_parallel_for_simd:
3738 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3739 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3740 AllowedNameModifiers.push_back(OMPD_parallel);
3741 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003742 case OMPD_distribute_simd:
3743 Res = ActOnOpenMPDistributeSimdDirective(
3744 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3745 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003746 case OMPD_target_parallel_for_simd:
3747 Res = ActOnOpenMPTargetParallelForSimdDirective(
3748 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3749 AllowedNameModifiers.push_back(OMPD_target);
3750 AllowedNameModifiers.push_back(OMPD_parallel);
3751 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003752 case OMPD_target_simd:
3753 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3754 EndLoc, VarsWithInheritedDSA);
3755 AllowedNameModifiers.push_back(OMPD_target);
3756 break;
Kelvin Li02532872016-08-05 14:37:37 +00003757 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003758 Res = ActOnOpenMPTeamsDistributeDirective(
3759 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003760 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003761 case OMPD_teams_distribute_simd:
3762 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3763 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3764 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003765 case OMPD_teams_distribute_parallel_for_simd:
3766 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3767 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3768 AllowedNameModifiers.push_back(OMPD_parallel);
3769 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003770 case OMPD_teams_distribute_parallel_for:
3771 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3772 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3773 AllowedNameModifiers.push_back(OMPD_parallel);
3774 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003775 case OMPD_target_teams:
3776 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3777 EndLoc);
3778 AllowedNameModifiers.push_back(OMPD_target);
3779 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003780 case OMPD_target_teams_distribute:
3781 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3782 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3783 AllowedNameModifiers.push_back(OMPD_target);
3784 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003785 case OMPD_target_teams_distribute_parallel_for:
3786 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3787 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3788 AllowedNameModifiers.push_back(OMPD_target);
3789 AllowedNameModifiers.push_back(OMPD_parallel);
3790 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003791 case OMPD_target_teams_distribute_parallel_for_simd:
3792 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3793 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3794 AllowedNameModifiers.push_back(OMPD_target);
3795 AllowedNameModifiers.push_back(OMPD_parallel);
3796 break;
Kelvin Lida681182017-01-10 18:08:18 +00003797 case OMPD_target_teams_distribute_simd:
3798 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3799 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3800 AllowedNameModifiers.push_back(OMPD_target);
3801 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003802 case OMPD_declare_target:
3803 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003804 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003805 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003806 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003807 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003808 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003809 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003810 llvm_unreachable("OpenMP Directive is not allowed");
3811 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003812 llvm_unreachable("Unknown OpenMP directive");
3813 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003814
Alexey Bataeve3727102018-04-18 15:57:46 +00003815 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003816 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3817 << P.first << P.second->getSourceRange();
3818 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003819 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3820
3821 if (!AllowedNameModifiers.empty())
3822 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3823 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003824
Alexey Bataeved09d242014-05-28 05:53:51 +00003825 if (ErrorFound)
3826 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003827 return Res;
3828}
3829
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003830Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3831 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003832 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003833 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3834 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003835 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003836 assert(Linears.size() == LinModifiers.size());
3837 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003838 if (!DG || DG.get().isNull())
3839 return DeclGroupPtrTy();
3840
3841 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003842 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003843 return DG;
3844 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003845 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003846 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3847 ADecl = FTD->getTemplatedDecl();
3848
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003849 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3850 if (!FD) {
3851 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003852 return DeclGroupPtrTy();
3853 }
3854
Alexey Bataev2af33e32016-04-07 12:45:37 +00003855 // OpenMP [2.8.2, declare simd construct, Description]
3856 // The parameter of the simdlen clause must be a constant positive integer
3857 // expression.
3858 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003859 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003860 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003861 // OpenMP [2.8.2, declare simd construct, Description]
3862 // The special this pointer can be used as if was one of the arguments to the
3863 // function in any of the linear, aligned, or uniform clauses.
3864 // The uniform clause declares one or more arguments to have an invariant
3865 // value for all concurrent invocations of the function in the execution of a
3866 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003867 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3868 const Expr *UniformedLinearThis = nullptr;
3869 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003870 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003871 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3872 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003873 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3874 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003875 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00003876 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003877 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003878 }
3879 if (isa<CXXThisExpr>(E)) {
3880 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003881 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003882 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003883 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3884 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003885 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003886 // OpenMP [2.8.2, declare simd construct, Description]
3887 // The aligned clause declares that the object to which each list item points
3888 // is aligned to the number of bytes expressed in the optional parameter of
3889 // the aligned clause.
3890 // The special this pointer can be used as if was one of the arguments to the
3891 // function in any of the linear, aligned, or uniform clauses.
3892 // The type of list items appearing in the aligned clause must be array,
3893 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00003894 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3895 const Expr *AlignedThis = nullptr;
3896 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003897 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003898 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3899 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3900 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00003901 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3902 FD->getParamDecl(PVD->getFunctionScopeIndex())
3903 ->getCanonicalDecl() == CanonPVD) {
3904 // OpenMP [2.8.1, simd construct, Restrictions]
3905 // A list-item cannot appear in more than one aligned clause.
3906 if (AlignedArgs.count(CanonPVD) > 0) {
3907 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3908 << 1 << E->getSourceRange();
3909 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3910 diag::note_omp_explicit_dsa)
3911 << getOpenMPClauseName(OMPC_aligned);
3912 continue;
3913 }
3914 AlignedArgs[CanonPVD] = E;
3915 QualType QTy = PVD->getType()
3916 .getNonReferenceType()
3917 .getUnqualifiedType()
3918 .getCanonicalType();
3919 const Type *Ty = QTy.getTypePtrOrNull();
3920 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3921 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3922 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3923 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3924 }
3925 continue;
3926 }
3927 }
3928 if (isa<CXXThisExpr>(E)) {
3929 if (AlignedThis) {
3930 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3931 << 2 << E->getSourceRange();
3932 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3933 << getOpenMPClauseName(OMPC_aligned);
3934 }
3935 AlignedThis = E;
3936 continue;
3937 }
3938 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3939 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3940 }
3941 // The optional parameter of the aligned clause, alignment, must be a constant
3942 // positive integer expression. If no optional parameter is specified,
3943 // implementation-defined default alignments for SIMD instructions on the
3944 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00003945 SmallVector<const Expr *, 4> NewAligns;
3946 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003947 ExprResult Align;
3948 if (E)
3949 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3950 NewAligns.push_back(Align.get());
3951 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003952 // OpenMP [2.8.2, declare simd construct, Description]
3953 // The linear clause declares one or more list items to be private to a SIMD
3954 // lane and to have a linear relationship with respect to the iteration space
3955 // of a loop.
3956 // The special this pointer can be used as if was one of the arguments to the
3957 // function in any of the linear, aligned, or uniform clauses.
3958 // When a linear-step expression is specified in a linear clause it must be
3959 // either a constant integer expression or an integer-typed parameter that is
3960 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00003961 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003962 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3963 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00003964 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003965 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3966 ++MI;
3967 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003968 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3969 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3970 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003971 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3972 FD->getParamDecl(PVD->getFunctionScopeIndex())
3973 ->getCanonicalDecl() == CanonPVD) {
3974 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3975 // A list-item cannot appear in more than one linear clause.
3976 if (LinearArgs.count(CanonPVD) > 0) {
3977 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3978 << getOpenMPClauseName(OMPC_linear)
3979 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3980 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3981 diag::note_omp_explicit_dsa)
3982 << getOpenMPClauseName(OMPC_linear);
3983 continue;
3984 }
3985 // Each argument can appear in at most one uniform or linear clause.
3986 if (UniformedArgs.count(CanonPVD) > 0) {
3987 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3988 << getOpenMPClauseName(OMPC_linear)
3989 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3990 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3991 diag::note_omp_explicit_dsa)
3992 << getOpenMPClauseName(OMPC_uniform);
3993 continue;
3994 }
3995 LinearArgs[CanonPVD] = E;
3996 if (E->isValueDependent() || E->isTypeDependent() ||
3997 E->isInstantiationDependent() ||
3998 E->containsUnexpandedParameterPack())
3999 continue;
4000 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4001 PVD->getOriginalType());
4002 continue;
4003 }
4004 }
4005 if (isa<CXXThisExpr>(E)) {
4006 if (UniformedLinearThis) {
4007 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4008 << getOpenMPClauseName(OMPC_linear)
4009 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4010 << E->getSourceRange();
4011 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4012 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4013 : OMPC_linear);
4014 continue;
4015 }
4016 UniformedLinearThis = E;
4017 if (E->isValueDependent() || E->isTypeDependent() ||
4018 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4019 continue;
4020 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4021 E->getType());
4022 continue;
4023 }
4024 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4025 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4026 }
4027 Expr *Step = nullptr;
4028 Expr *NewStep = nullptr;
4029 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004030 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004031 // Skip the same step expression, it was checked already.
4032 if (Step == E || !E) {
4033 NewSteps.push_back(E ? NewStep : nullptr);
4034 continue;
4035 }
4036 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004037 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4038 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4039 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004040 if (UniformedArgs.count(CanonPVD) == 0) {
4041 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4042 << Step->getSourceRange();
4043 } else if (E->isValueDependent() || E->isTypeDependent() ||
4044 E->isInstantiationDependent() ||
4045 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004046 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004047 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004048 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004049 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4050 << Step->getSourceRange();
4051 }
4052 continue;
4053 }
4054 NewStep = Step;
4055 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4056 !Step->isInstantiationDependent() &&
4057 !Step->containsUnexpandedParameterPack()) {
4058 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4059 .get();
4060 if (NewStep)
4061 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4062 }
4063 NewSteps.push_back(NewStep);
4064 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004065 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4066 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004067 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004068 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4069 const_cast<Expr **>(Linears.data()), Linears.size(),
4070 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4071 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004072 ADecl->addAttr(NewAttr);
4073 return ConvertDeclToDeclGroup(ADecl);
4074}
4075
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004076StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4077 Stmt *AStmt,
4078 SourceLocation StartLoc,
4079 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004080 if (!AStmt)
4081 return StmtError();
4082
Alexey Bataeve3727102018-04-18 15:57:46 +00004083 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004084 // 1.2.2 OpenMP Language Terminology
4085 // Structured block - An executable statement with a single entry at the
4086 // top and a single exit at the bottom.
4087 // The point of exit cannot be a branch out of the structured block.
4088 // longjmp() and throw() must not violate the entry/exit criteria.
4089 CS->getCapturedDecl()->setNothrow();
4090
Reid Kleckner87a31802018-03-12 21:43:02 +00004091 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004092
Alexey Bataev25e5b442015-09-15 12:52:43 +00004093 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4094 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004095}
4096
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004097namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004098/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004099/// extracting iteration space of each loop in the loop nest, that will be used
4100/// for IR generation.
4101class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004102 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004103 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004104 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004105 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004106 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004107 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004108 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004109 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004110 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004111 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004112 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004113 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004114 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004115 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004116 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004117 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004118 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004119 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004120 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004121 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004122 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004123 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004124 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004125 /// Var < UB
4126 /// Var <= UB
4127 /// UB > Var
4128 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004129 /// This will have no value when the condition is !=
4130 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004131 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004132 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004133 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004134 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004135
4136public:
4137 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004138 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004139 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004140 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004141 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004142 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004143 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004144 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004145 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004146 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004147 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004148 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004149 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004150 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004151 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004152 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004153 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004154 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004155 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004156 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004157 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004158 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004159 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004160 /// True, if the compare operator is strict (<, > or !=).
4161 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004162 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004163 Expr *buildNumIterations(
4164 Scope *S, const bool LimitedType,
4165 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004166 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004167 Expr *
4168 buildPreCond(Scope *S, Expr *Cond,
4169 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004170 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004171 DeclRefExpr *
4172 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4173 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004174 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004175 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004176 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004177 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004178 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004179 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004180 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004181 /// Build loop data with counter value for depend clauses in ordered
4182 /// directives.
4183 Expr *
4184 buildOrderedLoopData(Scope *S, Expr *Counter,
4185 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4186 SourceLocation Loc, Expr *Inc = nullptr,
4187 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004188 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004189 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004190
4191private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004192 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004193 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004194 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004195 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004196 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004197 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004198 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4199 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004200 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004201 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004202};
4203
Alexey Bataeve3727102018-04-18 15:57:46 +00004204bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004205 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004206 assert(!LB && !UB && !Step);
4207 return false;
4208 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004209 return LCDecl->getType()->isDependentType() ||
4210 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4211 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004212}
4213
Alexey Bataeve3727102018-04-18 15:57:46 +00004214bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004215 Expr *NewLCRefExpr,
4216 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004217 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004218 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004219 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004220 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004221 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004222 LCDecl = getCanonicalDecl(NewLCDecl);
4223 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004224 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4225 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004226 if ((Ctor->isCopyOrMoveConstructor() ||
4227 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4228 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004229 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004230 LB = NewLB;
4231 return false;
4232}
4233
Alexey Bataev316ccf62019-01-29 18:51:58 +00004234bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4235 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004236 bool StrictOp, SourceRange SR,
4237 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004238 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004239 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4240 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004241 if (!NewUB)
4242 return true;
4243 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004244 if (LessOp)
4245 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004246 TestIsStrictOp = StrictOp;
4247 ConditionSrcRange = SR;
4248 ConditionLoc = SL;
4249 return false;
4250}
4251
Alexey Bataeve3727102018-04-18 15:57:46 +00004252bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004253 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004254 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004255 if (!NewStep)
4256 return true;
4257 if (!NewStep->isValueDependent()) {
4258 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004259 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004260 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4261 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004262 if (Val.isInvalid())
4263 return true;
4264 NewStep = Val.get();
4265
4266 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4267 // If test-expr is of form var relational-op b and relational-op is < or
4268 // <= then incr-expr must cause var to increase on each iteration of the
4269 // loop. If test-expr is of form var relational-op b and relational-op is
4270 // > or >= then incr-expr must cause var to decrease on each iteration of
4271 // the loop.
4272 // If test-expr is of form b relational-op var and relational-op is < or
4273 // <= then incr-expr must cause var to decrease on each iteration of the
4274 // loop. If test-expr is of form b relational-op var and relational-op is
4275 // > or >= then incr-expr must cause var to increase on each iteration of
4276 // the loop.
4277 llvm::APSInt Result;
4278 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4279 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4280 bool IsConstNeg =
4281 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004282 bool IsConstPos =
4283 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004284 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004285
4286 // != with increment is treated as <; != with decrement is treated as >
4287 if (!TestIsLessOp.hasValue())
4288 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004289 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004290 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004291 (IsConstNeg || (IsUnsigned && Subtract)) :
4292 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004293 SemaRef.Diag(NewStep->getExprLoc(),
4294 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004295 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004296 SemaRef.Diag(ConditionLoc,
4297 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004298 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004299 return true;
4300 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004301 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004302 NewStep =
4303 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4304 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004305 Subtract = !Subtract;
4306 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004307 }
4308
4309 Step = NewStep;
4310 SubtractStep = Subtract;
4311 return false;
4312}
4313
Alexey Bataeve3727102018-04-18 15:57:46 +00004314bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004315 // Check init-expr for canonical loop form and save loop counter
4316 // variable - #Var and its initialization value - #LB.
4317 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4318 // var = lb
4319 // integer-type var = lb
4320 // random-access-iterator-type var = lb
4321 // pointer-type var = lb
4322 //
4323 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004324 if (EmitDiags) {
4325 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4326 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004327 return true;
4328 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004329 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4330 if (!ExprTemp->cleanupsHaveSideEffects())
4331 S = ExprTemp->getSubExpr();
4332
Alexander Musmana5f070a2014-10-01 06:03:56 +00004333 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004334 if (Expr *E = dyn_cast<Expr>(S))
4335 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004336 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004337 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004338 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004339 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4340 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4341 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004342 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4343 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004344 }
4345 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4346 if (ME->isArrow() &&
4347 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004348 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004349 }
4350 }
David Majnemer9d168222016-08-05 17:44:54 +00004351 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004352 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004353 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004354 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004355 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004356 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004357 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004358 diag::ext_omp_loop_not_canonical_init)
4359 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004360 return setLCDeclAndLB(
4361 Var,
4362 buildDeclRefExpr(SemaRef, Var,
4363 Var->getType().getNonReferenceType(),
4364 DS->getBeginLoc()),
4365 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004366 }
4367 }
4368 }
David Majnemer9d168222016-08-05 17:44:54 +00004369 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004370 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004371 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004372 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004373 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4374 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004375 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4376 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004377 }
4378 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4379 if (ME->isArrow() &&
4380 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004381 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004382 }
4383 }
4384 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004385
Alexey Bataeve3727102018-04-18 15:57:46 +00004386 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004387 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004388 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004389 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004390 << S->getSourceRange();
4391 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004392 return true;
4393}
4394
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004395/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004396/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004397static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004398 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004399 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004400 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004401 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004402 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004403 if ((Ctor->isCopyOrMoveConstructor() ||
4404 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4405 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004406 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004407 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4408 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004409 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004410 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004411 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004412 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4413 return getCanonicalDecl(ME->getMemberDecl());
4414 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004415}
4416
Alexey Bataeve3727102018-04-18 15:57:46 +00004417bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004418 // Check test-expr for canonical form, save upper-bound UB, flags for
4419 // less/greater and for strict/non-strict comparison.
4420 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4421 // var relational-op b
4422 // b relational-op var
4423 //
4424 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004425 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004426 return true;
4427 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004428 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004429 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004430 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004431 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004432 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4433 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004434 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4435 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4436 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004437 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4438 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004439 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4440 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4441 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004442 } else if (BO->getOpcode() == BO_NE)
4443 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4444 BO->getRHS() : BO->getLHS(),
4445 /*LessOp=*/llvm::None,
4446 /*StrictOp=*/true,
4447 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004448 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004449 if (CE->getNumArgs() == 2) {
4450 auto Op = CE->getOperator();
4451 switch (Op) {
4452 case OO_Greater:
4453 case OO_GreaterEqual:
4454 case OO_Less:
4455 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004456 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4457 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004458 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4459 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004460 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4461 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004462 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4463 CE->getOperatorLoc());
4464 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004465 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004466 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4467 CE->getArg(1) : CE->getArg(0),
4468 /*LessOp=*/llvm::None,
4469 /*StrictOp=*/true,
4470 CE->getSourceRange(),
4471 CE->getOperatorLoc());
4472 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004473 default:
4474 break;
4475 }
4476 }
4477 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004478 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004479 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004480 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004481 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004482 return true;
4483}
4484
Alexey Bataeve3727102018-04-18 15:57:46 +00004485bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004486 // RHS of canonical loop form increment can be:
4487 // var + incr
4488 // incr + var
4489 // var - incr
4490 //
4491 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004492 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004493 if (BO->isAdditiveOp()) {
4494 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004495 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4496 return setStep(BO->getRHS(), !IsAdd);
4497 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4498 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004499 }
David Majnemer9d168222016-08-05 17:44:54 +00004500 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004501 bool IsAdd = CE->getOperator() == OO_Plus;
4502 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004503 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4504 return setStep(CE->getArg(1), !IsAdd);
4505 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4506 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004507 }
4508 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004509 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004510 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004511 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004512 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004513 return true;
4514}
4515
Alexey Bataeve3727102018-04-18 15:57:46 +00004516bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004517 // Check incr-expr for canonical loop form and return true if it
4518 // does not conform.
4519 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4520 // ++var
4521 // var++
4522 // --var
4523 // var--
4524 // var += incr
4525 // var -= incr
4526 // var = var + incr
4527 // var = incr + var
4528 // var = var - incr
4529 //
4530 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004531 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004532 return true;
4533 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004534 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4535 if (!ExprTemp->cleanupsHaveSideEffects())
4536 S = ExprTemp->getSubExpr();
4537
Alexander Musmana5f070a2014-10-01 06:03:56 +00004538 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004539 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004540 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004541 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004542 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4543 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004544 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004545 (UO->isDecrementOp() ? -1 : 1))
4546 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004547 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004548 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004549 switch (BO->getOpcode()) {
4550 case BO_AddAssign:
4551 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004552 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4553 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004554 break;
4555 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004556 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4557 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004558 break;
4559 default:
4560 break;
4561 }
David Majnemer9d168222016-08-05 17:44:54 +00004562 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004563 switch (CE->getOperator()) {
4564 case OO_PlusPlus:
4565 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004566 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4567 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004568 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004569 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004570 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4571 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004572 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004573 break;
4574 case OO_PlusEqual:
4575 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004576 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4577 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004578 break;
4579 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004580 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4581 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004582 break;
4583 default:
4584 break;
4585 }
4586 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004587 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004588 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004589 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004590 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004591 return true;
4592}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004593
Alexey Bataev5a3af132016-03-29 08:58:54 +00004594static ExprResult
4595tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004596 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004597 if (SemaRef.CurContext->isDependentContext())
4598 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004599 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4600 return SemaRef.PerformImplicitConversion(
4601 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4602 /*AllowExplicit=*/true);
4603 auto I = Captures.find(Capture);
4604 if (I != Captures.end())
4605 return buildCapture(SemaRef, Capture, I->second);
4606 DeclRefExpr *Ref = nullptr;
4607 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4608 Captures[Capture] = Ref;
4609 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004610}
4611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004612/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004613Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004614 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004615 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004616 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004617 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004618 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004619 SemaRef.getLangOpts().CPlusPlus) {
4620 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004621 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4622 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004623 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4624 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004625 if (!Upper || !Lower)
4626 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004627
4628 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4629
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004630 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004631 // BuildBinOp already emitted error, this one is to point user to upper
4632 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004633 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004634 << Upper->getSourceRange() << Lower->getSourceRange();
4635 return nullptr;
4636 }
4637 }
4638
4639 if (!Diff.isUsable())
4640 return nullptr;
4641
4642 // Upper - Lower [- 1]
4643 if (TestIsStrictOp)
4644 Diff = SemaRef.BuildBinOp(
4645 S, DefaultLoc, BO_Sub, Diff.get(),
4646 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4647 if (!Diff.isUsable())
4648 return nullptr;
4649
4650 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004651 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004652 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004653 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004654 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004655 if (!Diff.isUsable())
4656 return nullptr;
4657
4658 // Parentheses (for dumping/debugging purposes only).
4659 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4660 if (!Diff.isUsable())
4661 return nullptr;
4662
4663 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004664 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004665 if (!Diff.isUsable())
4666 return nullptr;
4667
Alexander Musman174b3ca2014-10-06 11:16:29 +00004668 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004669 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004670 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004671 bool UseVarType = VarType->hasIntegerRepresentation() &&
4672 C.getTypeSize(Type) > C.getTypeSize(VarType);
4673 if (!Type->isIntegerType() || UseVarType) {
4674 unsigned NewSize =
4675 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4676 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4677 : Type->hasSignedIntegerRepresentation();
4678 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004679 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4680 Diff = SemaRef.PerformImplicitConversion(
4681 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4682 if (!Diff.isUsable())
4683 return nullptr;
4684 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004685 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004686 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004687 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4688 if (NewSize != C.getTypeSize(Type)) {
4689 if (NewSize < C.getTypeSize(Type)) {
4690 assert(NewSize == 64 && "incorrect loop var size");
4691 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4692 << InitSrcRange << ConditionSrcRange;
4693 }
4694 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004695 NewSize, Type->hasSignedIntegerRepresentation() ||
4696 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004697 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4698 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4699 Sema::AA_Converting, true);
4700 if (!Diff.isUsable())
4701 return nullptr;
4702 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004703 }
4704 }
4705
Alexander Musmana5f070a2014-10-01 06:03:56 +00004706 return Diff.get();
4707}
4708
Alexey Bataeve3727102018-04-18 15:57:46 +00004709Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004710 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004711 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004712 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4713 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4714 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004715
Alexey Bataeve3727102018-04-18 15:57:46 +00004716 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4717 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004718 if (!NewLB.isUsable() || !NewUB.isUsable())
4719 return nullptr;
4720
Alexey Bataeve3727102018-04-18 15:57:46 +00004721 ExprResult CondExpr =
4722 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004723 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004724 (TestIsStrictOp ? BO_LT : BO_LE) :
4725 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004726 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004727 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004728 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4729 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004730 CondExpr = SemaRef.PerformImplicitConversion(
4731 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4732 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004733 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004734 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004735 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004736 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4737}
4738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004739/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004740DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004741 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4742 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004743 auto *VD = dyn_cast<VarDecl>(LCDecl);
4744 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004745 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4746 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004747 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004748 const DSAStackTy::DSAVarData Data =
4749 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004750 // If the loop control decl is explicitly marked as private, do not mark it
4751 // as captured again.
4752 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4753 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004754 return Ref;
4755 }
4756 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004757 DefaultLoc);
4758}
4759
Alexey Bataeve3727102018-04-18 15:57:46 +00004760Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004761 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004762 QualType Type = LCDecl->getType().getNonReferenceType();
4763 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004764 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4765 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4766 isa<VarDecl>(LCDecl)
4767 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4768 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004769 if (PrivateVar->isInvalidDecl())
4770 return nullptr;
4771 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4772 }
4773 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004774}
4775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004776/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004777Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004779/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004780Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004781
Alexey Bataevf138fda2018-08-13 19:04:24 +00004782Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4783 Scope *S, Expr *Counter,
4784 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4785 Expr *Inc, OverloadedOperatorKind OOK) {
4786 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4787 if (!Cnt)
4788 return nullptr;
4789 if (Inc) {
4790 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4791 "Expected only + or - operations for depend clauses.");
4792 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4793 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4794 if (!Cnt)
4795 return nullptr;
4796 }
4797 ExprResult Diff;
4798 QualType VarType = LCDecl->getType().getNonReferenceType();
4799 if (VarType->isIntegerType() || VarType->isPointerType() ||
4800 SemaRef.getLangOpts().CPlusPlus) {
4801 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004802 Expr *Upper = TestIsLessOp.getValue()
4803 ? Cnt
4804 : tryBuildCapture(SemaRef, UB, Captures).get();
4805 Expr *Lower = TestIsLessOp.getValue()
4806 ? tryBuildCapture(SemaRef, LB, Captures).get()
4807 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004808 if (!Upper || !Lower)
4809 return nullptr;
4810
4811 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4812
4813 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4814 // BuildBinOp already emitted error, this one is to point user to upper
4815 // and lower bound, and to tell what is passed to 'operator-'.
4816 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4817 << Upper->getSourceRange() << Lower->getSourceRange();
4818 return nullptr;
4819 }
4820 }
4821
4822 if (!Diff.isUsable())
4823 return nullptr;
4824
4825 // Parentheses (for dumping/debugging purposes only).
4826 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4827 if (!Diff.isUsable())
4828 return nullptr;
4829
4830 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4831 if (!NewStep.isUsable())
4832 return nullptr;
4833 // (Upper - Lower) / Step
4834 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4835 if (!Diff.isUsable())
4836 return nullptr;
4837
4838 return Diff.get();
4839}
4840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004841/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004842struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004843 /// True if the condition operator is the strict compare operator (<, > or
4844 /// !=).
4845 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004846 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004847 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004848 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004849 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004850 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004851 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004852 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004853 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004854 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004855 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004856 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004857 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004858 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004859 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004860 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004861 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004862 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004863 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004864 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004865 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004866 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004867 SourceRange IncSrcRange;
4868};
4869
Alexey Bataev23b69422014-06-18 07:08:49 +00004870} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004871
Alexey Bataev9c821032015-04-30 04:23:23 +00004872void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4873 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4874 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004875 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4876 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004877 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00004878 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00004879 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004880 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4881 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004882 auto *VD = dyn_cast<VarDecl>(D);
4883 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004884 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004885 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00004886 } else {
4887 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4888 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004889 VD = cast<VarDecl>(Ref->getDecl());
4890 }
4891 }
4892 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00004893 const Decl *LD = DSAStack->getPossiblyLoopCunter();
4894 if (LD != D->getCanonicalDecl()) {
4895 DSAStack->resetPossibleLoopCounter();
4896 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4897 MarkDeclarationsReferencedInExpr(
4898 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4899 Var->getType().getNonLValueExprType(Context),
4900 ForLoc, /*RefersToCapture=*/true));
4901 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004902 }
4903 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004904 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004905 }
4906}
4907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004908/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004909/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00004910static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00004911 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4912 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00004913 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4914 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00004915 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004916 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00004917 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004918 // OpenMP [2.6, Canonical Loop Form]
4919 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004920 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004921 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004922 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004923 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00004924 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00004925 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004926 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00004927 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4928 SemaRef.Diag(DSA.getConstructLoc(),
4929 diag::note_omp_collapse_ordered_expr)
4930 << 2 << CollapseLoopCountExpr->getSourceRange()
4931 << OrderedLoopCountExpr->getSourceRange();
4932 else if (CollapseLoopCountExpr)
4933 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4934 diag::note_omp_collapse_ordered_expr)
4935 << 0 << CollapseLoopCountExpr->getSourceRange();
4936 else
4937 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4938 diag::note_omp_collapse_ordered_expr)
4939 << 1 << OrderedLoopCountExpr->getSourceRange();
4940 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004941 return true;
4942 }
4943 assert(For->getBody());
4944
4945 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4946
4947 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004948 Stmt *Init = For->getInit();
4949 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004950 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004951
4952 bool HasErrors = false;
4953
4954 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004955 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4956 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004957
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004958 // OpenMP [2.6, Canonical Loop Form]
4959 // Var is one of the following:
4960 // A variable of signed or unsigned integer type.
4961 // For C++, a variable of a random access iterator type.
4962 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004963 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004964 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4965 !VarType->isPointerType() &&
4966 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004967 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004968 << SemaRef.getLangOpts().CPlusPlus;
4969 HasErrors = true;
4970 }
4971
4972 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4973 // a Construct
4974 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4975 // parallel for construct is (are) private.
4976 // The loop iteration variable in the associated for-loop of a simd
4977 // construct with just one associated for-loop is linear with a
4978 // constant-linear-step that is the increment of the associated for-loop.
4979 // Exclude loop var from the list of variables with implicitly defined data
4980 // sharing attributes.
4981 VarsWithImplicitDSA.erase(LCDecl);
4982
4983 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4984 // in a Construct, C/C++].
4985 // The loop iteration variable in the associated for-loop of a simd
4986 // construct with just one associated for-loop may be listed in a linear
4987 // clause with a constant-linear-step that is the increment of the
4988 // associated for-loop.
4989 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4990 // parallel for construct may be listed in a private or lastprivate clause.
4991 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4992 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4993 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00004994 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004995 isOpenMPSimdDirective(DKind)
4996 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4997 : OMPC_private;
4998 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4999 DVar.CKind != PredeterminedCKind) ||
5000 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5001 isOpenMPDistributeDirective(DKind)) &&
5002 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5003 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5004 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005005 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005006 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5007 << getOpenMPClauseName(PredeterminedCKind);
5008 if (DVar.RefExpr == nullptr)
5009 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005010 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005011 HasErrors = true;
5012 } else if (LoopDeclRefExpr != nullptr) {
5013 // Make the loop iteration variable private (for worksharing constructs),
5014 // linear (for simd directives with the only one associated loop) or
5015 // lastprivate (for simd directives with several collapsed or ordered
5016 // loops).
5017 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005018 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005019 }
5020
5021 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5022
5023 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005024 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005025
5026 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005027 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005028 }
5029
Alexey Bataeve3727102018-04-18 15:57:46 +00005030 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005031 return HasErrors;
5032
Alexander Musmana5f070a2014-10-01 06:03:56 +00005033 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005034 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005035 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5036 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005037 DSA.getCurScope(),
5038 (isOpenMPWorksharingDirective(DKind) ||
5039 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5040 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005041 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5042 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5043 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5044 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5045 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5046 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5047 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5048 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005049 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005050
Alexey Bataev62dbb972015-04-22 11:59:37 +00005051 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5052 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005053 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005054 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005055 ResultIterSpace.CounterInit == nullptr ||
5056 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005057 if (!HasErrors && DSA.isOrderedRegion()) {
5058 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5059 if (CurrentNestedLoopCount <
5060 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5061 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5062 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5063 DSA.getOrderedRegionParam().second->setLoopCounter(
5064 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5065 }
5066 }
5067 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5068 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5069 // Erroneous case - clause has some problems.
5070 continue;
5071 }
5072 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5073 Pair.second.size() <= CurrentNestedLoopCount) {
5074 // Erroneous case - clause has some problems.
5075 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5076 continue;
5077 }
5078 Expr *CntValue;
5079 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5080 CntValue = ISC.buildOrderedLoopData(
5081 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5082 Pair.first->getDependencyLoc());
5083 else
5084 CntValue = ISC.buildOrderedLoopData(
5085 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5086 Pair.first->getDependencyLoc(),
5087 Pair.second[CurrentNestedLoopCount].first,
5088 Pair.second[CurrentNestedLoopCount].second);
5089 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5090 }
5091 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005092
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005093 return HasErrors;
5094}
5095
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005096/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005097static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005098buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005099 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005100 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005101 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005102 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005103 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005104 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005105 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005106 VarRef.get()->getType())) {
5107 NewStart = SemaRef.PerformImplicitConversion(
5108 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5109 /*AllowExplicit=*/true);
5110 if (!NewStart.isUsable())
5111 return ExprError();
5112 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005113
Alexey Bataeve3727102018-04-18 15:57:46 +00005114 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005115 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5116 return Init;
5117}
5118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005119/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005120static ExprResult buildCounterUpdate(
5121 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5122 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5123 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005124 // Add parentheses (for debugging purposes only).
5125 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5126 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5127 !Step.isUsable())
5128 return ExprError();
5129
Alexey Bataev5a3af132016-03-29 08:58:54 +00005130 ExprResult NewStep = Step;
5131 if (Captures)
5132 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005133 if (NewStep.isInvalid())
5134 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005135 ExprResult Update =
5136 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005137 if (!Update.isUsable())
5138 return ExprError();
5139
Alexey Bataevc0214e02016-02-16 12:13:49 +00005140 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5141 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005142 ExprResult NewStart = Start;
5143 if (Captures)
5144 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005145 if (NewStart.isInvalid())
5146 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005147
Alexey Bataevc0214e02016-02-16 12:13:49 +00005148 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5149 ExprResult SavedUpdate = Update;
5150 ExprResult UpdateVal;
5151 if (VarRef.get()->getType()->isOverloadableType() ||
5152 NewStart.get()->getType()->isOverloadableType() ||
5153 Update.get()->getType()->isOverloadableType()) {
5154 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5155 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5156 Update =
5157 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5158 if (Update.isUsable()) {
5159 UpdateVal =
5160 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5161 VarRef.get(), SavedUpdate.get());
5162 if (UpdateVal.isUsable()) {
5163 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5164 UpdateVal.get());
5165 }
5166 }
5167 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5168 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005169
Alexey Bataevc0214e02016-02-16 12:13:49 +00005170 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5171 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5172 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5173 NewStart.get(), SavedUpdate.get());
5174 if (!Update.isUsable())
5175 return ExprError();
5176
Alexey Bataev11481f52016-02-17 10:29:05 +00005177 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5178 VarRef.get()->getType())) {
5179 Update = SemaRef.PerformImplicitConversion(
5180 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5181 if (!Update.isUsable())
5182 return ExprError();
5183 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005184
5185 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5186 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005187 return Update;
5188}
5189
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005190/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005191/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005192static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005193 if (E == nullptr)
5194 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005195 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005196 QualType OldType = E->getType();
5197 unsigned HasBits = C.getTypeSize(OldType);
5198 if (HasBits >= Bits)
5199 return ExprResult(E);
5200 // OK to convert to signed, because new type has more bits than old.
5201 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5202 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5203 true);
5204}
5205
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005206/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005207/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005208static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005209 if (E == nullptr)
5210 return false;
5211 llvm::APSInt Result;
5212 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5213 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5214 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005215}
5216
Alexey Bataev5a3af132016-03-29 08:58:54 +00005217/// Build preinits statement for the given declarations.
5218static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005219 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005220 if (!PreInits.empty()) {
5221 return new (Context) DeclStmt(
5222 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5223 SourceLocation(), SourceLocation());
5224 }
5225 return nullptr;
5226}
5227
5228/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005229static Stmt *
5230buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005231 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005232 if (!Captures.empty()) {
5233 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005234 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005235 PreInits.push_back(Pair.second->getDecl());
5236 return buildPreInits(Context, PreInits);
5237 }
5238 return nullptr;
5239}
5240
5241/// Build postupdate expression for the given list of postupdates expressions.
5242static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5243 Expr *PostUpdate = nullptr;
5244 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005245 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005246 Expr *ConvE = S.BuildCStyleCastExpr(
5247 E->getExprLoc(),
5248 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5249 E->getExprLoc(), E)
5250 .get();
5251 PostUpdate = PostUpdate
5252 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5253 PostUpdate, ConvE)
5254 .get()
5255 : ConvE;
5256 }
5257 }
5258 return PostUpdate;
5259}
5260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005261/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005262/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5263/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005264static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005265checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005266 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5267 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005268 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005269 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005270 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005271 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005272 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005273 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005274 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005275 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005276 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005277 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005278 if (OrderedLoopCountExpr) {
5279 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005280 Expr::EvalResult EVResult;
5281 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5282 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005283 if (Result.getLimitedValue() < NestedLoopCount) {
5284 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5285 diag::err_omp_wrong_ordered_loop_count)
5286 << OrderedLoopCountExpr->getSourceRange();
5287 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5288 diag::note_collapse_loop_count)
5289 << CollapseLoopCountExpr->getSourceRange();
5290 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005291 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005292 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005293 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005294 // This is helper routine for loop directives (e.g., 'for', 'simd',
5295 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005296 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005297 SmallVector<LoopIterationSpace, 4> IterSpaces(
5298 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005299 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005300 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005301 if (checkOpenMPIterationSpace(
5302 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5303 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5304 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5305 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005306 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005307 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005308 // OpenMP [2.8.1, simd construct, Restrictions]
5309 // All loops associated with the construct must be perfectly nested; that
5310 // is, there must be no intervening code nor any OpenMP directive between
5311 // any two loops.
5312 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005313 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005314 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5315 if (checkOpenMPIterationSpace(
5316 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5317 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5318 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5319 Captures))
5320 return 0;
5321 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5322 // Handle initialization of captured loop iterator variables.
5323 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5324 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5325 Captures[DRE] = DRE;
5326 }
5327 }
5328 // Move on to the next nested for loop, or to the loop body.
5329 // OpenMP [2.8.1, simd construct, Restrictions]
5330 // All loops associated with the construct must be perfectly nested; that
5331 // is, there must be no intervening code nor any OpenMP directive between
5332 // any two loops.
5333 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5334 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005335
Alexander Musmana5f070a2014-10-01 06:03:56 +00005336 Built.clear(/* size */ NestedLoopCount);
5337
5338 if (SemaRef.CurContext->isDependentContext())
5339 return NestedLoopCount;
5340
5341 // An example of what is generated for the following code:
5342 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005343 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005344 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005345 // for (k = 0; k < NK; ++k)
5346 // for (j = J0; j < NJ; j+=2) {
5347 // <loop body>
5348 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005349 //
5350 // We generate the code below.
5351 // Note: the loop body may be outlined in CodeGen.
5352 // Note: some counters may be C++ classes, operator- is used to find number of
5353 // iterations and operator+= to calculate counter value.
5354 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5355 // or i64 is currently supported).
5356 //
5357 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5358 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5359 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5360 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5361 // // similar updates for vars in clauses (e.g. 'linear')
5362 // <loop body (using local i and j)>
5363 // }
5364 // i = NI; // assign final values of counters
5365 // j = NJ;
5366 //
5367
5368 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5369 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005370 // Precondition tests if there is at least one iteration (all conditions are
5371 // true).
5372 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005373 Expr *N0 = IterSpaces[0].NumIterations;
5374 ExprResult LastIteration32 =
5375 widenIterationCount(/*Bits=*/32,
5376 SemaRef
5377 .PerformImplicitConversion(
5378 N0->IgnoreImpCasts(), N0->getType(),
5379 Sema::AA_Converting, /*AllowExplicit=*/true)
5380 .get(),
5381 SemaRef);
5382 ExprResult LastIteration64 = widenIterationCount(
5383 /*Bits=*/64,
5384 SemaRef
5385 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5386 Sema::AA_Converting,
5387 /*AllowExplicit=*/true)
5388 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005389 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005390
5391 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5392 return NestedLoopCount;
5393
Alexey Bataeve3727102018-04-18 15:57:46 +00005394 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005395 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5396
5397 Scope *CurScope = DSA.getCurScope();
5398 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005399 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005400 PreCond =
5401 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5402 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005403 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005404 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005405 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005406 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5407 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005408 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005409 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005410 SemaRef
5411 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5412 Sema::AA_Converting,
5413 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005414 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005415 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005416 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005417 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005418 SemaRef
5419 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5420 Sema::AA_Converting,
5421 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005422 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005423 }
5424
5425 // Choose either the 32-bit or 64-bit version.
5426 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005427 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5428 (LastIteration32.isUsable() &&
5429 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5430 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5431 fitsInto(
5432 /*Bits=*/32,
5433 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5434 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005435 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005436 QualType VType = LastIteration.get()->getType();
5437 QualType RealVType = VType;
5438 QualType StrideVType = VType;
5439 if (isOpenMPTaskLoopDirective(DKind)) {
5440 VType =
5441 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5442 StrideVType =
5443 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5444 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005445
5446 if (!LastIteration.isUsable())
5447 return 0;
5448
5449 // Save the number of iterations.
5450 ExprResult NumIterations = LastIteration;
5451 {
5452 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005453 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5454 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005455 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5456 if (!LastIteration.isUsable())
5457 return 0;
5458 }
5459
5460 // Calculate the last iteration number beforehand instead of doing this on
5461 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5462 llvm::APSInt Result;
5463 bool IsConstant =
5464 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5465 ExprResult CalcLastIteration;
5466 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005467 ExprResult SaveRef =
5468 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005469 LastIteration = SaveRef;
5470
5471 // Prepare SaveRef + 1.
5472 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005473 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005474 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5475 if (!NumIterations.isUsable())
5476 return 0;
5477 }
5478
5479 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5480
David Majnemer9d168222016-08-05 17:44:54 +00005481 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005482 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005483 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5484 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005485 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005486 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5487 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005488 SemaRef.AddInitializerToDecl(LBDecl,
5489 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5490 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005491
5492 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005493 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5494 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005495 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005496 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005497
5498 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5499 // This will be used to implement clause 'lastprivate'.
5500 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005501 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5502 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005503 SemaRef.AddInitializerToDecl(ILDecl,
5504 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5505 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005506
5507 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005508 VarDecl *STDecl =
5509 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5510 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005511 SemaRef.AddInitializerToDecl(STDecl,
5512 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5513 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005514
5515 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005516 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005517 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5518 UB.get(), LastIteration.get());
5519 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005520 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5521 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005522 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5523 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005524 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005525
5526 // If we have a combined directive that combines 'distribute', 'for' or
5527 // 'simd' we need to be able to access the bounds of the schedule of the
5528 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5529 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5530 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005531 // Lower bound variable, initialized with zero.
5532 VarDecl *CombLBDecl =
5533 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5534 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5535 SemaRef.AddInitializerToDecl(
5536 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5537 /*DirectInit*/ false);
5538
5539 // Upper bound variable, initialized with last iteration number.
5540 VarDecl *CombUBDecl =
5541 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5542 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5543 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5544 /*DirectInit*/ false);
5545
5546 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5547 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5548 ExprResult CombCondOp =
5549 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5550 LastIteration.get(), CombUB.get());
5551 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5552 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005553 CombEUB =
5554 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005555
Alexey Bataeve3727102018-04-18 15:57:46 +00005556 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005557 // We expect to have at least 2 more parameters than the 'parallel'
5558 // directive does - the lower and upper bounds of the previous schedule.
5559 assert(CD->getNumParams() >= 4 &&
5560 "Unexpected number of parameters in loop combined directive");
5561
5562 // Set the proper type for the bounds given what we learned from the
5563 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005564 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5565 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005566
5567 // Previous lower and upper bounds are obtained from the region
5568 // parameters.
5569 PrevLB =
5570 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5571 PrevUB =
5572 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5573 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005574 }
5575
5576 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005577 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005578 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005579 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005580 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5581 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005582 Expr *RHS =
5583 (isOpenMPWorksharingDirective(DKind) ||
5584 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5585 ? LB.get()
5586 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005587 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005588 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005589
5590 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5591 Expr *CombRHS =
5592 (isOpenMPWorksharingDirective(DKind) ||
5593 isOpenMPTaskLoopDirective(DKind) ||
5594 isOpenMPDistributeDirective(DKind))
5595 ? CombLB.get()
5596 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5597 CombInit =
5598 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005599 CombInit =
5600 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005601 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005602 }
5603
Alexey Bataev316ccf62019-01-29 18:51:58 +00005604 bool UseStrictCompare =
5605 RealVType->hasUnsignedIntegerRepresentation() &&
5606 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5607 return LIS.IsStrictCompare;
5608 });
5609 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5610 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005611 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005612 Expr *BoundUB = UB.get();
5613 if (UseStrictCompare) {
5614 BoundUB =
5615 SemaRef
5616 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5617 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5618 .get();
5619 BoundUB =
5620 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5621 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005622 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005623 (isOpenMPWorksharingDirective(DKind) ||
5624 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005625 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5626 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5627 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005628 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5629 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005630 ExprResult CombDistCond;
5631 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005632 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5633 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005634 }
5635
Carlo Bertolliffafe102017-04-20 00:39:39 +00005636 ExprResult CombCond;
5637 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005638 Expr *BoundCombUB = CombUB.get();
5639 if (UseStrictCompare) {
5640 BoundCombUB =
5641 SemaRef
5642 .BuildBinOp(
5643 CurScope, CondLoc, BO_Add, BoundCombUB,
5644 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5645 .get();
5646 BoundCombUB =
5647 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5648 .get();
5649 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005650 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005651 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5652 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005653 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005654 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005655 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005656 ExprResult Inc =
5657 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5658 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5659 if (!Inc.isUsable())
5660 return 0;
5661 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005662 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005663 if (!Inc.isUsable())
5664 return 0;
5665
5666 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5667 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005668 // In combined construct, add combined version that use CombLB and CombUB
5669 // base variables for the update
5670 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005671 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5672 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005673 // LB + ST
5674 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5675 if (!NextLB.isUsable())
5676 return 0;
5677 // LB = LB + ST
5678 NextLB =
5679 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005680 NextLB =
5681 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005682 if (!NextLB.isUsable())
5683 return 0;
5684 // UB + ST
5685 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5686 if (!NextUB.isUsable())
5687 return 0;
5688 // UB = UB + ST
5689 NextUB =
5690 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005691 NextUB =
5692 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005693 if (!NextUB.isUsable())
5694 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005695 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5696 CombNextLB =
5697 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5698 if (!NextLB.isUsable())
5699 return 0;
5700 // LB = LB + ST
5701 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5702 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005703 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5704 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005705 if (!CombNextLB.isUsable())
5706 return 0;
5707 // UB + ST
5708 CombNextUB =
5709 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5710 if (!CombNextUB.isUsable())
5711 return 0;
5712 // UB = UB + ST
5713 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5714 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005715 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5716 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005717 if (!CombNextUB.isUsable())
5718 return 0;
5719 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005720 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005721
Carlo Bertolliffafe102017-04-20 00:39:39 +00005722 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005723 // directive with for as IV = IV + ST; ensure upper bound expression based
5724 // on PrevUB instead of NumIterations - used to implement 'for' when found
5725 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005726 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005727 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005728 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005729 DistCond = SemaRef.BuildBinOp(
5730 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005731 assert(DistCond.isUsable() && "distribute cond expr was not built");
5732
5733 DistInc =
5734 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5735 assert(DistInc.isUsable() && "distribute inc expr was not built");
5736 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5737 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005738 DistInc =
5739 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005740 assert(DistInc.isUsable() && "distribute inc expr was not built");
5741
5742 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5743 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005744 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005745 ExprResult IsUBGreater =
5746 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5747 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5748 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5749 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5750 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005751 PrevEUB =
5752 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005753
Alexey Bataev316ccf62019-01-29 18:51:58 +00005754 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5755 // parallel for is in combination with a distribute directive with
5756 // schedule(static, 1)
5757 Expr *BoundPrevUB = PrevUB.get();
5758 if (UseStrictCompare) {
5759 BoundPrevUB =
5760 SemaRef
5761 .BuildBinOp(
5762 CurScope, CondLoc, BO_Add, BoundPrevUB,
5763 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5764 .get();
5765 BoundPrevUB =
5766 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5767 .get();
5768 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005769 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005770 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5771 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005772 }
5773
Alexander Musmana5f070a2014-10-01 06:03:56 +00005774 // Build updates and final values of the loop counters.
5775 bool HasErrors = false;
5776 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005777 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005778 Built.Updates.resize(NestedLoopCount);
5779 Built.Finals.resize(NestedLoopCount);
5780 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005781 // We implement the following algorithm for obtaining the
5782 // original loop iteration variable values based on the
5783 // value of the collapsed loop iteration variable IV.
5784 //
5785 // Let n+1 be the number of collapsed loops in the nest.
5786 // Iteration variables (I0, I1, .... In)
5787 // Iteration counts (N0, N1, ... Nn)
5788 //
5789 // Acc = IV;
5790 //
5791 // To compute Ik for loop k, 0 <= k <= n, generate:
5792 // Prod = N(k+1) * N(k+2) * ... * Nn;
5793 // Ik = Acc / Prod;
5794 // Acc -= Ik * Prod;
5795 //
5796 ExprResult Acc = IV;
5797 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005798 LoopIterationSpace &IS = IterSpaces[Cnt];
5799 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005800 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005801
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005802 // Compute prod
5803 ExprResult Prod =
5804 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5805 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5806 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5807 IterSpaces[K].NumIterations);
5808
5809 // Iter = Acc / Prod
5810 // If there is at least one more inner loop to avoid
5811 // multiplication by 1.
5812 if (Cnt + 1 < NestedLoopCount)
5813 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5814 Acc.get(), Prod.get());
5815 else
5816 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005817 if (!Iter.isUsable()) {
5818 HasErrors = true;
5819 break;
5820 }
5821
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005822 // Update Acc:
5823 // Acc -= Iter * Prod
5824 // Check if there is at least one more inner loop to avoid
5825 // multiplication by 1.
5826 if (Cnt + 1 < NestedLoopCount)
5827 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5828 Iter.get(), Prod.get());
5829 else
5830 Prod = Iter;
5831 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5832 Acc.get(), Prod.get());
5833
Alexey Bataev39f915b82015-05-08 10:41:21 +00005834 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005835 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005836 DeclRefExpr *CounterVar = buildDeclRefExpr(
5837 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5838 /*RefersToCapture=*/true);
5839 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005840 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005841 if (!Init.isUsable()) {
5842 HasErrors = true;
5843 break;
5844 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005845 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005846 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5847 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005848 if (!Update.isUsable()) {
5849 HasErrors = true;
5850 break;
5851 }
5852
5853 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005854 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005855 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005856 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005857 if (!Final.isUsable()) {
5858 HasErrors = true;
5859 break;
5860 }
5861
Alexander Musmana5f070a2014-10-01 06:03:56 +00005862 if (!Update.isUsable() || !Final.isUsable()) {
5863 HasErrors = true;
5864 break;
5865 }
5866 // Save results
5867 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005868 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005869 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005870 Built.Updates[Cnt] = Update.get();
5871 Built.Finals[Cnt] = Final.get();
5872 }
5873 }
5874
5875 if (HasErrors)
5876 return 0;
5877
5878 // Save results
5879 Built.IterationVarRef = IV.get();
5880 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005881 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005882 Built.CalcLastIteration = SemaRef
5883 .ActOnFinishFullExpr(CalcLastIteration.get(),
5884 /*DiscardedValue*/ false)
5885 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005886 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005887 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005888 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005889 Built.Init = Init.get();
5890 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005891 Built.LB = LB.get();
5892 Built.UB = UB.get();
5893 Built.IL = IL.get();
5894 Built.ST = ST.get();
5895 Built.EUB = EUB.get();
5896 Built.NLB = NextLB.get();
5897 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005898 Built.PrevLB = PrevLB.get();
5899 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005900 Built.DistInc = DistInc.get();
5901 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005902 Built.DistCombinedFields.LB = CombLB.get();
5903 Built.DistCombinedFields.UB = CombUB.get();
5904 Built.DistCombinedFields.EUB = CombEUB.get();
5905 Built.DistCombinedFields.Init = CombInit.get();
5906 Built.DistCombinedFields.Cond = CombCond.get();
5907 Built.DistCombinedFields.NLB = CombNextLB.get();
5908 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005909 Built.DistCombinedFields.DistCond = CombDistCond.get();
5910 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005911
Alexey Bataevabfc0692014-06-25 06:52:00 +00005912 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005913}
5914
Alexey Bataev10e775f2015-07-30 11:36:16 +00005915static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005916 auto CollapseClauses =
5917 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5918 if (CollapseClauses.begin() != CollapseClauses.end())
5919 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005920 return nullptr;
5921}
5922
Alexey Bataev10e775f2015-07-30 11:36:16 +00005923static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005924 auto OrderedClauses =
5925 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5926 if (OrderedClauses.begin() != OrderedClauses.end())
5927 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005928 return nullptr;
5929}
5930
Kelvin Lic5609492016-07-15 04:39:07 +00005931static bool checkSimdlenSafelenSpecified(Sema &S,
5932 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005933 const OMPSafelenClause *Safelen = nullptr;
5934 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00005935
Alexey Bataeve3727102018-04-18 15:57:46 +00005936 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00005937 if (Clause->getClauseKind() == OMPC_safelen)
5938 Safelen = cast<OMPSafelenClause>(Clause);
5939 else if (Clause->getClauseKind() == OMPC_simdlen)
5940 Simdlen = cast<OMPSimdlenClause>(Clause);
5941 if (Safelen && Simdlen)
5942 break;
5943 }
5944
5945 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005946 const Expr *SimdlenLength = Simdlen->getSimdlen();
5947 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00005948 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5949 SimdlenLength->isInstantiationDependent() ||
5950 SimdlenLength->containsUnexpandedParameterPack())
5951 return false;
5952 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5953 SafelenLength->isInstantiationDependent() ||
5954 SafelenLength->containsUnexpandedParameterPack())
5955 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005956 Expr::EvalResult SimdlenResult, SafelenResult;
5957 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5958 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5959 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5960 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00005961 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5962 // If both simdlen and safelen clauses are specified, the value of the
5963 // simdlen parameter must be less than or equal to the value of the safelen
5964 // parameter.
5965 if (SimdlenRes > SafelenRes) {
5966 S.Diag(SimdlenLength->getExprLoc(),
5967 diag::err_omp_wrong_simdlen_safelen_values)
5968 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5969 return true;
5970 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005971 }
5972 return false;
5973}
5974
Alexey Bataeve3727102018-04-18 15:57:46 +00005975StmtResult
5976Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5977 SourceLocation StartLoc, SourceLocation EndLoc,
5978 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005979 if (!AStmt)
5980 return StmtError();
5981
5982 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005983 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005984 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5985 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005986 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005987 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5988 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005989 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005990 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005991
Alexander Musmana5f070a2014-10-01 06:03:56 +00005992 assert((CurContext->isDependentContext() || B.builtAll()) &&
5993 "omp simd loop exprs were not built");
5994
Alexander Musman3276a272015-03-21 10:12:56 +00005995 if (!CurContext->isDependentContext()) {
5996 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005997 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005998 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005999 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006000 B.NumIterations, *this, CurScope,
6001 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006002 return StmtError();
6003 }
6004 }
6005
Kelvin Lic5609492016-07-15 04:39:07 +00006006 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006007 return StmtError();
6008
Reid Kleckner87a31802018-03-12 21:43:02 +00006009 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006010 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6011 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006012}
6013
Alexey Bataeve3727102018-04-18 15:57:46 +00006014StmtResult
6015Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6016 SourceLocation StartLoc, SourceLocation EndLoc,
6017 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006018 if (!AStmt)
6019 return StmtError();
6020
6021 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006022 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006023 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6024 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006025 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006026 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6027 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006028 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006029 return StmtError();
6030
Alexander Musmana5f070a2014-10-01 06:03:56 +00006031 assert((CurContext->isDependentContext() || B.builtAll()) &&
6032 "omp for loop exprs were not built");
6033
Alexey Bataev54acd402015-08-04 11:18:19 +00006034 if (!CurContext->isDependentContext()) {
6035 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006036 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006037 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006038 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006039 B.NumIterations, *this, CurScope,
6040 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006041 return StmtError();
6042 }
6043 }
6044
Reid Kleckner87a31802018-03-12 21:43:02 +00006045 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006046 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006047 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006048}
6049
Alexander Musmanf82886e2014-09-18 05:12:34 +00006050StmtResult Sema::ActOnOpenMPForSimdDirective(
6051 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006052 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006053 if (!AStmt)
6054 return StmtError();
6055
6056 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006057 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006058 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6059 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006060 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006061 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006062 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6063 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006064 if (NestedLoopCount == 0)
6065 return StmtError();
6066
Alexander Musmanc6388682014-12-15 07:07:06 +00006067 assert((CurContext->isDependentContext() || B.builtAll()) &&
6068 "omp for simd loop exprs were not built");
6069
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006070 if (!CurContext->isDependentContext()) {
6071 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006072 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006073 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006074 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006075 B.NumIterations, *this, CurScope,
6076 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006077 return StmtError();
6078 }
6079 }
6080
Kelvin Lic5609492016-07-15 04:39:07 +00006081 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006082 return StmtError();
6083
Reid Kleckner87a31802018-03-12 21:43:02 +00006084 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006085 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6086 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006087}
6088
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006089StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6090 Stmt *AStmt,
6091 SourceLocation StartLoc,
6092 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006093 if (!AStmt)
6094 return StmtError();
6095
6096 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006097 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006098 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006099 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006100 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006101 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006102 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006103 return StmtError();
6104 // All associated statements must be '#pragma omp section' except for
6105 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006106 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006107 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6108 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006109 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006110 diag::err_omp_sections_substmt_not_section);
6111 return StmtError();
6112 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006113 cast<OMPSectionDirective>(SectionStmt)
6114 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006115 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006116 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006117 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006118 return StmtError();
6119 }
6120
Reid Kleckner87a31802018-03-12 21:43:02 +00006121 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006122
Alexey Bataev25e5b442015-09-15 12:52:43 +00006123 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6124 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006125}
6126
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006127StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6128 SourceLocation StartLoc,
6129 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006130 if (!AStmt)
6131 return StmtError();
6132
6133 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006134
Reid Kleckner87a31802018-03-12 21:43:02 +00006135 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006136 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006137
Alexey Bataev25e5b442015-09-15 12:52:43 +00006138 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6139 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006140}
6141
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006142StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6143 Stmt *AStmt,
6144 SourceLocation StartLoc,
6145 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006146 if (!AStmt)
6147 return StmtError();
6148
6149 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006150
Reid Kleckner87a31802018-03-12 21:43:02 +00006151 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006152
Alexey Bataev3255bf32015-01-19 05:20:46 +00006153 // OpenMP [2.7.3, single Construct, Restrictions]
6154 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006155 const OMPClause *Nowait = nullptr;
6156 const OMPClause *Copyprivate = nullptr;
6157 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006158 if (Clause->getClauseKind() == OMPC_nowait)
6159 Nowait = Clause;
6160 else if (Clause->getClauseKind() == OMPC_copyprivate)
6161 Copyprivate = Clause;
6162 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006163 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006164 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006165 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006166 return StmtError();
6167 }
6168 }
6169
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006170 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6171}
6172
Alexander Musman80c22892014-07-17 08:54:58 +00006173StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6174 SourceLocation StartLoc,
6175 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006176 if (!AStmt)
6177 return StmtError();
6178
6179 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006180
Reid Kleckner87a31802018-03-12 21:43:02 +00006181 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006182
6183 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6184}
6185
Alexey Bataev28c75412015-12-15 08:19:24 +00006186StmtResult Sema::ActOnOpenMPCriticalDirective(
6187 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6188 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006189 if (!AStmt)
6190 return StmtError();
6191
6192 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006193
Alexey Bataev28c75412015-12-15 08:19:24 +00006194 bool ErrorFound = false;
6195 llvm::APSInt Hint;
6196 SourceLocation HintLoc;
6197 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006198 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006199 if (C->getClauseKind() == OMPC_hint) {
6200 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006201 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006202 ErrorFound = true;
6203 }
6204 Expr *E = cast<OMPHintClause>(C)->getHint();
6205 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006206 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006207 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006208 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006209 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006210 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006211 }
6212 }
6213 }
6214 if (ErrorFound)
6215 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006216 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006217 if (Pair.first && DirName.getName() && !DependentHint) {
6218 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6219 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006220 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006221 Diag(HintLoc, diag::note_omp_critical_hint_here)
6222 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006223 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006224 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006225 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006226 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006227 << 1
6228 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6229 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006230 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006231 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006232 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006233 }
6234 }
6235
Reid Kleckner87a31802018-03-12 21:43:02 +00006236 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006237
Alexey Bataev28c75412015-12-15 08:19:24 +00006238 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6239 Clauses, AStmt);
6240 if (!Pair.first && DirName.getName() && !DependentHint)
6241 DSAStack->addCriticalWithHint(Dir, Hint);
6242 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006243}
6244
Alexey Bataev4acb8592014-07-07 13:01:15 +00006245StmtResult Sema::ActOnOpenMPParallelForDirective(
6246 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006247 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006248 if (!AStmt)
6249 return StmtError();
6250
Alexey Bataeve3727102018-04-18 15:57:46 +00006251 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006252 // 1.2.2 OpenMP Language Terminology
6253 // Structured block - An executable statement with a single entry at the
6254 // top and a single exit at the bottom.
6255 // The point of exit cannot be a branch out of the structured block.
6256 // longjmp() and throw() must not violate the entry/exit criteria.
6257 CS->getCapturedDecl()->setNothrow();
6258
Alexander Musmanc6388682014-12-15 07:07:06 +00006259 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006260 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6261 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006262 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006263 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006264 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6265 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006266 if (NestedLoopCount == 0)
6267 return StmtError();
6268
Alexander Musmana5f070a2014-10-01 06:03:56 +00006269 assert((CurContext->isDependentContext() || B.builtAll()) &&
6270 "omp parallel for loop exprs were not built");
6271
Alexey Bataev54acd402015-08-04 11:18:19 +00006272 if (!CurContext->isDependentContext()) {
6273 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006274 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006275 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006276 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006277 B.NumIterations, *this, CurScope,
6278 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006279 return StmtError();
6280 }
6281 }
6282
Reid Kleckner87a31802018-03-12 21:43:02 +00006283 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006284 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006285 NestedLoopCount, Clauses, AStmt, B,
6286 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006287}
6288
Alexander Musmane4e893b2014-09-23 09:33:00 +00006289StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6290 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006291 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006292 if (!AStmt)
6293 return StmtError();
6294
Alexey Bataeve3727102018-04-18 15:57:46 +00006295 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006296 // 1.2.2 OpenMP Language Terminology
6297 // Structured block - An executable statement with a single entry at the
6298 // top and a single exit at the bottom.
6299 // The point of exit cannot be a branch out of the structured block.
6300 // longjmp() and throw() must not violate the entry/exit criteria.
6301 CS->getCapturedDecl()->setNothrow();
6302
Alexander Musmanc6388682014-12-15 07:07:06 +00006303 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006304 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6305 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006306 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006307 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006308 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6309 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006310 if (NestedLoopCount == 0)
6311 return StmtError();
6312
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006313 if (!CurContext->isDependentContext()) {
6314 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006315 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006316 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006317 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006318 B.NumIterations, *this, CurScope,
6319 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006320 return StmtError();
6321 }
6322 }
6323
Kelvin Lic5609492016-07-15 04:39:07 +00006324 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006325 return StmtError();
6326
Reid Kleckner87a31802018-03-12 21:43:02 +00006327 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006328 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006329 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006330}
6331
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006332StmtResult
6333Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6334 Stmt *AStmt, SourceLocation StartLoc,
6335 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006336 if (!AStmt)
6337 return StmtError();
6338
6339 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006340 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006341 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006342 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006343 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006344 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006345 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006346 return StmtError();
6347 // All associated statements must be '#pragma omp section' except for
6348 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006349 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006350 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6351 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006352 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006353 diag::err_omp_parallel_sections_substmt_not_section);
6354 return StmtError();
6355 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006356 cast<OMPSectionDirective>(SectionStmt)
6357 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006358 }
6359 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006360 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006361 diag::err_omp_parallel_sections_not_compound_stmt);
6362 return StmtError();
6363 }
6364
Reid Kleckner87a31802018-03-12 21:43:02 +00006365 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006366
Alexey Bataev25e5b442015-09-15 12:52:43 +00006367 return OMPParallelSectionsDirective::Create(
6368 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006369}
6370
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006371StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6372 Stmt *AStmt, SourceLocation StartLoc,
6373 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006374 if (!AStmt)
6375 return StmtError();
6376
David Majnemer9d168222016-08-05 17:44:54 +00006377 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006378 // 1.2.2 OpenMP Language Terminology
6379 // Structured block - An executable statement with a single entry at the
6380 // top and a single exit at the bottom.
6381 // The point of exit cannot be a branch out of the structured block.
6382 // longjmp() and throw() must not violate the entry/exit criteria.
6383 CS->getCapturedDecl()->setNothrow();
6384
Reid Kleckner87a31802018-03-12 21:43:02 +00006385 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006386
Alexey Bataev25e5b442015-09-15 12:52:43 +00006387 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6388 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006389}
6390
Alexey Bataev68446b72014-07-18 07:47:19 +00006391StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6392 SourceLocation EndLoc) {
6393 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6394}
6395
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006396StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6397 SourceLocation EndLoc) {
6398 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6399}
6400
Alexey Bataev2df347a2014-07-18 10:17:07 +00006401StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6402 SourceLocation EndLoc) {
6403 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6404}
6405
Alexey Bataev169d96a2017-07-18 20:17:46 +00006406StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6407 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006408 SourceLocation StartLoc,
6409 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006410 if (!AStmt)
6411 return StmtError();
6412
6413 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006414
Reid Kleckner87a31802018-03-12 21:43:02 +00006415 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006416
Alexey Bataev169d96a2017-07-18 20:17:46 +00006417 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006418 AStmt,
6419 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006420}
6421
Alexey Bataev6125da92014-07-21 11:26:11 +00006422StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6423 SourceLocation StartLoc,
6424 SourceLocation EndLoc) {
6425 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6426 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6427}
6428
Alexey Bataev346265e2015-09-25 10:37:12 +00006429StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6430 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006431 SourceLocation StartLoc,
6432 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006433 const OMPClause *DependFound = nullptr;
6434 const OMPClause *DependSourceClause = nullptr;
6435 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006436 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006437 const OMPThreadsClause *TC = nullptr;
6438 const OMPSIMDClause *SC = nullptr;
6439 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006440 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6441 DependFound = C;
6442 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6443 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006444 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006445 << getOpenMPDirectiveName(OMPD_ordered)
6446 << getOpenMPClauseName(OMPC_depend) << 2;
6447 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006448 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006449 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006450 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006451 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006452 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006453 << 0;
6454 ErrorFound = true;
6455 }
6456 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6457 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006458 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006459 << 1;
6460 ErrorFound = true;
6461 }
6462 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006463 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006464 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006465 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006466 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006467 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006468 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006469 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006470 if (!ErrorFound && !SC &&
6471 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006472 // OpenMP [2.8.1,simd Construct, Restrictions]
6473 // An ordered construct with the simd clause is the only OpenMP construct
6474 // that can appear in the simd region.
6475 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006476 ErrorFound = true;
6477 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006478 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006479 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6480 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006481 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006482 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006483 diag::err_omp_ordered_directive_without_param);
6484 ErrorFound = true;
6485 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006486 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006487 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006488 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6489 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006490 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006491 ErrorFound = true;
6492 }
6493 }
6494 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006495 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006496
6497 if (AStmt) {
6498 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6499
Reid Kleckner87a31802018-03-12 21:43:02 +00006500 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006501 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006502
6503 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006504}
6505
Alexey Bataev1d160b12015-03-13 12:27:31 +00006506namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006507/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006508/// construct.
6509class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006510 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006511 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006512 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006513 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006514 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006515 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006516 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006517 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006518 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006519 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006520 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006521 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006522 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006523 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006524 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006525 /// expression.
6526 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006527 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006528 /// part.
6529 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006530 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006531 NoError
6532 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006533 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006534 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006535 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006536 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006537 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006538 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006539 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006540 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006541 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006542 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6543 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6544 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006545 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006546 /// important for non-associative operations.
6547 bool IsXLHSInRHSPart;
6548 BinaryOperatorKind Op;
6549 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006550 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006551 /// if it is a prefix unary operation.
6552 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006553
6554public:
6555 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006556 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006557 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006558 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006559 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006560 /// expression. If DiagId and NoteId == 0, then only check is performed
6561 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006562 /// \param DiagId Diagnostic which should be emitted if error is found.
6563 /// \param NoteId Diagnostic note for the main error message.
6564 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006565 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006566 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006567 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006568 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006569 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006570 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006571 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6572 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6573 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006574 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006575 /// false otherwise.
6576 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6577
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006578 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006579 /// if it is a prefix unary operation.
6580 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6581
Alexey Bataev1d160b12015-03-13 12:27:31 +00006582private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006583 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6584 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006585};
6586} // namespace
6587
6588bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6589 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6590 ExprAnalysisErrorCode ErrorFound = NoError;
6591 SourceLocation ErrorLoc, NoteLoc;
6592 SourceRange ErrorRange, NoteRange;
6593 // Allowed constructs are:
6594 // x = x binop expr;
6595 // x = expr binop x;
6596 if (AtomicBinOp->getOpcode() == BO_Assign) {
6597 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006598 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006599 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6600 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6601 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6602 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006603 Op = AtomicInnerBinOp->getOpcode();
6604 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006605 Expr *LHS = AtomicInnerBinOp->getLHS();
6606 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006607 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6608 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6609 /*Canonical=*/true);
6610 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6611 /*Canonical=*/true);
6612 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6613 /*Canonical=*/true);
6614 if (XId == LHSId) {
6615 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006616 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006617 } else if (XId == RHSId) {
6618 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006619 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006620 } else {
6621 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6622 ErrorRange = AtomicInnerBinOp->getSourceRange();
6623 NoteLoc = X->getExprLoc();
6624 NoteRange = X->getSourceRange();
6625 ErrorFound = NotAnUpdateExpression;
6626 }
6627 } else {
6628 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6629 ErrorRange = AtomicInnerBinOp->getSourceRange();
6630 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6631 NoteRange = SourceRange(NoteLoc, NoteLoc);
6632 ErrorFound = NotABinaryOperator;
6633 }
6634 } else {
6635 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6636 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6637 ErrorFound = NotABinaryExpression;
6638 }
6639 } else {
6640 ErrorLoc = AtomicBinOp->getExprLoc();
6641 ErrorRange = AtomicBinOp->getSourceRange();
6642 NoteLoc = AtomicBinOp->getOperatorLoc();
6643 NoteRange = SourceRange(NoteLoc, NoteLoc);
6644 ErrorFound = NotAnAssignmentOp;
6645 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006646 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006647 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6648 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6649 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006650 }
6651 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006652 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006653 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006654}
6655
6656bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6657 unsigned NoteId) {
6658 ExprAnalysisErrorCode ErrorFound = NoError;
6659 SourceLocation ErrorLoc, NoteLoc;
6660 SourceRange ErrorRange, NoteRange;
6661 // Allowed constructs are:
6662 // x++;
6663 // x--;
6664 // ++x;
6665 // --x;
6666 // x binop= expr;
6667 // x = x binop expr;
6668 // x = expr binop x;
6669 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6670 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6671 if (AtomicBody->getType()->isScalarType() ||
6672 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006673 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006674 AtomicBody->IgnoreParenImpCasts())) {
6675 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006676 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006677 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006678 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006679 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006680 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006681 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006682 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6683 AtomicBody->IgnoreParenImpCasts())) {
6684 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006685 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006686 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006687 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006688 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006689 // Check for Unary Operation
6690 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006691 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006692 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6693 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006694 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006695 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6696 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006697 } else {
6698 ErrorFound = NotAnUnaryIncDecExpression;
6699 ErrorLoc = AtomicUnaryOp->getExprLoc();
6700 ErrorRange = AtomicUnaryOp->getSourceRange();
6701 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6702 NoteRange = SourceRange(NoteLoc, NoteLoc);
6703 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006704 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006705 ErrorFound = NotABinaryOrUnaryExpression;
6706 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6707 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6708 }
6709 } else {
6710 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006711 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006712 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6713 }
6714 } else {
6715 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006716 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006717 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6718 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006719 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006720 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6721 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6722 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006723 }
6724 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006725 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006726 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006727 // Build an update expression of form 'OpaqueValueExpr(x) binop
6728 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6729 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6730 auto *OVEX = new (SemaRef.getASTContext())
6731 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6732 auto *OVEExpr = new (SemaRef.getASTContext())
6733 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006734 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006735 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6736 IsXLHSInRHSPart ? OVEExpr : OVEX);
6737 if (Update.isInvalid())
6738 return true;
6739 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6740 Sema::AA_Casting);
6741 if (Update.isInvalid())
6742 return true;
6743 UpdateExpr = Update.get();
6744 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006745 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006746}
6747
Alexey Bataev0162e452014-07-22 10:10:35 +00006748StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6749 Stmt *AStmt,
6750 SourceLocation StartLoc,
6751 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006752 if (!AStmt)
6753 return StmtError();
6754
David Majnemer9d168222016-08-05 17:44:54 +00006755 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006756 // 1.2.2 OpenMP Language Terminology
6757 // Structured block - An executable statement with a single entry at the
6758 // top and a single exit at the bottom.
6759 // The point of exit cannot be a branch out of the structured block.
6760 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006761 OpenMPClauseKind AtomicKind = OMPC_unknown;
6762 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006763 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006764 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006765 C->getClauseKind() == OMPC_update ||
6766 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006767 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006768 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006769 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006770 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6771 << getOpenMPClauseName(AtomicKind);
6772 } else {
6773 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006774 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006775 }
6776 }
6777 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006778
Alexey Bataeve3727102018-04-18 15:57:46 +00006779 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006780 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6781 Body = EWC->getSubExpr();
6782
Alexey Bataev62cec442014-11-18 10:14:22 +00006783 Expr *X = nullptr;
6784 Expr *V = nullptr;
6785 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006786 Expr *UE = nullptr;
6787 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006788 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006789 // OpenMP [2.12.6, atomic Construct]
6790 // In the next expressions:
6791 // * x and v (as applicable) are both l-value expressions with scalar type.
6792 // * During the execution of an atomic region, multiple syntactic
6793 // occurrences of x must designate the same storage location.
6794 // * Neither of v and expr (as applicable) may access the storage location
6795 // designated by x.
6796 // * Neither of x and expr (as applicable) may access the storage location
6797 // designated by v.
6798 // * expr is an expression with scalar type.
6799 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6800 // * binop, binop=, ++, and -- are not overloaded operators.
6801 // * The expression x binop expr must be numerically equivalent to x binop
6802 // (expr). This requirement is satisfied if the operators in expr have
6803 // precedence greater than binop, or by using parentheses around expr or
6804 // subexpressions of expr.
6805 // * The expression expr binop x must be numerically equivalent to (expr)
6806 // binop x. This requirement is satisfied if the operators in expr have
6807 // precedence equal to or greater than binop, or by using parentheses around
6808 // expr or subexpressions of expr.
6809 // * For forms that allow multiple occurrences of x, the number of times
6810 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006811 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006812 enum {
6813 NotAnExpression,
6814 NotAnAssignmentOp,
6815 NotAScalarType,
6816 NotAnLValue,
6817 NoError
6818 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006819 SourceLocation ErrorLoc, NoteLoc;
6820 SourceRange ErrorRange, NoteRange;
6821 // If clause is read:
6822 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006823 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6824 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006825 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6826 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6827 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6828 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6829 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6830 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6831 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006832 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006833 ErrorFound = NotAnLValue;
6834 ErrorLoc = AtomicBinOp->getExprLoc();
6835 ErrorRange = AtomicBinOp->getSourceRange();
6836 NoteLoc = NotLValueExpr->getExprLoc();
6837 NoteRange = NotLValueExpr->getSourceRange();
6838 }
6839 } else if (!X->isInstantiationDependent() ||
6840 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006841 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006842 (X->isInstantiationDependent() || X->getType()->isScalarType())
6843 ? V
6844 : X;
6845 ErrorFound = NotAScalarType;
6846 ErrorLoc = AtomicBinOp->getExprLoc();
6847 ErrorRange = AtomicBinOp->getSourceRange();
6848 NoteLoc = NotScalarExpr->getExprLoc();
6849 NoteRange = NotScalarExpr->getSourceRange();
6850 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006851 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006852 ErrorFound = NotAnAssignmentOp;
6853 ErrorLoc = AtomicBody->getExprLoc();
6854 ErrorRange = AtomicBody->getSourceRange();
6855 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6856 : AtomicBody->getExprLoc();
6857 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6858 : AtomicBody->getSourceRange();
6859 }
6860 } else {
6861 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006862 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006863 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006864 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006865 if (ErrorFound != NoError) {
6866 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6867 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006868 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6869 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006870 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006871 }
6872 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00006873 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006874 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006875 enum {
6876 NotAnExpression,
6877 NotAnAssignmentOp,
6878 NotAScalarType,
6879 NotAnLValue,
6880 NoError
6881 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006882 SourceLocation ErrorLoc, NoteLoc;
6883 SourceRange ErrorRange, NoteRange;
6884 // If clause is write:
6885 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00006886 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6887 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006888 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6889 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006890 X = AtomicBinOp->getLHS();
6891 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006892 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6893 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6894 if (!X->isLValue()) {
6895 ErrorFound = NotAnLValue;
6896 ErrorLoc = AtomicBinOp->getExprLoc();
6897 ErrorRange = AtomicBinOp->getSourceRange();
6898 NoteLoc = X->getExprLoc();
6899 NoteRange = X->getSourceRange();
6900 }
6901 } else if (!X->isInstantiationDependent() ||
6902 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006903 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006904 (X->isInstantiationDependent() || X->getType()->isScalarType())
6905 ? E
6906 : X;
6907 ErrorFound = NotAScalarType;
6908 ErrorLoc = AtomicBinOp->getExprLoc();
6909 ErrorRange = AtomicBinOp->getSourceRange();
6910 NoteLoc = NotScalarExpr->getExprLoc();
6911 NoteRange = NotScalarExpr->getSourceRange();
6912 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006913 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006914 ErrorFound = NotAnAssignmentOp;
6915 ErrorLoc = AtomicBody->getExprLoc();
6916 ErrorRange = AtomicBody->getSourceRange();
6917 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6918 : AtomicBody->getExprLoc();
6919 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6920 : AtomicBody->getSourceRange();
6921 }
6922 } else {
6923 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006924 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006925 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006926 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006927 if (ErrorFound != NoError) {
6928 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6929 << ErrorRange;
6930 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6931 << NoteRange;
6932 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006933 }
6934 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00006935 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006936 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006937 // If clause is update:
6938 // x++;
6939 // x--;
6940 // ++x;
6941 // --x;
6942 // x binop= expr;
6943 // x = x binop expr;
6944 // x = expr binop x;
6945 OpenMPAtomicUpdateChecker Checker(*this);
6946 if (Checker.checkStatement(
6947 Body, (AtomicKind == OMPC_update)
6948 ? diag::err_omp_atomic_update_not_expression_statement
6949 : diag::err_omp_atomic_not_expression_statement,
6950 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006951 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006952 if (!CurContext->isDependentContext()) {
6953 E = Checker.getExpr();
6954 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006955 UE = Checker.getUpdateExpr();
6956 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006957 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006958 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006959 enum {
6960 NotAnAssignmentOp,
6961 NotACompoundStatement,
6962 NotTwoSubstatements,
6963 NotASpecificExpression,
6964 NoError
6965 } ErrorFound = NoError;
6966 SourceLocation ErrorLoc, NoteLoc;
6967 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00006968 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006969 // If clause is a capture:
6970 // v = x++;
6971 // v = x--;
6972 // v = ++x;
6973 // v = --x;
6974 // v = x binop= expr;
6975 // v = x = x binop expr;
6976 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006977 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00006978 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6979 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6980 V = AtomicBinOp->getLHS();
6981 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6982 OpenMPAtomicUpdateChecker Checker(*this);
6983 if (Checker.checkStatement(
6984 Body, diag::err_omp_atomic_capture_not_expression_statement,
6985 diag::note_omp_atomic_update))
6986 return StmtError();
6987 E = Checker.getExpr();
6988 X = Checker.getX();
6989 UE = Checker.getUpdateExpr();
6990 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6991 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006992 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006993 ErrorLoc = AtomicBody->getExprLoc();
6994 ErrorRange = AtomicBody->getSourceRange();
6995 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6996 : AtomicBody->getExprLoc();
6997 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6998 : AtomicBody->getSourceRange();
6999 ErrorFound = NotAnAssignmentOp;
7000 }
7001 if (ErrorFound != NoError) {
7002 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7003 << ErrorRange;
7004 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7005 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007006 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007007 if (CurContext->isDependentContext())
7008 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007009 } else {
7010 // If clause is a capture:
7011 // { v = x; x = expr; }
7012 // { v = x; x++; }
7013 // { v = x; x--; }
7014 // { v = x; ++x; }
7015 // { v = x; --x; }
7016 // { v = x; x binop= expr; }
7017 // { v = x; x = x binop expr; }
7018 // { v = x; x = expr binop x; }
7019 // { x++; v = x; }
7020 // { x--; v = x; }
7021 // { ++x; v = x; }
7022 // { --x; v = x; }
7023 // { x binop= expr; v = x; }
7024 // { x = x binop expr; v = x; }
7025 // { x = expr binop x; v = x; }
7026 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7027 // Check that this is { expr1; expr2; }
7028 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007029 Stmt *First = CS->body_front();
7030 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007031 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7032 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7033 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7034 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7035 // Need to find what subexpression is 'v' and what is 'x'.
7036 OpenMPAtomicUpdateChecker Checker(*this);
7037 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7038 BinaryOperator *BinOp = nullptr;
7039 if (IsUpdateExprFound) {
7040 BinOp = dyn_cast<BinaryOperator>(First);
7041 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7042 }
7043 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7044 // { v = x; x++; }
7045 // { v = x; x--; }
7046 // { v = x; ++x; }
7047 // { v = x; --x; }
7048 // { v = x; x binop= expr; }
7049 // { v = x; x = x binop expr; }
7050 // { v = x; x = expr binop x; }
7051 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007052 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007053 llvm::FoldingSetNodeID XId, PossibleXId;
7054 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7055 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7056 IsUpdateExprFound = XId == PossibleXId;
7057 if (IsUpdateExprFound) {
7058 V = BinOp->getLHS();
7059 X = Checker.getX();
7060 E = Checker.getExpr();
7061 UE = Checker.getUpdateExpr();
7062 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007063 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007064 }
7065 }
7066 if (!IsUpdateExprFound) {
7067 IsUpdateExprFound = !Checker.checkStatement(First);
7068 BinOp = nullptr;
7069 if (IsUpdateExprFound) {
7070 BinOp = dyn_cast<BinaryOperator>(Second);
7071 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7072 }
7073 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7074 // { x++; v = x; }
7075 // { x--; v = x; }
7076 // { ++x; v = x; }
7077 // { --x; v = x; }
7078 // { x binop= expr; v = x; }
7079 // { x = x binop expr; v = x; }
7080 // { x = expr binop x; v = x; }
7081 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007082 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007083 llvm::FoldingSetNodeID XId, PossibleXId;
7084 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7085 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7086 IsUpdateExprFound = XId == PossibleXId;
7087 if (IsUpdateExprFound) {
7088 V = BinOp->getLHS();
7089 X = Checker.getX();
7090 E = Checker.getExpr();
7091 UE = Checker.getUpdateExpr();
7092 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007093 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007094 }
7095 }
7096 }
7097 if (!IsUpdateExprFound) {
7098 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007099 auto *FirstExpr = dyn_cast<Expr>(First);
7100 auto *SecondExpr = dyn_cast<Expr>(Second);
7101 if (!FirstExpr || !SecondExpr ||
7102 !(FirstExpr->isInstantiationDependent() ||
7103 SecondExpr->isInstantiationDependent())) {
7104 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7105 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007106 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007107 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007108 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007109 NoteRange = ErrorRange = FirstBinOp
7110 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007111 : SourceRange(ErrorLoc, ErrorLoc);
7112 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007113 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7114 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7115 ErrorFound = NotAnAssignmentOp;
7116 NoteLoc = ErrorLoc = SecondBinOp
7117 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007118 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007119 NoteRange = ErrorRange =
7120 SecondBinOp ? SecondBinOp->getSourceRange()
7121 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007122 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007123 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007124 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007125 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007126 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7127 llvm::FoldingSetNodeID X1Id, X2Id;
7128 PossibleXRHSInFirst->Profile(X1Id, Context,
7129 /*Canonical=*/true);
7130 PossibleXLHSInSecond->Profile(X2Id, Context,
7131 /*Canonical=*/true);
7132 IsUpdateExprFound = X1Id == X2Id;
7133 if (IsUpdateExprFound) {
7134 V = FirstBinOp->getLHS();
7135 X = SecondBinOp->getLHS();
7136 E = SecondBinOp->getRHS();
7137 UE = nullptr;
7138 IsXLHSInRHSPart = false;
7139 IsPostfixUpdate = true;
7140 } else {
7141 ErrorFound = NotASpecificExpression;
7142 ErrorLoc = FirstBinOp->getExprLoc();
7143 ErrorRange = FirstBinOp->getSourceRange();
7144 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7145 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7146 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007147 }
7148 }
7149 }
7150 }
7151 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007152 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007153 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007154 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007155 ErrorFound = NotTwoSubstatements;
7156 }
7157 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007158 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007159 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007160 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007161 ErrorFound = NotACompoundStatement;
7162 }
7163 if (ErrorFound != NoError) {
7164 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7165 << ErrorRange;
7166 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7167 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007168 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007169 if (CurContext->isDependentContext())
7170 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007171 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007172 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007173
Reid Kleckner87a31802018-03-12 21:43:02 +00007174 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007175
Alexey Bataev62cec442014-11-18 10:14:22 +00007176 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007177 X, V, E, UE, IsXLHSInRHSPart,
7178 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007179}
7180
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007181StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7182 Stmt *AStmt,
7183 SourceLocation StartLoc,
7184 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007185 if (!AStmt)
7186 return StmtError();
7187
Alexey Bataeve3727102018-04-18 15:57:46 +00007188 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007189 // 1.2.2 OpenMP Language Terminology
7190 // Structured block - An executable statement with a single entry at the
7191 // top and a single exit at the bottom.
7192 // The point of exit cannot be a branch out of the structured block.
7193 // longjmp() and throw() must not violate the entry/exit criteria.
7194 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007195 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7196 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7197 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7198 // 1.2.2 OpenMP Language Terminology
7199 // Structured block - An executable statement with a single entry at the
7200 // top and a single exit at the bottom.
7201 // The point of exit cannot be a branch out of the structured block.
7202 // longjmp() and throw() must not violate the entry/exit criteria.
7203 CS->getCapturedDecl()->setNothrow();
7204 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007205
Alexey Bataev13314bf2014-10-09 04:18:56 +00007206 // OpenMP [2.16, Nesting of Regions]
7207 // If specified, a teams construct must be contained within a target
7208 // construct. That target construct must contain no statements or directives
7209 // outside of the teams construct.
7210 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007211 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007212 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007213 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007214 auto I = CS->body_begin();
7215 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007216 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007217 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7218 OMPTeamsFound) {
7219
Alexey Bataev13314bf2014-10-09 04:18:56 +00007220 OMPTeamsFound = false;
7221 break;
7222 }
7223 ++I;
7224 }
7225 assert(I != CS->body_end() && "Not found statement");
7226 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007227 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007228 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007229 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007230 }
7231 if (!OMPTeamsFound) {
7232 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7233 Diag(DSAStack->getInnerTeamsRegionLoc(),
7234 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007235 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007236 << isa<OMPExecutableDirective>(S);
7237 return StmtError();
7238 }
7239 }
7240
Reid Kleckner87a31802018-03-12 21:43:02 +00007241 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007242
7243 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7244}
7245
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007246StmtResult
7247Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7248 Stmt *AStmt, SourceLocation StartLoc,
7249 SourceLocation EndLoc) {
7250 if (!AStmt)
7251 return StmtError();
7252
Alexey Bataeve3727102018-04-18 15:57:46 +00007253 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007254 // 1.2.2 OpenMP Language Terminology
7255 // Structured block - An executable statement with a single entry at the
7256 // top and a single exit at the bottom.
7257 // The point of exit cannot be a branch out of the structured block.
7258 // longjmp() and throw() must not violate the entry/exit criteria.
7259 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007260 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7261 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7262 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7263 // 1.2.2 OpenMP Language Terminology
7264 // Structured block - An executable statement with a single entry at the
7265 // top and a single exit at the bottom.
7266 // The point of exit cannot be a branch out of the structured block.
7267 // longjmp() and throw() must not violate the entry/exit criteria.
7268 CS->getCapturedDecl()->setNothrow();
7269 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007270
Reid Kleckner87a31802018-03-12 21:43:02 +00007271 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007272
7273 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7274 AStmt);
7275}
7276
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007277StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7278 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007279 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007280 if (!AStmt)
7281 return StmtError();
7282
Alexey Bataeve3727102018-04-18 15:57:46 +00007283 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007284 // 1.2.2 OpenMP Language Terminology
7285 // Structured block - An executable statement with a single entry at the
7286 // top and a single exit at the bottom.
7287 // The point of exit cannot be a branch out of the structured block.
7288 // longjmp() and throw() must not violate the entry/exit criteria.
7289 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007290 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7291 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7292 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7293 // 1.2.2 OpenMP Language Terminology
7294 // Structured block - An executable statement with a single entry at the
7295 // top and a single exit at the bottom.
7296 // The point of exit cannot be a branch out of the structured block.
7297 // longjmp() and throw() must not violate the entry/exit criteria.
7298 CS->getCapturedDecl()->setNothrow();
7299 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007300
7301 OMPLoopDirective::HelperExprs B;
7302 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7303 // define the nested loops number.
7304 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007305 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007306 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007307 VarsWithImplicitDSA, B);
7308 if (NestedLoopCount == 0)
7309 return StmtError();
7310
7311 assert((CurContext->isDependentContext() || B.builtAll()) &&
7312 "omp target parallel for loop exprs were not built");
7313
7314 if (!CurContext->isDependentContext()) {
7315 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007316 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007317 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007318 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007319 B.NumIterations, *this, CurScope,
7320 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007321 return StmtError();
7322 }
7323 }
7324
Reid Kleckner87a31802018-03-12 21:43:02 +00007325 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007326 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7327 NestedLoopCount, Clauses, AStmt,
7328 B, DSAStack->isCancelRegion());
7329}
7330
Alexey Bataev95b64a92017-05-30 16:00:04 +00007331/// Check for existence of a map clause in the list of clauses.
7332static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7333 const OpenMPClauseKind K) {
7334 return llvm::any_of(
7335 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7336}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007337
Alexey Bataev95b64a92017-05-30 16:00:04 +00007338template <typename... Params>
7339static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7340 const Params... ClauseTypes) {
7341 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007342}
7343
Michael Wong65f367f2015-07-21 13:44:28 +00007344StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7345 Stmt *AStmt,
7346 SourceLocation StartLoc,
7347 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007348 if (!AStmt)
7349 return StmtError();
7350
7351 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7352
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007353 // OpenMP [2.10.1, Restrictions, p. 97]
7354 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007355 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7356 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7357 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007358 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007359 return StmtError();
7360 }
7361
Reid Kleckner87a31802018-03-12 21:43:02 +00007362 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007363
7364 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7365 AStmt);
7366}
7367
Samuel Antaodf67fc42016-01-19 19:15:56 +00007368StmtResult
7369Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7370 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007371 SourceLocation EndLoc, Stmt *AStmt) {
7372 if (!AStmt)
7373 return StmtError();
7374
Alexey Bataeve3727102018-04-18 15:57:46 +00007375 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007376 // 1.2.2 OpenMP Language Terminology
7377 // Structured block - An executable statement with a single entry at the
7378 // top and a single exit at the bottom.
7379 // The point of exit cannot be a branch out of the structured block.
7380 // longjmp() and throw() must not violate the entry/exit criteria.
7381 CS->getCapturedDecl()->setNothrow();
7382 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7383 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7384 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7385 // 1.2.2 OpenMP Language Terminology
7386 // Structured block - An executable statement with a single entry at the
7387 // top and a single exit at the bottom.
7388 // The point of exit cannot be a branch out of the structured block.
7389 // longjmp() and throw() must not violate the entry/exit criteria.
7390 CS->getCapturedDecl()->setNothrow();
7391 }
7392
Samuel Antaodf67fc42016-01-19 19:15:56 +00007393 // OpenMP [2.10.2, Restrictions, p. 99]
7394 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007395 if (!hasClauses(Clauses, OMPC_map)) {
7396 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7397 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007398 return StmtError();
7399 }
7400
Alexey Bataev7828b252017-11-21 17:08:48 +00007401 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7402 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007403}
7404
Samuel Antao72590762016-01-19 20:04:50 +00007405StmtResult
7406Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7407 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007408 SourceLocation EndLoc, Stmt *AStmt) {
7409 if (!AStmt)
7410 return StmtError();
7411
Alexey Bataeve3727102018-04-18 15:57:46 +00007412 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007413 // 1.2.2 OpenMP Language Terminology
7414 // Structured block - An executable statement with a single entry at the
7415 // top and a single exit at the bottom.
7416 // The point of exit cannot be a branch out of the structured block.
7417 // longjmp() and throw() must not violate the entry/exit criteria.
7418 CS->getCapturedDecl()->setNothrow();
7419 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7420 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7421 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7422 // 1.2.2 OpenMP Language Terminology
7423 // Structured block - An executable statement with a single entry at the
7424 // top and a single exit at the bottom.
7425 // The point of exit cannot be a branch out of the structured block.
7426 // longjmp() and throw() must not violate the entry/exit criteria.
7427 CS->getCapturedDecl()->setNothrow();
7428 }
7429
Samuel Antao72590762016-01-19 20:04:50 +00007430 // OpenMP [2.10.3, Restrictions, p. 102]
7431 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007432 if (!hasClauses(Clauses, OMPC_map)) {
7433 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7434 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007435 return StmtError();
7436 }
7437
Alexey Bataev7828b252017-11-21 17:08:48 +00007438 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7439 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007440}
7441
Samuel Antao686c70c2016-05-26 17:30:50 +00007442StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7443 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007444 SourceLocation EndLoc,
7445 Stmt *AStmt) {
7446 if (!AStmt)
7447 return StmtError();
7448
Alexey Bataeve3727102018-04-18 15:57:46 +00007449 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007450 // 1.2.2 OpenMP Language Terminology
7451 // Structured block - An executable statement with a single entry at the
7452 // top and a single exit at the bottom.
7453 // The point of exit cannot be a branch out of the structured block.
7454 // longjmp() and throw() must not violate the entry/exit criteria.
7455 CS->getCapturedDecl()->setNothrow();
7456 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7457 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7458 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7459 // 1.2.2 OpenMP Language Terminology
7460 // Structured block - An executable statement with a single entry at the
7461 // top and a single exit at the bottom.
7462 // The point of exit cannot be a branch out of the structured block.
7463 // longjmp() and throw() must not violate the entry/exit criteria.
7464 CS->getCapturedDecl()->setNothrow();
7465 }
7466
Alexey Bataev95b64a92017-05-30 16:00:04 +00007467 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007468 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7469 return StmtError();
7470 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007471 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7472 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007473}
7474
Alexey Bataev13314bf2014-10-09 04:18:56 +00007475StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7476 Stmt *AStmt, SourceLocation StartLoc,
7477 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007478 if (!AStmt)
7479 return StmtError();
7480
Alexey Bataeve3727102018-04-18 15:57:46 +00007481 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007482 // 1.2.2 OpenMP Language Terminology
7483 // Structured block - An executable statement with a single entry at the
7484 // top and a single exit at the bottom.
7485 // The point of exit cannot be a branch out of the structured block.
7486 // longjmp() and throw() must not violate the entry/exit criteria.
7487 CS->getCapturedDecl()->setNothrow();
7488
Reid Kleckner87a31802018-03-12 21:43:02 +00007489 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007490
Alexey Bataevceabd412017-11-30 18:01:54 +00007491 DSAStack->setParentTeamsRegionLoc(StartLoc);
7492
Alexey Bataev13314bf2014-10-09 04:18:56 +00007493 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7494}
7495
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007496StmtResult
7497Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7498 SourceLocation EndLoc,
7499 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007500 if (DSAStack->isParentNowaitRegion()) {
7501 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7502 return StmtError();
7503 }
7504 if (DSAStack->isParentOrderedRegion()) {
7505 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7506 return StmtError();
7507 }
7508 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7509 CancelRegion);
7510}
7511
Alexey Bataev87933c72015-09-18 08:07:34 +00007512StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7513 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007514 SourceLocation EndLoc,
7515 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007516 if (DSAStack->isParentNowaitRegion()) {
7517 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7518 return StmtError();
7519 }
7520 if (DSAStack->isParentOrderedRegion()) {
7521 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7522 return StmtError();
7523 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007524 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007525 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7526 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007527}
7528
Alexey Bataev382967a2015-12-08 12:06:20 +00007529static bool checkGrainsizeNumTasksClauses(Sema &S,
7530 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007531 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007532 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007533 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007534 if (C->getClauseKind() == OMPC_grainsize ||
7535 C->getClauseKind() == OMPC_num_tasks) {
7536 if (!PrevClause)
7537 PrevClause = C;
7538 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007539 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007540 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7541 << getOpenMPClauseName(C->getClauseKind())
7542 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007543 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007544 diag::note_omp_previous_grainsize_num_tasks)
7545 << getOpenMPClauseName(PrevClause->getClauseKind());
7546 ErrorFound = true;
7547 }
7548 }
7549 }
7550 return ErrorFound;
7551}
7552
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007553static bool checkReductionClauseWithNogroup(Sema &S,
7554 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007555 const OMPClause *ReductionClause = nullptr;
7556 const OMPClause *NogroupClause = nullptr;
7557 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007558 if (C->getClauseKind() == OMPC_reduction) {
7559 ReductionClause = C;
7560 if (NogroupClause)
7561 break;
7562 continue;
7563 }
7564 if (C->getClauseKind() == OMPC_nogroup) {
7565 NogroupClause = C;
7566 if (ReductionClause)
7567 break;
7568 continue;
7569 }
7570 }
7571 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007572 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7573 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007574 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007575 return true;
7576 }
7577 return false;
7578}
7579
Alexey Bataev49f6e782015-12-01 04:18:41 +00007580StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7581 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007582 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007583 if (!AStmt)
7584 return StmtError();
7585
7586 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7587 OMPLoopDirective::HelperExprs B;
7588 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7589 // define the nested loops number.
7590 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007591 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007592 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007593 VarsWithImplicitDSA, B);
7594 if (NestedLoopCount == 0)
7595 return StmtError();
7596
7597 assert((CurContext->isDependentContext() || B.builtAll()) &&
7598 "omp for loop exprs were not built");
7599
Alexey Bataev382967a2015-12-08 12:06:20 +00007600 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7601 // The grainsize clause and num_tasks clause are mutually exclusive and may
7602 // not appear on the same taskloop directive.
7603 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7604 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007605 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7606 // If a reduction clause is present on the taskloop directive, the nogroup
7607 // clause must not be specified.
7608 if (checkReductionClauseWithNogroup(*this, Clauses))
7609 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007610
Reid Kleckner87a31802018-03-12 21:43:02 +00007611 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007612 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7613 NestedLoopCount, Clauses, AStmt, B);
7614}
7615
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007616StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7617 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007618 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007619 if (!AStmt)
7620 return StmtError();
7621
7622 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7623 OMPLoopDirective::HelperExprs B;
7624 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7625 // define the nested loops number.
7626 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007627 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007628 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7629 VarsWithImplicitDSA, B);
7630 if (NestedLoopCount == 0)
7631 return StmtError();
7632
7633 assert((CurContext->isDependentContext() || B.builtAll()) &&
7634 "omp for loop exprs were not built");
7635
Alexey Bataev5a3af132016-03-29 08:58:54 +00007636 if (!CurContext->isDependentContext()) {
7637 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007638 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007639 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007640 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007641 B.NumIterations, *this, CurScope,
7642 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007643 return StmtError();
7644 }
7645 }
7646
Alexey Bataev382967a2015-12-08 12:06:20 +00007647 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7648 // The grainsize clause and num_tasks clause are mutually exclusive and may
7649 // not appear on the same taskloop directive.
7650 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7651 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007652 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7653 // If a reduction clause is present on the taskloop directive, the nogroup
7654 // clause must not be specified.
7655 if (checkReductionClauseWithNogroup(*this, Clauses))
7656 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007657 if (checkSimdlenSafelenSpecified(*this, Clauses))
7658 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007659
Reid Kleckner87a31802018-03-12 21:43:02 +00007660 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007661 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7662 NestedLoopCount, Clauses, AStmt, B);
7663}
7664
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007665StmtResult Sema::ActOnOpenMPDistributeDirective(
7666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007667 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007668 if (!AStmt)
7669 return StmtError();
7670
7671 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7672 OMPLoopDirective::HelperExprs B;
7673 // In presence of clause 'collapse' with number of loops, it will
7674 // define the nested loops number.
7675 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007676 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007677 nullptr /*ordered not a clause on distribute*/, AStmt,
7678 *this, *DSAStack, VarsWithImplicitDSA, B);
7679 if (NestedLoopCount == 0)
7680 return StmtError();
7681
7682 assert((CurContext->isDependentContext() || B.builtAll()) &&
7683 "omp for loop exprs were not built");
7684
Reid Kleckner87a31802018-03-12 21:43:02 +00007685 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007686 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7687 NestedLoopCount, Clauses, AStmt, B);
7688}
7689
Carlo Bertolli9925f152016-06-27 14:55:37 +00007690StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7691 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007692 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007693 if (!AStmt)
7694 return StmtError();
7695
Alexey Bataeve3727102018-04-18 15:57:46 +00007696 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007697 // 1.2.2 OpenMP Language Terminology
7698 // Structured block - An executable statement with a single entry at the
7699 // top and a single exit at the bottom.
7700 // The point of exit cannot be a branch out of the structured block.
7701 // longjmp() and throw() must not violate the entry/exit criteria.
7702 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007703 for (int ThisCaptureLevel =
7704 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7705 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7706 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7707 // 1.2.2 OpenMP Language Terminology
7708 // Structured block - An executable statement with a single entry at the
7709 // top and a single exit at the bottom.
7710 // The point of exit cannot be a branch out of the structured block.
7711 // longjmp() and throw() must not violate the entry/exit criteria.
7712 CS->getCapturedDecl()->setNothrow();
7713 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007714
7715 OMPLoopDirective::HelperExprs B;
7716 // In presence of clause 'collapse' with number of loops, it will
7717 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007718 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007719 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007720 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007721 VarsWithImplicitDSA, B);
7722 if (NestedLoopCount == 0)
7723 return StmtError();
7724
7725 assert((CurContext->isDependentContext() || B.builtAll()) &&
7726 "omp for loop exprs were not built");
7727
Reid Kleckner87a31802018-03-12 21:43:02 +00007728 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007729 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007730 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7731 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007732}
7733
Kelvin Li4a39add2016-07-05 05:00:15 +00007734StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7735 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007736 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007737 if (!AStmt)
7738 return StmtError();
7739
Alexey Bataeve3727102018-04-18 15:57:46 +00007740 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007741 // 1.2.2 OpenMP Language Terminology
7742 // Structured block - An executable statement with a single entry at the
7743 // top and a single exit at the bottom.
7744 // The point of exit cannot be a branch out of the structured block.
7745 // longjmp() and throw() must not violate the entry/exit criteria.
7746 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007747 for (int ThisCaptureLevel =
7748 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7749 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7750 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7751 // 1.2.2 OpenMP Language Terminology
7752 // Structured block - An executable statement with a single entry at the
7753 // top and a single exit at the bottom.
7754 // The point of exit cannot be a branch out of the structured block.
7755 // longjmp() and throw() must not violate the entry/exit criteria.
7756 CS->getCapturedDecl()->setNothrow();
7757 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007758
7759 OMPLoopDirective::HelperExprs B;
7760 // In presence of clause 'collapse' with number of loops, it will
7761 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007762 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007763 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007764 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007765 VarsWithImplicitDSA, B);
7766 if (NestedLoopCount == 0)
7767 return StmtError();
7768
7769 assert((CurContext->isDependentContext() || B.builtAll()) &&
7770 "omp for loop exprs were not built");
7771
Alexey Bataev438388c2017-11-22 18:34:02 +00007772 if (!CurContext->isDependentContext()) {
7773 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007774 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007775 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7776 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7777 B.NumIterations, *this, CurScope,
7778 DSAStack))
7779 return StmtError();
7780 }
7781 }
7782
Kelvin Lic5609492016-07-15 04:39:07 +00007783 if (checkSimdlenSafelenSpecified(*this, Clauses))
7784 return StmtError();
7785
Reid Kleckner87a31802018-03-12 21:43:02 +00007786 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007787 return OMPDistributeParallelForSimdDirective::Create(
7788 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7789}
7790
Kelvin Li787f3fc2016-07-06 04:45:38 +00007791StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7792 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007793 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007794 if (!AStmt)
7795 return StmtError();
7796
Alexey Bataeve3727102018-04-18 15:57:46 +00007797 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007798 // 1.2.2 OpenMP Language Terminology
7799 // Structured block - An executable statement with a single entry at the
7800 // top and a single exit at the bottom.
7801 // The point of exit cannot be a branch out of the structured block.
7802 // longjmp() and throw() must not violate the entry/exit criteria.
7803 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007804 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7805 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7806 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7807 // 1.2.2 OpenMP Language Terminology
7808 // Structured block - An executable statement with a single entry at the
7809 // top and a single exit at the bottom.
7810 // The point of exit cannot be a branch out of the structured block.
7811 // longjmp() and throw() must not violate the entry/exit criteria.
7812 CS->getCapturedDecl()->setNothrow();
7813 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007814
7815 OMPLoopDirective::HelperExprs B;
7816 // In presence of clause 'collapse' with number of loops, it will
7817 // define the nested loops number.
7818 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007819 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007820 nullptr /*ordered not a clause on distribute*/, CS, *this,
7821 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007822 if (NestedLoopCount == 0)
7823 return StmtError();
7824
7825 assert((CurContext->isDependentContext() || B.builtAll()) &&
7826 "omp for loop exprs were not built");
7827
Alexey Bataev438388c2017-11-22 18:34:02 +00007828 if (!CurContext->isDependentContext()) {
7829 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007830 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007831 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7832 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7833 B.NumIterations, *this, CurScope,
7834 DSAStack))
7835 return StmtError();
7836 }
7837 }
7838
Kelvin Lic5609492016-07-15 04:39:07 +00007839 if (checkSimdlenSafelenSpecified(*this, Clauses))
7840 return StmtError();
7841
Reid Kleckner87a31802018-03-12 21:43:02 +00007842 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007843 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7844 NestedLoopCount, Clauses, AStmt, B);
7845}
7846
Kelvin Lia579b912016-07-14 02:54:56 +00007847StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7848 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007849 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007850 if (!AStmt)
7851 return StmtError();
7852
Alexey Bataeve3727102018-04-18 15:57:46 +00007853 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007854 // 1.2.2 OpenMP Language Terminology
7855 // Structured block - An executable statement with a single entry at the
7856 // top and a single exit at the bottom.
7857 // The point of exit cannot be a branch out of the structured block.
7858 // longjmp() and throw() must not violate the entry/exit criteria.
7859 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007860 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7861 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7862 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7863 // 1.2.2 OpenMP Language Terminology
7864 // Structured block - An executable statement with a single entry at the
7865 // top and a single exit at the bottom.
7866 // The point of exit cannot be a branch out of the structured block.
7867 // longjmp() and throw() must not violate the entry/exit criteria.
7868 CS->getCapturedDecl()->setNothrow();
7869 }
Kelvin Lia579b912016-07-14 02:54:56 +00007870
7871 OMPLoopDirective::HelperExprs B;
7872 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7873 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007874 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00007875 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007876 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007877 VarsWithImplicitDSA, B);
7878 if (NestedLoopCount == 0)
7879 return StmtError();
7880
7881 assert((CurContext->isDependentContext() || B.builtAll()) &&
7882 "omp target parallel for simd loop exprs were not built");
7883
7884 if (!CurContext->isDependentContext()) {
7885 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007886 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007887 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007888 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7889 B.NumIterations, *this, CurScope,
7890 DSAStack))
7891 return StmtError();
7892 }
7893 }
Kelvin Lic5609492016-07-15 04:39:07 +00007894 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007895 return StmtError();
7896
Reid Kleckner87a31802018-03-12 21:43:02 +00007897 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007898 return OMPTargetParallelForSimdDirective::Create(
7899 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7900}
7901
Kelvin Li986330c2016-07-20 22:57:10 +00007902StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7903 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007904 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00007905 if (!AStmt)
7906 return StmtError();
7907
Alexey Bataeve3727102018-04-18 15:57:46 +00007908 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00007909 // 1.2.2 OpenMP Language Terminology
7910 // Structured block - An executable statement with a single entry at the
7911 // top and a single exit at the bottom.
7912 // The point of exit cannot be a branch out of the structured block.
7913 // longjmp() and throw() must not violate the entry/exit criteria.
7914 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007915 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7916 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7917 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7918 // 1.2.2 OpenMP Language Terminology
7919 // Structured block - An executable statement with a single entry at the
7920 // top and a single exit at the bottom.
7921 // The point of exit cannot be a branch out of the structured block.
7922 // longjmp() and throw() must not violate the entry/exit criteria.
7923 CS->getCapturedDecl()->setNothrow();
7924 }
7925
Kelvin Li986330c2016-07-20 22:57:10 +00007926 OMPLoopDirective::HelperExprs B;
7927 // In presence of clause 'collapse' with number of loops, it will define the
7928 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007929 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007930 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007931 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007932 VarsWithImplicitDSA, B);
7933 if (NestedLoopCount == 0)
7934 return StmtError();
7935
7936 assert((CurContext->isDependentContext() || B.builtAll()) &&
7937 "omp target simd loop exprs were not built");
7938
7939 if (!CurContext->isDependentContext()) {
7940 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007941 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007942 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007943 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7944 B.NumIterations, *this, CurScope,
7945 DSAStack))
7946 return StmtError();
7947 }
7948 }
7949
7950 if (checkSimdlenSafelenSpecified(*this, Clauses))
7951 return StmtError();
7952
Reid Kleckner87a31802018-03-12 21:43:02 +00007953 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007954 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7955 NestedLoopCount, Clauses, AStmt, B);
7956}
7957
Kelvin Li02532872016-08-05 14:37:37 +00007958StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7959 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007960 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00007961 if (!AStmt)
7962 return StmtError();
7963
Alexey Bataeve3727102018-04-18 15:57:46 +00007964 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00007965 // 1.2.2 OpenMP Language Terminology
7966 // Structured block - An executable statement with a single entry at the
7967 // top and a single exit at the bottom.
7968 // The point of exit cannot be a branch out of the structured block.
7969 // longjmp() and throw() must not violate the entry/exit criteria.
7970 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007971 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7972 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7973 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7974 // 1.2.2 OpenMP Language Terminology
7975 // Structured block - An executable statement with a single entry at the
7976 // top and a single exit at the bottom.
7977 // The point of exit cannot be a branch out of the structured block.
7978 // longjmp() and throw() must not violate the entry/exit criteria.
7979 CS->getCapturedDecl()->setNothrow();
7980 }
Kelvin Li02532872016-08-05 14:37:37 +00007981
7982 OMPLoopDirective::HelperExprs B;
7983 // In presence of clause 'collapse' with number of loops, it will
7984 // define the nested loops number.
7985 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007986 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007987 nullptr /*ordered not a clause on distribute*/, CS, *this,
7988 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007989 if (NestedLoopCount == 0)
7990 return StmtError();
7991
7992 assert((CurContext->isDependentContext() || B.builtAll()) &&
7993 "omp teams distribute loop exprs were not built");
7994
Reid Kleckner87a31802018-03-12 21:43:02 +00007995 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007996
7997 DSAStack->setParentTeamsRegionLoc(StartLoc);
7998
David Majnemer9d168222016-08-05 17:44:54 +00007999 return OMPTeamsDistributeDirective::Create(
8000 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008001}
8002
Kelvin Li4e325f72016-10-25 12:50:55 +00008003StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8004 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008005 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008006 if (!AStmt)
8007 return StmtError();
8008
Alexey Bataeve3727102018-04-18 15:57:46 +00008009 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008010 // 1.2.2 OpenMP Language Terminology
8011 // Structured block - An executable statement with a single entry at the
8012 // top and a single exit at the bottom.
8013 // The point of exit cannot be a branch out of the structured block.
8014 // longjmp() and throw() must not violate the entry/exit criteria.
8015 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008016 for (int ThisCaptureLevel =
8017 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8018 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8019 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8020 // 1.2.2 OpenMP Language Terminology
8021 // Structured block - An executable statement with a single entry at the
8022 // top and a single exit at the bottom.
8023 // The point of exit cannot be a branch out of the structured block.
8024 // longjmp() and throw() must not violate the entry/exit criteria.
8025 CS->getCapturedDecl()->setNothrow();
8026 }
8027
Kelvin Li4e325f72016-10-25 12:50:55 +00008028
8029 OMPLoopDirective::HelperExprs B;
8030 // In presence of clause 'collapse' with number of loops, it will
8031 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008032 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008033 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008034 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008035 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008036
8037 if (NestedLoopCount == 0)
8038 return StmtError();
8039
8040 assert((CurContext->isDependentContext() || B.builtAll()) &&
8041 "omp teams distribute simd loop exprs were not built");
8042
8043 if (!CurContext->isDependentContext()) {
8044 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008045 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008046 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8047 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8048 B.NumIterations, *this, CurScope,
8049 DSAStack))
8050 return StmtError();
8051 }
8052 }
8053
8054 if (checkSimdlenSafelenSpecified(*this, Clauses))
8055 return StmtError();
8056
Reid Kleckner87a31802018-03-12 21:43:02 +00008057 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008058
8059 DSAStack->setParentTeamsRegionLoc(StartLoc);
8060
Kelvin Li4e325f72016-10-25 12:50:55 +00008061 return OMPTeamsDistributeSimdDirective::Create(
8062 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8063}
8064
Kelvin Li579e41c2016-11-30 23:51:03 +00008065StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8066 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008067 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008068 if (!AStmt)
8069 return StmtError();
8070
Alexey Bataeve3727102018-04-18 15:57:46 +00008071 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008072 // 1.2.2 OpenMP Language Terminology
8073 // Structured block - An executable statement with a single entry at the
8074 // top and a single exit at the bottom.
8075 // The point of exit cannot be a branch out of the structured block.
8076 // longjmp() and throw() must not violate the entry/exit criteria.
8077 CS->getCapturedDecl()->setNothrow();
8078
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008079 for (int ThisCaptureLevel =
8080 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8081 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8082 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8083 // 1.2.2 OpenMP Language Terminology
8084 // Structured block - An executable statement with a single entry at the
8085 // top and a single exit at the bottom.
8086 // The point of exit cannot be a branch out of the structured block.
8087 // longjmp() and throw() must not violate the entry/exit criteria.
8088 CS->getCapturedDecl()->setNothrow();
8089 }
8090
Kelvin Li579e41c2016-11-30 23:51:03 +00008091 OMPLoopDirective::HelperExprs B;
8092 // In presence of clause 'collapse' with number of loops, it will
8093 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008094 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008095 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008096 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008097 VarsWithImplicitDSA, B);
8098
8099 if (NestedLoopCount == 0)
8100 return StmtError();
8101
8102 assert((CurContext->isDependentContext() || B.builtAll()) &&
8103 "omp for loop exprs were not built");
8104
8105 if (!CurContext->isDependentContext()) {
8106 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008107 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008108 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8109 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8110 B.NumIterations, *this, CurScope,
8111 DSAStack))
8112 return StmtError();
8113 }
8114 }
8115
8116 if (checkSimdlenSafelenSpecified(*this, Clauses))
8117 return StmtError();
8118
Reid Kleckner87a31802018-03-12 21:43:02 +00008119 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008120
8121 DSAStack->setParentTeamsRegionLoc(StartLoc);
8122
Kelvin Li579e41c2016-11-30 23:51:03 +00008123 return OMPTeamsDistributeParallelForSimdDirective::Create(
8124 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8125}
8126
Kelvin Li7ade93f2016-12-09 03:24:30 +00008127StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8128 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008129 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008130 if (!AStmt)
8131 return StmtError();
8132
Alexey Bataeve3727102018-04-18 15:57:46 +00008133 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008134 // 1.2.2 OpenMP Language Terminology
8135 // Structured block - An executable statement with a single entry at the
8136 // top and a single exit at the bottom.
8137 // The point of exit cannot be a branch out of the structured block.
8138 // longjmp() and throw() must not violate the entry/exit criteria.
8139 CS->getCapturedDecl()->setNothrow();
8140
Carlo Bertolli62fae152017-11-20 20:46:39 +00008141 for (int ThisCaptureLevel =
8142 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8143 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8144 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8145 // 1.2.2 OpenMP Language Terminology
8146 // Structured block - An executable statement with a single entry at the
8147 // top and a single exit at the bottom.
8148 // The point of exit cannot be a branch out of the structured block.
8149 // longjmp() and throw() must not violate the entry/exit criteria.
8150 CS->getCapturedDecl()->setNothrow();
8151 }
8152
Kelvin Li7ade93f2016-12-09 03:24:30 +00008153 OMPLoopDirective::HelperExprs B;
8154 // In presence of clause 'collapse' with number of loops, it will
8155 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008156 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008157 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008158 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008159 VarsWithImplicitDSA, B);
8160
8161 if (NestedLoopCount == 0)
8162 return StmtError();
8163
8164 assert((CurContext->isDependentContext() || B.builtAll()) &&
8165 "omp for loop exprs were not built");
8166
Reid Kleckner87a31802018-03-12 21:43:02 +00008167 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008168
8169 DSAStack->setParentTeamsRegionLoc(StartLoc);
8170
Kelvin Li7ade93f2016-12-09 03:24:30 +00008171 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008172 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8173 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008174}
8175
Kelvin Libf594a52016-12-17 05:48:59 +00008176StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8177 Stmt *AStmt,
8178 SourceLocation StartLoc,
8179 SourceLocation EndLoc) {
8180 if (!AStmt)
8181 return StmtError();
8182
Alexey Bataeve3727102018-04-18 15:57:46 +00008183 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008184 // 1.2.2 OpenMP Language Terminology
8185 // Structured block - An executable statement with a single entry at the
8186 // top and a single exit at the bottom.
8187 // The point of exit cannot be a branch out of the structured block.
8188 // longjmp() and throw() must not violate the entry/exit criteria.
8189 CS->getCapturedDecl()->setNothrow();
8190
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008191 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8192 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8193 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8194 // 1.2.2 OpenMP Language Terminology
8195 // Structured block - An executable statement with a single entry at the
8196 // top and a single exit at the bottom.
8197 // The point of exit cannot be a branch out of the structured block.
8198 // longjmp() and throw() must not violate the entry/exit criteria.
8199 CS->getCapturedDecl()->setNothrow();
8200 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008201 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008202
8203 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8204 AStmt);
8205}
8206
Kelvin Li83c451e2016-12-25 04:52:54 +00008207StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8208 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008209 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008210 if (!AStmt)
8211 return StmtError();
8212
Alexey Bataeve3727102018-04-18 15:57:46 +00008213 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008214 // 1.2.2 OpenMP Language Terminology
8215 // Structured block - An executable statement with a single entry at the
8216 // top and a single exit at the bottom.
8217 // The point of exit cannot be a branch out of the structured block.
8218 // longjmp() and throw() must not violate the entry/exit criteria.
8219 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008220 for (int ThisCaptureLevel =
8221 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8222 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8223 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8224 // 1.2.2 OpenMP Language Terminology
8225 // Structured block - An executable statement with a single entry at the
8226 // top and a single exit at the bottom.
8227 // The point of exit cannot be a branch out of the structured block.
8228 // longjmp() and throw() must not violate the entry/exit criteria.
8229 CS->getCapturedDecl()->setNothrow();
8230 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008231
8232 OMPLoopDirective::HelperExprs B;
8233 // In presence of clause 'collapse' with number of loops, it will
8234 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008235 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008236 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8237 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008238 VarsWithImplicitDSA, B);
8239 if (NestedLoopCount == 0)
8240 return StmtError();
8241
8242 assert((CurContext->isDependentContext() || B.builtAll()) &&
8243 "omp target teams distribute loop exprs were not built");
8244
Reid Kleckner87a31802018-03-12 21:43:02 +00008245 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008246 return OMPTargetTeamsDistributeDirective::Create(
8247 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8248}
8249
Kelvin Li80e8f562016-12-29 22:16:30 +00008250StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8251 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008252 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008253 if (!AStmt)
8254 return StmtError();
8255
Alexey Bataeve3727102018-04-18 15:57:46 +00008256 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008257 // 1.2.2 OpenMP Language Terminology
8258 // Structured block - An executable statement with a single entry at the
8259 // top and a single exit at the bottom.
8260 // The point of exit cannot be a branch out of the structured block.
8261 // longjmp() and throw() must not violate the entry/exit criteria.
8262 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008263 for (int ThisCaptureLevel =
8264 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8265 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8266 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8267 // 1.2.2 OpenMP Language Terminology
8268 // Structured block - An executable statement with a single entry at the
8269 // top and a single exit at the bottom.
8270 // The point of exit cannot be a branch out of the structured block.
8271 // longjmp() and throw() must not violate the entry/exit criteria.
8272 CS->getCapturedDecl()->setNothrow();
8273 }
8274
Kelvin Li80e8f562016-12-29 22:16:30 +00008275 OMPLoopDirective::HelperExprs B;
8276 // In presence of clause 'collapse' with number of loops, it will
8277 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008278 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008279 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8280 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008281 VarsWithImplicitDSA, B);
8282 if (NestedLoopCount == 0)
8283 return StmtError();
8284
8285 assert((CurContext->isDependentContext() || B.builtAll()) &&
8286 "omp target teams distribute parallel for loop exprs were not built");
8287
Alexey Bataev647dd842018-01-15 20:59:40 +00008288 if (!CurContext->isDependentContext()) {
8289 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008290 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008291 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8292 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8293 B.NumIterations, *this, CurScope,
8294 DSAStack))
8295 return StmtError();
8296 }
8297 }
8298
Reid Kleckner87a31802018-03-12 21:43:02 +00008299 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008300 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008301 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8302 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008303}
8304
Kelvin Li1851df52017-01-03 05:23:48 +00008305StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8306 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008307 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008308 if (!AStmt)
8309 return StmtError();
8310
Alexey Bataeve3727102018-04-18 15:57:46 +00008311 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008312 // 1.2.2 OpenMP Language Terminology
8313 // Structured block - An executable statement with a single entry at the
8314 // top and a single exit at the bottom.
8315 // The point of exit cannot be a branch out of the structured block.
8316 // longjmp() and throw() must not violate the entry/exit criteria.
8317 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008318 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8319 OMPD_target_teams_distribute_parallel_for_simd);
8320 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8321 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8322 // 1.2.2 OpenMP Language Terminology
8323 // Structured block - An executable statement with a single entry at the
8324 // top and a single exit at the bottom.
8325 // The point of exit cannot be a branch out of the structured block.
8326 // longjmp() and throw() must not violate the entry/exit criteria.
8327 CS->getCapturedDecl()->setNothrow();
8328 }
Kelvin Li1851df52017-01-03 05:23:48 +00008329
8330 OMPLoopDirective::HelperExprs B;
8331 // In presence of clause 'collapse' with number of loops, it will
8332 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008333 unsigned NestedLoopCount =
8334 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008335 getCollapseNumberExpr(Clauses),
8336 nullptr /*ordered not a clause on distribute*/, CS, *this,
8337 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008338 if (NestedLoopCount == 0)
8339 return StmtError();
8340
8341 assert((CurContext->isDependentContext() || B.builtAll()) &&
8342 "omp target teams distribute parallel for simd loop exprs were not "
8343 "built");
8344
8345 if (!CurContext->isDependentContext()) {
8346 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008347 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008348 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8349 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8350 B.NumIterations, *this, CurScope,
8351 DSAStack))
8352 return StmtError();
8353 }
8354 }
8355
Alexey Bataev438388c2017-11-22 18:34:02 +00008356 if (checkSimdlenSafelenSpecified(*this, Clauses))
8357 return StmtError();
8358
Reid Kleckner87a31802018-03-12 21:43:02 +00008359 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008360 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8361 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8362}
8363
Kelvin Lida681182017-01-10 18:08:18 +00008364StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8365 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008366 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008367 if (!AStmt)
8368 return StmtError();
8369
8370 auto *CS = cast<CapturedStmt>(AStmt);
8371 // 1.2.2 OpenMP Language Terminology
8372 // Structured block - An executable statement with a single entry at the
8373 // top and a single exit at the bottom.
8374 // The point of exit cannot be a branch out of the structured block.
8375 // longjmp() and throw() must not violate the entry/exit criteria.
8376 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008377 for (int ThisCaptureLevel =
8378 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8379 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8380 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8381 // 1.2.2 OpenMP Language Terminology
8382 // Structured block - An executable statement with a single entry at the
8383 // top and a single exit at the bottom.
8384 // The point of exit cannot be a branch out of the structured block.
8385 // longjmp() and throw() must not violate the entry/exit criteria.
8386 CS->getCapturedDecl()->setNothrow();
8387 }
Kelvin Lida681182017-01-10 18:08:18 +00008388
8389 OMPLoopDirective::HelperExprs B;
8390 // In presence of clause 'collapse' with number of loops, it will
8391 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008392 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008393 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008394 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008395 VarsWithImplicitDSA, B);
8396 if (NestedLoopCount == 0)
8397 return StmtError();
8398
8399 assert((CurContext->isDependentContext() || B.builtAll()) &&
8400 "omp target teams distribute simd loop exprs were not built");
8401
Alexey Bataev438388c2017-11-22 18:34:02 +00008402 if (!CurContext->isDependentContext()) {
8403 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008404 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008405 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8406 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8407 B.NumIterations, *this, CurScope,
8408 DSAStack))
8409 return StmtError();
8410 }
8411 }
8412
8413 if (checkSimdlenSafelenSpecified(*this, Clauses))
8414 return StmtError();
8415
Reid Kleckner87a31802018-03-12 21:43:02 +00008416 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008417 return OMPTargetTeamsDistributeSimdDirective::Create(
8418 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8419}
8420
Alexey Bataeved09d242014-05-28 05:53:51 +00008421OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008422 SourceLocation StartLoc,
8423 SourceLocation LParenLoc,
8424 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008425 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008426 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008427 case OMPC_final:
8428 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8429 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008430 case OMPC_num_threads:
8431 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8432 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008433 case OMPC_safelen:
8434 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8435 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008436 case OMPC_simdlen:
8437 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8438 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008439 case OMPC_collapse:
8440 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8441 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008442 case OMPC_ordered:
8443 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8444 break;
Michael Wonge710d542015-08-07 16:16:36 +00008445 case OMPC_device:
8446 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8447 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008448 case OMPC_num_teams:
8449 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8450 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008451 case OMPC_thread_limit:
8452 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8453 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008454 case OMPC_priority:
8455 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8456 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008457 case OMPC_grainsize:
8458 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8459 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008460 case OMPC_num_tasks:
8461 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8462 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008463 case OMPC_hint:
8464 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8465 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008466 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008467 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008468 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008469 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008470 case OMPC_private:
8471 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008472 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008473 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008474 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008475 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008476 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008477 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008478 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008479 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008480 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008481 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008482 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008483 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008484 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008485 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008486 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008487 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008488 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008489 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008490 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008491 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008492 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008493 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008494 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008495 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008496 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008497 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008498 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008499 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008500 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008501 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008502 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008503 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008504 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008505 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008506 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008507 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008508 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008509 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008510 llvm_unreachable("Clause is not allowed.");
8511 }
8512 return Res;
8513}
8514
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008515// An OpenMP directive such as 'target parallel' has two captured regions:
8516// for the 'target' and 'parallel' respectively. This function returns
8517// the region in which to capture expressions associated with a clause.
8518// A return value of OMPD_unknown signifies that the expression should not
8519// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008520static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8521 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8522 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008523 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008524 switch (CKind) {
8525 case OMPC_if:
8526 switch (DKind) {
8527 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008528 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008529 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008530 // If this clause applies to the nested 'parallel' region, capture within
8531 // the 'target' region, otherwise do not capture.
8532 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8533 CaptureRegion = OMPD_target;
8534 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008535 case OMPD_target_teams_distribute_parallel_for:
8536 case OMPD_target_teams_distribute_parallel_for_simd:
8537 // If this clause applies to the nested 'parallel' region, capture within
8538 // the 'teams' region, otherwise do not capture.
8539 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8540 CaptureRegion = OMPD_teams;
8541 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008542 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008543 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008544 CaptureRegion = OMPD_teams;
8545 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008546 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008547 case OMPD_target_enter_data:
8548 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008549 CaptureRegion = OMPD_task;
8550 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008551 case OMPD_cancel:
8552 case OMPD_parallel:
8553 case OMPD_parallel_sections:
8554 case OMPD_parallel_for:
8555 case OMPD_parallel_for_simd:
8556 case OMPD_target:
8557 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008558 case OMPD_target_teams:
8559 case OMPD_target_teams_distribute:
8560 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008561 case OMPD_distribute_parallel_for:
8562 case OMPD_distribute_parallel_for_simd:
8563 case OMPD_task:
8564 case OMPD_taskloop:
8565 case OMPD_taskloop_simd:
8566 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008567 // Do not capture if-clause expressions.
8568 break;
8569 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008570 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008571 case OMPD_taskyield:
8572 case OMPD_barrier:
8573 case OMPD_taskwait:
8574 case OMPD_cancellation_point:
8575 case OMPD_flush:
8576 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008577 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008578 case OMPD_declare_simd:
8579 case OMPD_declare_target:
8580 case OMPD_end_declare_target:
8581 case OMPD_teams:
8582 case OMPD_simd:
8583 case OMPD_for:
8584 case OMPD_for_simd:
8585 case OMPD_sections:
8586 case OMPD_section:
8587 case OMPD_single:
8588 case OMPD_master:
8589 case OMPD_critical:
8590 case OMPD_taskgroup:
8591 case OMPD_distribute:
8592 case OMPD_ordered:
8593 case OMPD_atomic:
8594 case OMPD_distribute_simd:
8595 case OMPD_teams_distribute:
8596 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008597 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008598 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8599 case OMPD_unknown:
8600 llvm_unreachable("Unknown OpenMP directive");
8601 }
8602 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008603 case OMPC_num_threads:
8604 switch (DKind) {
8605 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008606 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008607 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008608 CaptureRegion = OMPD_target;
8609 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008610 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008611 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008612 case OMPD_target_teams_distribute_parallel_for:
8613 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008614 CaptureRegion = OMPD_teams;
8615 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008616 case OMPD_parallel:
8617 case OMPD_parallel_sections:
8618 case OMPD_parallel_for:
8619 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008620 case OMPD_distribute_parallel_for:
8621 case OMPD_distribute_parallel_for_simd:
8622 // Do not capture num_threads-clause expressions.
8623 break;
8624 case OMPD_target_data:
8625 case OMPD_target_enter_data:
8626 case OMPD_target_exit_data:
8627 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008628 case OMPD_target:
8629 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008630 case OMPD_target_teams:
8631 case OMPD_target_teams_distribute:
8632 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008633 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008634 case OMPD_task:
8635 case OMPD_taskloop:
8636 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008637 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008638 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008639 case OMPD_taskyield:
8640 case OMPD_barrier:
8641 case OMPD_taskwait:
8642 case OMPD_cancellation_point:
8643 case OMPD_flush:
8644 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008645 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008646 case OMPD_declare_simd:
8647 case OMPD_declare_target:
8648 case OMPD_end_declare_target:
8649 case OMPD_teams:
8650 case OMPD_simd:
8651 case OMPD_for:
8652 case OMPD_for_simd:
8653 case OMPD_sections:
8654 case OMPD_section:
8655 case OMPD_single:
8656 case OMPD_master:
8657 case OMPD_critical:
8658 case OMPD_taskgroup:
8659 case OMPD_distribute:
8660 case OMPD_ordered:
8661 case OMPD_atomic:
8662 case OMPD_distribute_simd:
8663 case OMPD_teams_distribute:
8664 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008665 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008666 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8667 case OMPD_unknown:
8668 llvm_unreachable("Unknown OpenMP directive");
8669 }
8670 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008671 case OMPC_num_teams:
8672 switch (DKind) {
8673 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008674 case OMPD_target_teams_distribute:
8675 case OMPD_target_teams_distribute_simd:
8676 case OMPD_target_teams_distribute_parallel_for:
8677 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008678 CaptureRegion = OMPD_target;
8679 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008680 case OMPD_teams_distribute_parallel_for:
8681 case OMPD_teams_distribute_parallel_for_simd:
8682 case OMPD_teams:
8683 case OMPD_teams_distribute:
8684 case OMPD_teams_distribute_simd:
8685 // Do not capture num_teams-clause expressions.
8686 break;
8687 case OMPD_distribute_parallel_for:
8688 case OMPD_distribute_parallel_for_simd:
8689 case OMPD_task:
8690 case OMPD_taskloop:
8691 case OMPD_taskloop_simd:
8692 case OMPD_target_data:
8693 case OMPD_target_enter_data:
8694 case OMPD_target_exit_data:
8695 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008696 case OMPD_cancel:
8697 case OMPD_parallel:
8698 case OMPD_parallel_sections:
8699 case OMPD_parallel_for:
8700 case OMPD_parallel_for_simd:
8701 case OMPD_target:
8702 case OMPD_target_simd:
8703 case OMPD_target_parallel:
8704 case OMPD_target_parallel_for:
8705 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008706 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008707 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008708 case OMPD_taskyield:
8709 case OMPD_barrier:
8710 case OMPD_taskwait:
8711 case OMPD_cancellation_point:
8712 case OMPD_flush:
8713 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008714 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008715 case OMPD_declare_simd:
8716 case OMPD_declare_target:
8717 case OMPD_end_declare_target:
8718 case OMPD_simd:
8719 case OMPD_for:
8720 case OMPD_for_simd:
8721 case OMPD_sections:
8722 case OMPD_section:
8723 case OMPD_single:
8724 case OMPD_master:
8725 case OMPD_critical:
8726 case OMPD_taskgroup:
8727 case OMPD_distribute:
8728 case OMPD_ordered:
8729 case OMPD_atomic:
8730 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008731 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008732 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8733 case OMPD_unknown:
8734 llvm_unreachable("Unknown OpenMP directive");
8735 }
8736 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008737 case OMPC_thread_limit:
8738 switch (DKind) {
8739 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008740 case OMPD_target_teams_distribute:
8741 case OMPD_target_teams_distribute_simd:
8742 case OMPD_target_teams_distribute_parallel_for:
8743 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008744 CaptureRegion = OMPD_target;
8745 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008746 case OMPD_teams_distribute_parallel_for:
8747 case OMPD_teams_distribute_parallel_for_simd:
8748 case OMPD_teams:
8749 case OMPD_teams_distribute:
8750 case OMPD_teams_distribute_simd:
8751 // Do not capture thread_limit-clause expressions.
8752 break;
8753 case OMPD_distribute_parallel_for:
8754 case OMPD_distribute_parallel_for_simd:
8755 case OMPD_task:
8756 case OMPD_taskloop:
8757 case OMPD_taskloop_simd:
8758 case OMPD_target_data:
8759 case OMPD_target_enter_data:
8760 case OMPD_target_exit_data:
8761 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008762 case OMPD_cancel:
8763 case OMPD_parallel:
8764 case OMPD_parallel_sections:
8765 case OMPD_parallel_for:
8766 case OMPD_parallel_for_simd:
8767 case OMPD_target:
8768 case OMPD_target_simd:
8769 case OMPD_target_parallel:
8770 case OMPD_target_parallel_for:
8771 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008772 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008773 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008774 case OMPD_taskyield:
8775 case OMPD_barrier:
8776 case OMPD_taskwait:
8777 case OMPD_cancellation_point:
8778 case OMPD_flush:
8779 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008780 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008781 case OMPD_declare_simd:
8782 case OMPD_declare_target:
8783 case OMPD_end_declare_target:
8784 case OMPD_simd:
8785 case OMPD_for:
8786 case OMPD_for_simd:
8787 case OMPD_sections:
8788 case OMPD_section:
8789 case OMPD_single:
8790 case OMPD_master:
8791 case OMPD_critical:
8792 case OMPD_taskgroup:
8793 case OMPD_distribute:
8794 case OMPD_ordered:
8795 case OMPD_atomic:
8796 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008797 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008798 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8799 case OMPD_unknown:
8800 llvm_unreachable("Unknown OpenMP directive");
8801 }
8802 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008803 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008804 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008805 case OMPD_parallel_for:
8806 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008807 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008808 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008809 case OMPD_teams_distribute_parallel_for:
8810 case OMPD_teams_distribute_parallel_for_simd:
8811 case OMPD_target_parallel_for:
8812 case OMPD_target_parallel_for_simd:
8813 case OMPD_target_teams_distribute_parallel_for:
8814 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008815 CaptureRegion = OMPD_parallel;
8816 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008817 case OMPD_for:
8818 case OMPD_for_simd:
8819 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008820 break;
8821 case OMPD_task:
8822 case OMPD_taskloop:
8823 case OMPD_taskloop_simd:
8824 case OMPD_target_data:
8825 case OMPD_target_enter_data:
8826 case OMPD_target_exit_data:
8827 case OMPD_target_update:
8828 case OMPD_teams:
8829 case OMPD_teams_distribute:
8830 case OMPD_teams_distribute_simd:
8831 case OMPD_target_teams_distribute:
8832 case OMPD_target_teams_distribute_simd:
8833 case OMPD_target:
8834 case OMPD_target_simd:
8835 case OMPD_target_parallel:
8836 case OMPD_cancel:
8837 case OMPD_parallel:
8838 case OMPD_parallel_sections:
8839 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008840 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008841 case OMPD_taskyield:
8842 case OMPD_barrier:
8843 case OMPD_taskwait:
8844 case OMPD_cancellation_point:
8845 case OMPD_flush:
8846 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008847 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008848 case OMPD_declare_simd:
8849 case OMPD_declare_target:
8850 case OMPD_end_declare_target:
8851 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008852 case OMPD_sections:
8853 case OMPD_section:
8854 case OMPD_single:
8855 case OMPD_master:
8856 case OMPD_critical:
8857 case OMPD_taskgroup:
8858 case OMPD_distribute:
8859 case OMPD_ordered:
8860 case OMPD_atomic:
8861 case OMPD_distribute_simd:
8862 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008863 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008864 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8865 case OMPD_unknown:
8866 llvm_unreachable("Unknown OpenMP directive");
8867 }
8868 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008869 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008870 switch (DKind) {
8871 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008872 case OMPD_teams_distribute_parallel_for_simd:
8873 case OMPD_teams_distribute:
8874 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008875 case OMPD_target_teams_distribute_parallel_for:
8876 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008877 case OMPD_target_teams_distribute:
8878 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008879 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008880 break;
8881 case OMPD_distribute_parallel_for:
8882 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008883 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008884 case OMPD_distribute_simd:
8885 // Do not capture thread_limit-clause expressions.
8886 break;
8887 case OMPD_parallel_for:
8888 case OMPD_parallel_for_simd:
8889 case OMPD_target_parallel_for_simd:
8890 case OMPD_target_parallel_for:
8891 case OMPD_task:
8892 case OMPD_taskloop:
8893 case OMPD_taskloop_simd:
8894 case OMPD_target_data:
8895 case OMPD_target_enter_data:
8896 case OMPD_target_exit_data:
8897 case OMPD_target_update:
8898 case OMPD_teams:
8899 case OMPD_target:
8900 case OMPD_target_simd:
8901 case OMPD_target_parallel:
8902 case OMPD_cancel:
8903 case OMPD_parallel:
8904 case OMPD_parallel_sections:
8905 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008906 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008907 case OMPD_taskyield:
8908 case OMPD_barrier:
8909 case OMPD_taskwait:
8910 case OMPD_cancellation_point:
8911 case OMPD_flush:
8912 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008913 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008914 case OMPD_declare_simd:
8915 case OMPD_declare_target:
8916 case OMPD_end_declare_target:
8917 case OMPD_simd:
8918 case OMPD_for:
8919 case OMPD_for_simd:
8920 case OMPD_sections:
8921 case OMPD_section:
8922 case OMPD_single:
8923 case OMPD_master:
8924 case OMPD_critical:
8925 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008926 case OMPD_ordered:
8927 case OMPD_atomic:
8928 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008929 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008930 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8931 case OMPD_unknown:
8932 llvm_unreachable("Unknown OpenMP directive");
8933 }
8934 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008935 case OMPC_device:
8936 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008937 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008938 case OMPD_target_enter_data:
8939 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008940 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008941 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008942 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008943 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008944 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008945 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008946 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008947 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008948 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008949 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008950 CaptureRegion = OMPD_task;
8951 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008952 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008953 // Do not capture device-clause expressions.
8954 break;
8955 case OMPD_teams_distribute_parallel_for:
8956 case OMPD_teams_distribute_parallel_for_simd:
8957 case OMPD_teams:
8958 case OMPD_teams_distribute:
8959 case OMPD_teams_distribute_simd:
8960 case OMPD_distribute_parallel_for:
8961 case OMPD_distribute_parallel_for_simd:
8962 case OMPD_task:
8963 case OMPD_taskloop:
8964 case OMPD_taskloop_simd:
8965 case OMPD_cancel:
8966 case OMPD_parallel:
8967 case OMPD_parallel_sections:
8968 case OMPD_parallel_for:
8969 case OMPD_parallel_for_simd:
8970 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008971 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008972 case OMPD_taskyield:
8973 case OMPD_barrier:
8974 case OMPD_taskwait:
8975 case OMPD_cancellation_point:
8976 case OMPD_flush:
8977 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008978 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008979 case OMPD_declare_simd:
8980 case OMPD_declare_target:
8981 case OMPD_end_declare_target:
8982 case OMPD_simd:
8983 case OMPD_for:
8984 case OMPD_for_simd:
8985 case OMPD_sections:
8986 case OMPD_section:
8987 case OMPD_single:
8988 case OMPD_master:
8989 case OMPD_critical:
8990 case OMPD_taskgroup:
8991 case OMPD_distribute:
8992 case OMPD_ordered:
8993 case OMPD_atomic:
8994 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008995 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008996 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8997 case OMPD_unknown:
8998 llvm_unreachable("Unknown OpenMP directive");
8999 }
9000 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009001 case OMPC_firstprivate:
9002 case OMPC_lastprivate:
9003 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009004 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009005 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009006 case OMPC_linear:
9007 case OMPC_default:
9008 case OMPC_proc_bind:
9009 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009010 case OMPC_safelen:
9011 case OMPC_simdlen:
9012 case OMPC_collapse:
9013 case OMPC_private:
9014 case OMPC_shared:
9015 case OMPC_aligned:
9016 case OMPC_copyin:
9017 case OMPC_copyprivate:
9018 case OMPC_ordered:
9019 case OMPC_nowait:
9020 case OMPC_untied:
9021 case OMPC_mergeable:
9022 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009023 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009024 case OMPC_flush:
9025 case OMPC_read:
9026 case OMPC_write:
9027 case OMPC_update:
9028 case OMPC_capture:
9029 case OMPC_seq_cst:
9030 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009031 case OMPC_threads:
9032 case OMPC_simd:
9033 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009034 case OMPC_priority:
9035 case OMPC_grainsize:
9036 case OMPC_nogroup:
9037 case OMPC_num_tasks:
9038 case OMPC_hint:
9039 case OMPC_defaultmap:
9040 case OMPC_unknown:
9041 case OMPC_uniform:
9042 case OMPC_to:
9043 case OMPC_from:
9044 case OMPC_use_device_ptr:
9045 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009046 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009047 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009048 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009049 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009050 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009051 llvm_unreachable("Unexpected OpenMP clause.");
9052 }
9053 return CaptureRegion;
9054}
9055
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009056OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9057 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009058 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009059 SourceLocation NameModifierLoc,
9060 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009061 SourceLocation EndLoc) {
9062 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009063 Stmt *HelperValStmt = nullptr;
9064 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009065 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9066 !Condition->isInstantiationDependent() &&
9067 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009068 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009069 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009070 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009071
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009072 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009073
9074 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9075 CaptureRegion =
9076 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009077 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009078 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009079 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009080 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9081 HelperValStmt = buildPreInits(Context, Captures);
9082 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009083 }
9084
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009085 return new (Context)
9086 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9087 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009088}
9089
Alexey Bataev3778b602014-07-17 07:32:53 +00009090OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9091 SourceLocation StartLoc,
9092 SourceLocation LParenLoc,
9093 SourceLocation EndLoc) {
9094 Expr *ValExpr = Condition;
9095 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9096 !Condition->isInstantiationDependent() &&
9097 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009098 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009099 if (Val.isInvalid())
9100 return nullptr;
9101
Richard Smith03a4aa32016-06-23 19:02:52 +00009102 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009103 }
9104
9105 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9106}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009107ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9108 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009109 if (!Op)
9110 return ExprError();
9111
9112 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9113 public:
9114 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009115 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009116 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9117 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009118 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9119 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009120 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9121 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009122 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9123 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009124 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9125 QualType T,
9126 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009127 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9128 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009129 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9130 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009131 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009132 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009133 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009134 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9135 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009136 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9137 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009138 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9139 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009140 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009141 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009142 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009143 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9144 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009145 llvm_unreachable("conversion functions are permitted");
9146 }
9147 } ConvertDiagnoser;
9148 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9149}
9150
Alexey Bataeve3727102018-04-18 15:57:46 +00009151static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009152 OpenMPClauseKind CKind,
9153 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009154 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9155 !ValExpr->isInstantiationDependent()) {
9156 SourceLocation Loc = ValExpr->getExprLoc();
9157 ExprResult Value =
9158 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9159 if (Value.isInvalid())
9160 return false;
9161
9162 ValExpr = Value.get();
9163 // The expression must evaluate to a non-negative integer value.
9164 llvm::APSInt Result;
9165 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009166 Result.isSigned() &&
9167 !((!StrictlyPositive && Result.isNonNegative()) ||
9168 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009169 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009170 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9171 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009172 return false;
9173 }
9174 }
9175 return true;
9176}
9177
Alexey Bataev568a8332014-03-06 06:15:19 +00009178OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9179 SourceLocation StartLoc,
9180 SourceLocation LParenLoc,
9181 SourceLocation EndLoc) {
9182 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009183 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009184
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009185 // OpenMP [2.5, Restrictions]
9186 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009187 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009188 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009189 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009190
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009191 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009192 OpenMPDirectiveKind CaptureRegion =
9193 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9194 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009195 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009196 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009197 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9198 HelperValStmt = buildPreInits(Context, Captures);
9199 }
9200
9201 return new (Context) OMPNumThreadsClause(
9202 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009203}
9204
Alexey Bataev62c87d22014-03-21 04:51:18 +00009205ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009206 OpenMPClauseKind CKind,
9207 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009208 if (!E)
9209 return ExprError();
9210 if (E->isValueDependent() || E->isTypeDependent() ||
9211 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009212 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009213 llvm::APSInt Result;
9214 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9215 if (ICE.isInvalid())
9216 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009217 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9218 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009219 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009220 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9221 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009222 return ExprError();
9223 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009224 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9225 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9226 << E->getSourceRange();
9227 return ExprError();
9228 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009229 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9230 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009231 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009232 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009233 return ICE;
9234}
9235
9236OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9237 SourceLocation LParenLoc,
9238 SourceLocation EndLoc) {
9239 // OpenMP [2.8.1, simd construct, Description]
9240 // The parameter of the safelen clause must be a constant
9241 // positive integer expression.
9242 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9243 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009244 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009245 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009246 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009247}
9248
Alexey Bataev66b15b52015-08-21 11:14:16 +00009249OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9250 SourceLocation LParenLoc,
9251 SourceLocation EndLoc) {
9252 // OpenMP [2.8.1, simd construct, Description]
9253 // The parameter of the simdlen clause must be a constant
9254 // positive integer expression.
9255 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9256 if (Simdlen.isInvalid())
9257 return nullptr;
9258 return new (Context)
9259 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9260}
9261
Alexander Musman64d33f12014-06-04 07:53:32 +00009262OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9263 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009264 SourceLocation LParenLoc,
9265 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009266 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009267 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009268 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009269 // The parameter of the collapse clause must be a constant
9270 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009271 ExprResult NumForLoopsResult =
9272 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9273 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009274 return nullptr;
9275 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009276 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009277}
9278
Alexey Bataev10e775f2015-07-30 11:36:16 +00009279OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9280 SourceLocation EndLoc,
9281 SourceLocation LParenLoc,
9282 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009283 // OpenMP [2.7.1, loop construct, Description]
9284 // OpenMP [2.8.1, simd construct, Description]
9285 // OpenMP [2.9.6, distribute construct, Description]
9286 // The parameter of the ordered clause must be a constant
9287 // positive integer expression if any.
9288 if (NumForLoops && LParenLoc.isValid()) {
9289 ExprResult NumForLoopsResult =
9290 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9291 if (NumForLoopsResult.isInvalid())
9292 return nullptr;
9293 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009294 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009295 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009296 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009297 auto *Clause = OMPOrderedClause::Create(
9298 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9299 StartLoc, LParenLoc, EndLoc);
9300 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9301 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009302}
9303
Alexey Bataeved09d242014-05-28 05:53:51 +00009304OMPClause *Sema::ActOnOpenMPSimpleClause(
9305 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9306 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009307 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009308 switch (Kind) {
9309 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009310 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009311 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9312 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009313 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009314 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009315 Res = ActOnOpenMPProcBindClause(
9316 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9317 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009318 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009319 case OMPC_atomic_default_mem_order:
9320 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9321 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9322 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9323 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009324 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009325 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009326 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009327 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009328 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009329 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009330 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009331 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009332 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009333 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009334 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009335 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009336 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009337 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009338 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009339 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009340 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009341 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009342 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009343 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009344 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009345 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009346 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009347 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009348 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009349 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009350 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009351 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009352 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009353 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009354 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009355 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009356 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009357 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009358 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009359 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009360 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009361 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009362 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009363 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009364 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009365 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009366 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009367 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009368 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009369 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009370 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009371 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009372 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009373 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009374 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009375 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009376 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009377 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009378 llvm_unreachable("Clause is not allowed.");
9379 }
9380 return Res;
9381}
9382
Alexey Bataev6402bca2015-12-28 07:25:51 +00009383static std::string
9384getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9385 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009386 SmallString<256> Buffer;
9387 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009388 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9389 unsigned Skipped = Exclude.size();
9390 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009391 for (unsigned I = First; I < Last; ++I) {
9392 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009393 --Skipped;
9394 continue;
9395 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009396 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9397 if (I == Bound - Skipped)
9398 Out << " or ";
9399 else if (I != Bound + 1 - Skipped)
9400 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009401 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009402 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009403}
9404
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009405OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9406 SourceLocation KindKwLoc,
9407 SourceLocation StartLoc,
9408 SourceLocation LParenLoc,
9409 SourceLocation EndLoc) {
9410 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009411 static_assert(OMPC_DEFAULT_unknown > 0,
9412 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009413 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009414 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9415 /*Last=*/OMPC_DEFAULT_unknown)
9416 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009417 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009418 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009419 switch (Kind) {
9420 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009421 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009422 break;
9423 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009424 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009425 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009426 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009427 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009428 break;
9429 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009430 return new (Context)
9431 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009432}
9433
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009434OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9435 SourceLocation KindKwLoc,
9436 SourceLocation StartLoc,
9437 SourceLocation LParenLoc,
9438 SourceLocation EndLoc) {
9439 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009440 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009441 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9442 /*Last=*/OMPC_PROC_BIND_unknown)
9443 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009444 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009445 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009446 return new (Context)
9447 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009448}
9449
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009450OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9451 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9452 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9453 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9454 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9455 << getListOfPossibleValues(
9456 OMPC_atomic_default_mem_order, /*First=*/0,
9457 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9458 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9459 return nullptr;
9460 }
9461 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9462 LParenLoc, EndLoc);
9463}
9464
Alexey Bataev56dafe82014-06-20 07:16:17 +00009465OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009466 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009467 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009468 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009469 SourceLocation EndLoc) {
9470 OMPClause *Res = nullptr;
9471 switch (Kind) {
9472 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009473 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9474 assert(Argument.size() == NumberOfElements &&
9475 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009476 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009477 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9478 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9479 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9480 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9481 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009482 break;
9483 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009484 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9485 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9486 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9487 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009488 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009489 case OMPC_dist_schedule:
9490 Res = ActOnOpenMPDistScheduleClause(
9491 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9492 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9493 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009494 case OMPC_defaultmap:
9495 enum { Modifier, DefaultmapKind };
9496 Res = ActOnOpenMPDefaultmapClause(
9497 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9498 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009499 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9500 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009501 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009502 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009503 case OMPC_num_threads:
9504 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009505 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009506 case OMPC_collapse:
9507 case OMPC_default:
9508 case OMPC_proc_bind:
9509 case OMPC_private:
9510 case OMPC_firstprivate:
9511 case OMPC_lastprivate:
9512 case OMPC_shared:
9513 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009514 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009515 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009516 case OMPC_linear:
9517 case OMPC_aligned:
9518 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009519 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009520 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009521 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009522 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009523 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009524 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009525 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009526 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009527 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009528 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009529 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009530 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009531 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009532 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009533 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009534 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009535 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009536 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009537 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009538 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009539 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009540 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009541 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009542 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009543 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009544 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009545 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009546 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009547 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009548 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009549 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009550 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009551 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009552 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009553 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009554 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009555 llvm_unreachable("Clause is not allowed.");
9556 }
9557 return Res;
9558}
9559
Alexey Bataev6402bca2015-12-28 07:25:51 +00009560static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9561 OpenMPScheduleClauseModifier M2,
9562 SourceLocation M1Loc, SourceLocation M2Loc) {
9563 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9564 SmallVector<unsigned, 2> Excluded;
9565 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9566 Excluded.push_back(M2);
9567 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9568 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9569 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9570 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9571 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9572 << getListOfPossibleValues(OMPC_schedule,
9573 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9574 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9575 Excluded)
9576 << getOpenMPClauseName(OMPC_schedule);
9577 return true;
9578 }
9579 return false;
9580}
9581
Alexey Bataev56dafe82014-06-20 07:16:17 +00009582OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009583 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009584 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009585 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9586 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9587 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9588 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9589 return nullptr;
9590 // OpenMP, 2.7.1, Loop Construct, Restrictions
9591 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9592 // but not both.
9593 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9594 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9595 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9596 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9597 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9598 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9599 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9600 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9601 return nullptr;
9602 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009603 if (Kind == OMPC_SCHEDULE_unknown) {
9604 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009605 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9606 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9607 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9608 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9609 Exclude);
9610 } else {
9611 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9612 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009613 }
9614 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9615 << Values << getOpenMPClauseName(OMPC_schedule);
9616 return nullptr;
9617 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009618 // OpenMP, 2.7.1, Loop Construct, Restrictions
9619 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9620 // schedule(guided).
9621 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9622 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9623 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9624 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9625 diag::err_omp_schedule_nonmonotonic_static);
9626 return nullptr;
9627 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009628 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009629 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009630 if (ChunkSize) {
9631 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9632 !ChunkSize->isInstantiationDependent() &&
9633 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009634 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009635 ExprResult Val =
9636 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9637 if (Val.isInvalid())
9638 return nullptr;
9639
9640 ValExpr = Val.get();
9641
9642 // OpenMP [2.7.1, Restrictions]
9643 // chunk_size must be a loop invariant integer expression with a positive
9644 // value.
9645 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009646 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9647 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9648 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009649 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009650 return nullptr;
9651 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009652 } else if (getOpenMPCaptureRegionForClause(
9653 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9654 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009655 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009656 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009657 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009658 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9659 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009660 }
9661 }
9662 }
9663
Alexey Bataev6402bca2015-12-28 07:25:51 +00009664 return new (Context)
9665 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009666 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009667}
9668
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009669OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9670 SourceLocation StartLoc,
9671 SourceLocation EndLoc) {
9672 OMPClause *Res = nullptr;
9673 switch (Kind) {
9674 case OMPC_ordered:
9675 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9676 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009677 case OMPC_nowait:
9678 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9679 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009680 case OMPC_untied:
9681 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9682 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009683 case OMPC_mergeable:
9684 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9685 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009686 case OMPC_read:
9687 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9688 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009689 case OMPC_write:
9690 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9691 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009692 case OMPC_update:
9693 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9694 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009695 case OMPC_capture:
9696 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9697 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009698 case OMPC_seq_cst:
9699 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9700 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009701 case OMPC_threads:
9702 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9703 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009704 case OMPC_simd:
9705 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9706 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009707 case OMPC_nogroup:
9708 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9709 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009710 case OMPC_unified_address:
9711 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9712 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009713 case OMPC_unified_shared_memory:
9714 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9715 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009716 case OMPC_reverse_offload:
9717 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9718 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009719 case OMPC_dynamic_allocators:
9720 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9721 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009722 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009723 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009724 case OMPC_num_threads:
9725 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009726 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009727 case OMPC_collapse:
9728 case OMPC_schedule:
9729 case OMPC_private:
9730 case OMPC_firstprivate:
9731 case OMPC_lastprivate:
9732 case OMPC_shared:
9733 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009734 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009735 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009736 case OMPC_linear:
9737 case OMPC_aligned:
9738 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009739 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009740 case OMPC_default:
9741 case OMPC_proc_bind:
9742 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009743 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009744 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009745 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009746 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009747 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009748 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009749 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009750 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009751 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009752 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009753 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009754 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009755 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009756 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009757 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009758 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009759 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009760 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009761 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009762 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009763 llvm_unreachable("Clause is not allowed.");
9764 }
9765 return Res;
9766}
9767
Alexey Bataev236070f2014-06-20 11:19:47 +00009768OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9769 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009770 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009771 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9772}
9773
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009774OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9775 SourceLocation EndLoc) {
9776 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9777}
9778
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009779OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9780 SourceLocation EndLoc) {
9781 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9782}
9783
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009784OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9785 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009786 return new (Context) OMPReadClause(StartLoc, EndLoc);
9787}
9788
Alexey Bataevdea47612014-07-23 07:46:59 +00009789OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9790 SourceLocation EndLoc) {
9791 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9792}
9793
Alexey Bataev67a4f222014-07-23 10:25:33 +00009794OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9795 SourceLocation EndLoc) {
9796 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9797}
9798
Alexey Bataev459dec02014-07-24 06:46:57 +00009799OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9800 SourceLocation EndLoc) {
9801 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9802}
9803
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009804OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9805 SourceLocation EndLoc) {
9806 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9807}
9808
Alexey Bataev346265e2015-09-25 10:37:12 +00009809OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9810 SourceLocation EndLoc) {
9811 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9812}
9813
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009814OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9815 SourceLocation EndLoc) {
9816 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9817}
9818
Alexey Bataevb825de12015-12-07 10:51:44 +00009819OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9820 SourceLocation EndLoc) {
9821 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9822}
9823
Kelvin Li1408f912018-09-26 04:28:39 +00009824OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9825 SourceLocation EndLoc) {
9826 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9827}
9828
Patrick Lyster4a370b92018-10-01 13:47:43 +00009829OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9830 SourceLocation EndLoc) {
9831 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9832}
9833
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009834OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9835 SourceLocation EndLoc) {
9836 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9837}
9838
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009839OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9840 SourceLocation EndLoc) {
9841 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9842}
9843
Alexey Bataevc5e02582014-06-16 07:08:35 +00009844OMPClause *Sema::ActOnOpenMPVarListClause(
9845 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009846 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
9847 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
9848 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +00009849 OpenMPLinearClauseKind LinKind,
9850 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009851 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
9852 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
9853 SourceLocation StartLoc = Locs.StartLoc;
9854 SourceLocation LParenLoc = Locs.LParenLoc;
9855 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009856 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009857 switch (Kind) {
9858 case OMPC_private:
9859 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9860 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009861 case OMPC_firstprivate:
9862 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9863 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009864 case OMPC_lastprivate:
9865 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9866 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009867 case OMPC_shared:
9868 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9869 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009870 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009871 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009872 EndLoc, ReductionOrMapperIdScopeSpec,
9873 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009874 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009875 case OMPC_task_reduction:
9876 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009877 EndLoc, ReductionOrMapperIdScopeSpec,
9878 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +00009879 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009880 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009881 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9882 EndLoc, ReductionOrMapperIdScopeSpec,
9883 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +00009884 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009885 case OMPC_linear:
9886 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009887 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009888 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009889 case OMPC_aligned:
9890 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9891 ColonLoc, EndLoc);
9892 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009893 case OMPC_copyin:
9894 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9895 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009896 case OMPC_copyprivate:
9897 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9898 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009899 case OMPC_flush:
9900 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9901 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009902 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009903 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009904 StartLoc, LParenLoc, EndLoc);
9905 break;
9906 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009907 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
9908 ReductionOrMapperIdScopeSpec,
9909 ReductionOrMapperId, MapType, IsMapTypeImplicit,
9910 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009911 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009912 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +00009913 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
9914 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +00009915 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009916 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +00009917 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
9918 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +00009919 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009920 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009921 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +00009922 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009923 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009924 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +00009925 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009926 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009927 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009928 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009929 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009930 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009931 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009932 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009933 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009934 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009935 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009936 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009937 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009938 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009939 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009940 case OMPC_allocate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009941 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009942 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009943 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009944 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009945 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009946 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009947 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009948 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009949 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009950 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009951 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009952 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009953 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009954 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009955 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009956 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009957 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009958 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009959 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +00009960 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009961 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009962 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009963 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009964 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009965 llvm_unreachable("Clause is not allowed.");
9966 }
9967 return Res;
9968}
9969
Alexey Bataev90c228f2016-02-08 09:29:13 +00009970ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009971 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009972 ExprResult Res = BuildDeclRefExpr(
9973 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9974 if (!Res.isUsable())
9975 return ExprError();
9976 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9977 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9978 if (!Res.isUsable())
9979 return ExprError();
9980 }
9981 if (VK != VK_LValue && Res.get()->isGLValue()) {
9982 Res = DefaultLvalueConversion(Res.get());
9983 if (!Res.isUsable())
9984 return ExprError();
9985 }
9986 return Res;
9987}
9988
Alexey Bataev60da77e2016-02-29 05:54:20 +00009989static std::pair<ValueDecl *, bool>
9990getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9991 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009992 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9993 RefExpr->containsUnexpandedParameterPack())
9994 return std::make_pair(nullptr, true);
9995
Alexey Bataevd985eda2016-02-10 11:29:16 +00009996 // OpenMP [3.1, C/C++]
9997 // A list item is a variable name.
9998 // OpenMP [2.9.3.3, Restrictions, p.1]
9999 // A variable that is part of another variable (as an array or
10000 // structure element) cannot appear in a private clause.
10001 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010002 enum {
10003 NoArrayExpr = -1,
10004 ArraySubscript = 0,
10005 OMPArraySection = 1
10006 } IsArrayExpr = NoArrayExpr;
10007 if (AllowArraySection) {
10008 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010009 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010010 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10011 Base = TempASE->getBase()->IgnoreParenImpCasts();
10012 RefExpr = Base;
10013 IsArrayExpr = ArraySubscript;
10014 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010015 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010016 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10017 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10018 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10019 Base = TempASE->getBase()->IgnoreParenImpCasts();
10020 RefExpr = Base;
10021 IsArrayExpr = OMPArraySection;
10022 }
10023 }
10024 ELoc = RefExpr->getExprLoc();
10025 ERange = RefExpr->getSourceRange();
10026 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +000010027 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10028 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10029 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10030 (S.getCurrentThisType().isNull() || !ME ||
10031 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10032 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010033 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010034 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10035 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000010036 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010037 S.Diag(ELoc,
10038 AllowArraySection
10039 ? diag::err_omp_expected_var_name_member_expr_or_array_item
10040 : diag::err_omp_expected_var_name_member_expr)
10041 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10042 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010043 return std::make_pair(nullptr, false);
10044 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010045 return std::make_pair(
10046 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010047}
10048
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010049OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10050 SourceLocation StartLoc,
10051 SourceLocation LParenLoc,
10052 SourceLocation EndLoc) {
10053 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010054 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010055 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010056 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010057 SourceLocation ELoc;
10058 SourceRange ERange;
10059 Expr *SimpleRefExpr = RefExpr;
10060 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010061 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010062 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010063 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010064 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010065 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010066 ValueDecl *D = Res.first;
10067 if (!D)
10068 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010069
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010070 QualType Type = D->getType();
10071 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010072
10073 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10074 // A variable that appears in a private clause must not have an incomplete
10075 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010076 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010077 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010078 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010079
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010080 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10081 // A variable that is privatized must not have a const-qualified type
10082 // unless it is of class type with a mutable member. This restriction does
10083 // not apply to the firstprivate clause.
10084 //
10085 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10086 // A variable that appears in a private clause must not have a
10087 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010088 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010089 continue;
10090
Alexey Bataev758e55e2013-09-06 18:03:48 +000010091 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10092 // in a Construct]
10093 // Variables with the predetermined data-sharing attributes may not be
10094 // listed in data-sharing attributes clauses, except for the cases
10095 // listed below. For these exceptions only, listing a predetermined
10096 // variable in a data-sharing attribute clause is allowed and overrides
10097 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010098 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010099 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010100 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10101 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010102 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010103 continue;
10104 }
10105
Alexey Bataeve3727102018-04-18 15:57:46 +000010106 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010107 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010108 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010109 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010110 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10111 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010112 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010113 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010114 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010115 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010116 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010117 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010118 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010119 continue;
10120 }
10121
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010122 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10123 // A list item cannot appear in both a map clause and a data-sharing
10124 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010125 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010126 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010127 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010128 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010129 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10130 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10131 ConflictKind = WhereFoundClauseKind;
10132 return true;
10133 })) {
10134 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010135 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010136 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010137 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010138 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010139 continue;
10140 }
10141 }
10142
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010143 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10144 // A variable of class type (or array thereof) that appears in a private
10145 // clause requires an accessible, unambiguous default constructor for the
10146 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010147 // Generate helper private variable and initialize it with the default
10148 // value. The address of the original variable is replaced by the address of
10149 // the new private variable in CodeGen. This new variable is not added to
10150 // IdResolver, so the code in the OpenMP region uses original variable for
10151 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010152 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010153 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010154 buildVarDecl(*this, ELoc, Type, D->getName(),
10155 D->hasAttrs() ? &D->getAttrs() : nullptr,
10156 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010157 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010158 if (VDPrivate->isInvalidDecl())
10159 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010160 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010161 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010162
Alexey Bataev90c228f2016-02-08 09:29:13 +000010163 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010164 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010165 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010166 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010167 Vars.push_back((VD || CurContext->isDependentContext())
10168 ? RefExpr->IgnoreParens()
10169 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010170 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010171 }
10172
Alexey Bataeved09d242014-05-28 05:53:51 +000010173 if (Vars.empty())
10174 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010175
Alexey Bataev03b340a2014-10-21 03:16:40 +000010176 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10177 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010178}
10179
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010180namespace {
10181class DiagsUninitializedSeveretyRAII {
10182private:
10183 DiagnosticsEngine &Diags;
10184 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010185 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010186
10187public:
10188 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10189 bool IsIgnored)
10190 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10191 if (!IsIgnored) {
10192 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10193 /*Map*/ diag::Severity::Ignored, Loc);
10194 }
10195 }
10196 ~DiagsUninitializedSeveretyRAII() {
10197 if (!IsIgnored)
10198 Diags.popMappings(SavedLoc);
10199 }
10200};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010201}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010202
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010203OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10204 SourceLocation StartLoc,
10205 SourceLocation LParenLoc,
10206 SourceLocation EndLoc) {
10207 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010208 SmallVector<Expr *, 8> PrivateCopies;
10209 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010210 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010211 bool IsImplicitClause =
10212 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010213 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010214
Alexey Bataeve3727102018-04-18 15:57:46 +000010215 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010216 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010217 SourceLocation ELoc;
10218 SourceRange ERange;
10219 Expr *SimpleRefExpr = RefExpr;
10220 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010221 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010222 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010223 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010224 PrivateCopies.push_back(nullptr);
10225 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010226 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010227 ValueDecl *D = Res.first;
10228 if (!D)
10229 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010230
Alexey Bataev60da77e2016-02-29 05:54:20 +000010231 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010232 QualType Type = D->getType();
10233 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010234
10235 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10236 // A variable that appears in a private clause must not have an incomplete
10237 // type or a reference type.
10238 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010239 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010240 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010241 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010242
10243 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10244 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010245 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010246 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010247 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010248
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010249 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010250 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010251 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010252 DSAStackTy::DSAVarData DVar =
10253 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010254 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010255 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010256 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010257 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10258 // A list item that specifies a given variable may not appear in more
10259 // than one clause on the same directive, except that a variable may be
10260 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010261 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10262 // A list item may appear in a firstprivate or lastprivate clause but not
10263 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010264 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010265 (isOpenMPDistributeDirective(CurrDir) ||
10266 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010267 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010268 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010269 << getOpenMPClauseName(DVar.CKind)
10270 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010271 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010272 continue;
10273 }
10274
10275 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10276 // in a Construct]
10277 // Variables with the predetermined data-sharing attributes may not be
10278 // listed in data-sharing attributes clauses, except for the cases
10279 // listed below. For these exceptions only, listing a predetermined
10280 // variable in a data-sharing attribute clause is allowed and overrides
10281 // the variable's predetermined data-sharing attributes.
10282 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10283 // in a Construct, C/C++, p.2]
10284 // Variables with const-qualified type having no mutable member may be
10285 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010286 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010287 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10288 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010289 << getOpenMPClauseName(DVar.CKind)
10290 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010291 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010292 continue;
10293 }
10294
10295 // OpenMP [2.9.3.4, Restrictions, p.2]
10296 // A list item that is private within a parallel region must not appear
10297 // in a firstprivate clause on a worksharing construct if any of the
10298 // worksharing regions arising from the worksharing construct ever bind
10299 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010300 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10301 // A list item that is private within a teams region must not appear in a
10302 // firstprivate clause on a distribute construct if any of the distribute
10303 // regions arising from the distribute construct ever bind to any of the
10304 // teams regions arising from the teams construct.
10305 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10306 // A list item that appears in a reduction clause of a teams construct
10307 // must not appear in a firstprivate clause on a distribute construct if
10308 // any of the distribute regions arising from the distribute construct
10309 // ever bind to any of the teams regions arising from the teams construct.
10310 if ((isOpenMPWorksharingDirective(CurrDir) ||
10311 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010312 !isOpenMPParallelDirective(CurrDir) &&
10313 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010314 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010315 if (DVar.CKind != OMPC_shared &&
10316 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010317 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010318 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010319 Diag(ELoc, diag::err_omp_required_access)
10320 << getOpenMPClauseName(OMPC_firstprivate)
10321 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010322 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010323 continue;
10324 }
10325 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010326 // OpenMP [2.9.3.4, Restrictions, p.3]
10327 // A list item that appears in a reduction clause of a parallel construct
10328 // must not appear in a firstprivate clause on a worksharing or task
10329 // construct if any of the worksharing or task regions arising from the
10330 // worksharing or task construct ever bind to any of the parallel regions
10331 // arising from the parallel construct.
10332 // OpenMP [2.9.3.4, Restrictions, p.4]
10333 // A list item that appears in a reduction clause in worksharing
10334 // construct must not appear in a firstprivate clause in a task construct
10335 // encountered during execution of any of the worksharing regions arising
10336 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010337 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010338 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010339 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10340 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010341 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010342 isOpenMPWorksharingDirective(K) ||
10343 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010344 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010345 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010346 if (DVar.CKind == OMPC_reduction &&
10347 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010348 isOpenMPWorksharingDirective(DVar.DKind) ||
10349 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010350 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10351 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010352 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010353 continue;
10354 }
10355 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010356
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010357 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10358 // A list item cannot appear in both a map clause and a data-sharing
10359 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010360 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010361 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010362 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010363 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010364 [&ConflictKind](
10365 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10366 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010367 ConflictKind = WhereFoundClauseKind;
10368 return true;
10369 })) {
10370 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010371 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010372 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010373 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010374 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010375 continue;
10376 }
10377 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010378 }
10379
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010380 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010381 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010382 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010383 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10384 << getOpenMPClauseName(OMPC_firstprivate) << Type
10385 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10386 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010387 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010388 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010389 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010390 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010391 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010392 continue;
10393 }
10394
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010395 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010396 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010397 buildVarDecl(*this, ELoc, Type, D->getName(),
10398 D->hasAttrs() ? &D->getAttrs() : nullptr,
10399 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010400 // Generate helper private variable and initialize it with the value of the
10401 // original variable. The address of the original variable is replaced by
10402 // the address of the new private variable in the CodeGen. This new variable
10403 // is not added to IdResolver, so the code in the OpenMP region uses
10404 // original variable for proper diagnostics and variable capturing.
10405 Expr *VDInitRefExpr = nullptr;
10406 // For arrays generate initializer for single element and replace it by the
10407 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010408 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010409 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010410 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010411 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010412 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010413 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010414 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10415 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010416 InitializedEntity Entity =
10417 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010418 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10419
10420 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10421 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10422 if (Result.isInvalid())
10423 VDPrivate->setInvalidDecl();
10424 else
10425 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010426 // Remove temp variable declaration.
10427 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010428 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010429 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10430 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010431 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10432 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010433 AddInitializerToDecl(VDPrivate,
10434 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010435 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010436 }
10437 if (VDPrivate->isInvalidDecl()) {
10438 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010439 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010440 diag::note_omp_task_predetermined_firstprivate_here);
10441 }
10442 continue;
10443 }
10444 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010445 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010446 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10447 RefExpr->getExprLoc());
10448 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010449 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010450 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010451 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010452 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010453 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010454 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010455 ExprCaptures.push_back(Ref->getDecl());
10456 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010457 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010458 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010459 Vars.push_back((VD || CurContext->isDependentContext())
10460 ? RefExpr->IgnoreParens()
10461 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010462 PrivateCopies.push_back(VDPrivateRefExpr);
10463 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010464 }
10465
Alexey Bataeved09d242014-05-28 05:53:51 +000010466 if (Vars.empty())
10467 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010468
10469 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010470 Vars, PrivateCopies, Inits,
10471 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010472}
10473
Alexander Musman1bb328c2014-06-04 13:06:39 +000010474OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10475 SourceLocation StartLoc,
10476 SourceLocation LParenLoc,
10477 SourceLocation EndLoc) {
10478 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010479 SmallVector<Expr *, 8> SrcExprs;
10480 SmallVector<Expr *, 8> DstExprs;
10481 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010482 SmallVector<Decl *, 4> ExprCaptures;
10483 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010484 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010485 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010486 SourceLocation ELoc;
10487 SourceRange ERange;
10488 Expr *SimpleRefExpr = RefExpr;
10489 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010490 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010491 // It will be analyzed later.
10492 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010493 SrcExprs.push_back(nullptr);
10494 DstExprs.push_back(nullptr);
10495 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010496 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010497 ValueDecl *D = Res.first;
10498 if (!D)
10499 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010500
Alexey Bataev74caaf22016-02-20 04:09:36 +000010501 QualType Type = D->getType();
10502 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010503
10504 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10505 // A variable that appears in a lastprivate clause must not have an
10506 // incomplete type or a reference type.
10507 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010508 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010509 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010510 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010511
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010512 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10513 // A variable that is privatized must not have a const-qualified type
10514 // unless it is of class type with a mutable member. This restriction does
10515 // not apply to the firstprivate clause.
10516 //
10517 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10518 // A variable that appears in a lastprivate clause must not have a
10519 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010520 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010521 continue;
10522
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010523 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010524 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10525 // in a Construct]
10526 // Variables with the predetermined data-sharing attributes may not be
10527 // listed in data-sharing attributes clauses, except for the cases
10528 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010529 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10530 // A list item may appear in a firstprivate or lastprivate clause but not
10531 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010532 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010533 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010534 (isOpenMPDistributeDirective(CurrDir) ||
10535 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010536 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10537 Diag(ELoc, diag::err_omp_wrong_dsa)
10538 << getOpenMPClauseName(DVar.CKind)
10539 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010540 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010541 continue;
10542 }
10543
Alexey Bataevf29276e2014-06-18 04:14:57 +000010544 // OpenMP [2.14.3.5, Restrictions, p.2]
10545 // A list item that is private within a parallel region, or that appears in
10546 // the reduction clause of a parallel construct, must not appear in a
10547 // lastprivate clause on a worksharing construct if any of the corresponding
10548 // worksharing regions ever binds to any of the corresponding parallel
10549 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010550 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010551 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010552 !isOpenMPParallelDirective(CurrDir) &&
10553 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010554 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010555 if (DVar.CKind != OMPC_shared) {
10556 Diag(ELoc, diag::err_omp_required_access)
10557 << getOpenMPClauseName(OMPC_lastprivate)
10558 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010559 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010560 continue;
10561 }
10562 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010563
Alexander Musman1bb328c2014-06-04 13:06:39 +000010564 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010565 // A variable of class type (or array thereof) that appears in a
10566 // lastprivate clause requires an accessible, unambiguous default
10567 // constructor for the class type, unless the list item is also specified
10568 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010569 // A variable of class type (or array thereof) that appears in a
10570 // lastprivate clause requires an accessible, unambiguous copy assignment
10571 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010572 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010573 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10574 Type.getUnqualifiedType(), ".lastprivate.src",
10575 D->hasAttrs() ? &D->getAttrs() : nullptr);
10576 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010577 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010578 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010579 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010580 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010581 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010582 // For arrays generate assignment operation for single element and replace
10583 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010584 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10585 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010586 if (AssignmentOp.isInvalid())
10587 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010588 AssignmentOp =
10589 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010590 if (AssignmentOp.isInvalid())
10591 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010592
Alexey Bataev74caaf22016-02-20 04:09:36 +000010593 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010594 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010595 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010596 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010597 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010598 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010599 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010600 ExprCaptures.push_back(Ref->getDecl());
10601 }
10602 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010603 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010604 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010605 ExprResult RefRes = DefaultLvalueConversion(Ref);
10606 if (!RefRes.isUsable())
10607 continue;
10608 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010609 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10610 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010611 if (!PostUpdateRes.isUsable())
10612 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010613 ExprPostUpdates.push_back(
10614 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010615 }
10616 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010617 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010618 Vars.push_back((VD || CurContext->isDependentContext())
10619 ? RefExpr->IgnoreParens()
10620 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010621 SrcExprs.push_back(PseudoSrcExpr);
10622 DstExprs.push_back(PseudoDstExpr);
10623 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010624 }
10625
10626 if (Vars.empty())
10627 return nullptr;
10628
10629 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010630 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010631 buildPreInits(Context, ExprCaptures),
10632 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010633}
10634
Alexey Bataev758e55e2013-09-06 18:03:48 +000010635OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10636 SourceLocation StartLoc,
10637 SourceLocation LParenLoc,
10638 SourceLocation EndLoc) {
10639 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010640 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010641 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010642 SourceLocation ELoc;
10643 SourceRange ERange;
10644 Expr *SimpleRefExpr = RefExpr;
10645 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010646 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010647 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010648 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010649 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010650 ValueDecl *D = Res.first;
10651 if (!D)
10652 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010653
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010654 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010655 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10656 // in a Construct]
10657 // Variables with the predetermined data-sharing attributes may not be
10658 // listed in data-sharing attributes clauses, except for the cases
10659 // listed below. For these exceptions only, listing a predetermined
10660 // variable in a data-sharing attribute clause is allowed and overrides
10661 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010662 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010663 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10664 DVar.RefExpr) {
10665 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10666 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010667 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010668 continue;
10669 }
10670
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010671 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010672 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010673 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010674 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010675 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10676 ? RefExpr->IgnoreParens()
10677 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010678 }
10679
Alexey Bataeved09d242014-05-28 05:53:51 +000010680 if (Vars.empty())
10681 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010682
10683 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10684}
10685
Alexey Bataevc5e02582014-06-16 07:08:35 +000010686namespace {
10687class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10688 DSAStackTy *Stack;
10689
10690public:
10691 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010692 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10693 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010694 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10695 return false;
10696 if (DVar.CKind != OMPC_unknown)
10697 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010698 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010699 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010700 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010701 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010702 }
10703 return false;
10704 }
10705 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010706 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010707 if (Child && Visit(Child))
10708 return true;
10709 }
10710 return false;
10711 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010712 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010713};
Alexey Bataev23b69422014-06-18 07:08:49 +000010714} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010715
Alexey Bataev60da77e2016-02-29 05:54:20 +000010716namespace {
10717// Transform MemberExpression for specified FieldDecl of current class to
10718// DeclRefExpr to specified OMPCapturedExprDecl.
10719class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10720 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010721 ValueDecl *Field = nullptr;
10722 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010723
10724public:
10725 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10726 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10727
10728 ExprResult TransformMemberExpr(MemberExpr *E) {
10729 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10730 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010731 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010732 return CapturedExpr;
10733 }
10734 return BaseTransform::TransformMemberExpr(E);
10735 }
10736 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10737};
10738} // namespace
10739
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010740template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010741static T filterLookupForUDReductionAndMapper(
10742 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010743 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010744 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010745 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010746 return Res;
10747 }
10748 }
10749 return T();
10750}
10751
Alexey Bataev43b90b72018-09-12 16:31:59 +000010752static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10753 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10754
10755 for (auto RD : D->redecls()) {
10756 // Don't bother with extra checks if we already know this one isn't visible.
10757 if (RD == D)
10758 continue;
10759
10760 auto ND = cast<NamedDecl>(RD);
10761 if (LookupResult::isVisible(SemaRef, ND))
10762 return ND;
10763 }
10764
10765 return nullptr;
10766}
10767
10768static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010769argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010770 SourceLocation Loc, QualType Ty,
10771 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10772 // Find all of the associated namespaces and classes based on the
10773 // arguments we have.
10774 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10775 Sema::AssociatedClassSet AssociatedClasses;
10776 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10777 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10778 AssociatedClasses);
10779
10780 // C++ [basic.lookup.argdep]p3:
10781 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10782 // and let Y be the lookup set produced by argument dependent
10783 // lookup (defined as follows). If X contains [...] then Y is
10784 // empty. Otherwise Y is the set of declarations found in the
10785 // namespaces associated with the argument types as described
10786 // below. The set of declarations found by the lookup of the name
10787 // is the union of X and Y.
10788 //
10789 // Here, we compute Y and add its members to the overloaded
10790 // candidate set.
10791 for (auto *NS : AssociatedNamespaces) {
10792 // When considering an associated namespace, the lookup is the
10793 // same as the lookup performed when the associated namespace is
10794 // used as a qualifier (3.4.3.2) except that:
10795 //
10796 // -- Any using-directives in the associated namespace are
10797 // ignored.
10798 //
10799 // -- Any namespace-scope friend functions declared in
10800 // associated classes are visible within their respective
10801 // namespaces even if they are not visible during an ordinary
10802 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000010803 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000010804 for (auto *D : R) {
10805 auto *Underlying = D;
10806 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10807 Underlying = USD->getTargetDecl();
10808
Michael Kruse4304e9d2019-02-19 16:38:20 +000010809 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
10810 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000010811 continue;
10812
10813 if (!SemaRef.isVisible(D)) {
10814 D = findAcceptableDecl(SemaRef, D);
10815 if (!D)
10816 continue;
10817 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10818 Underlying = USD->getTargetDecl();
10819 }
10820 Lookups.emplace_back();
10821 Lookups.back().addDecl(Underlying);
10822 }
10823 }
10824}
10825
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010826static ExprResult
10827buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10828 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10829 const DeclarationNameInfo &ReductionId, QualType Ty,
10830 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10831 if (ReductionIdScopeSpec.isInvalid())
10832 return ExprError();
10833 SmallVector<UnresolvedSet<8>, 4> Lookups;
10834 if (S) {
10835 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10836 Lookup.suppressDiagnostics();
10837 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010838 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010839 do {
10840 S = S->getParent();
10841 } while (S && !S->isDeclScope(D));
10842 if (S)
10843 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000010844 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010845 Lookups.back().append(Lookup.begin(), Lookup.end());
10846 Lookup.clear();
10847 }
10848 } else if (auto *ULE =
10849 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10850 Lookups.push_back(UnresolvedSet<8>());
10851 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010852 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010853 if (D == PrevD)
10854 Lookups.push_back(UnresolvedSet<8>());
10855 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10856 Lookups.back().addDecl(DRD);
10857 PrevD = D;
10858 }
10859 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000010860 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10861 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010862 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000010863 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010864 return !D->isInvalidDecl() &&
10865 (D->getType()->isDependentType() ||
10866 D->getType()->isInstantiationDependentType() ||
10867 D->getType()->containsUnexpandedParameterPack());
10868 })) {
10869 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000010870 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000010871 if (Set.empty())
10872 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010873 ResSet.append(Set.begin(), Set.end());
10874 // The last item marks the end of all declarations at the specified scope.
10875 ResSet.addDecl(Set[Set.size() - 1]);
10876 }
10877 return UnresolvedLookupExpr::Create(
10878 SemaRef.Context, /*NamingClass=*/nullptr,
10879 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10880 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10881 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000010882 // Lookup inside the classes.
10883 // C++ [over.match.oper]p3:
10884 // For a unary operator @ with an operand of a type whose
10885 // cv-unqualified version is T1, and for a binary operator @ with
10886 // a left operand of a type whose cv-unqualified version is T1 and
10887 // a right operand of a type whose cv-unqualified version is T2,
10888 // three sets of candidate functions, designated member
10889 // candidates, non-member candidates and built-in candidates, are
10890 // constructed as follows:
10891 // -- If T1 is a complete class type or a class currently being
10892 // defined, the set of member candidates is the result of the
10893 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10894 // the set of member candidates is empty.
10895 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10896 Lookup.suppressDiagnostics();
10897 if (const auto *TyRec = Ty->getAs<RecordType>()) {
10898 // Complete the type if it can be completed.
10899 // If the type is neither complete nor being defined, bail out now.
10900 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10901 TyRec->getDecl()->getDefinition()) {
10902 Lookup.clear();
10903 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10904 if (Lookup.empty()) {
10905 Lookups.emplace_back();
10906 Lookups.back().append(Lookup.begin(), Lookup.end());
10907 }
10908 }
10909 }
10910 // Perform ADL.
10911 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010912 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010913 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10914 if (!D->isInvalidDecl() &&
10915 SemaRef.Context.hasSameType(D->getType(), Ty))
10916 return D;
10917 return nullptr;
10918 }))
James Y Knightb92d2902019-02-05 16:05:50 +000010919 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
10920 VK_LValue, Loc);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010921 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010922 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10923 if (!D->isInvalidDecl() &&
10924 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10925 !Ty.isMoreQualifiedThan(D->getType()))
10926 return D;
10927 return nullptr;
10928 })) {
10929 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10930 /*DetectVirtual=*/false);
10931 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10932 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10933 VD->getType().getUnqualifiedType()))) {
10934 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10935 /*DiagID=*/0) !=
10936 Sema::AR_inaccessible) {
10937 SemaRef.BuildBasePathArray(Paths, BasePath);
James Y Knightb92d2902019-02-05 16:05:50 +000010938 return SemaRef.BuildDeclRefExpr(
10939 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010940 }
10941 }
10942 }
10943 }
10944 if (ReductionIdScopeSpec.isSet()) {
10945 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10946 return ExprError();
10947 }
10948 return ExprEmpty();
10949}
10950
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010951namespace {
10952/// Data for the reduction-based clauses.
10953struct ReductionData {
10954 /// List of original reduction items.
10955 SmallVector<Expr *, 8> Vars;
10956 /// List of private copies of the reduction items.
10957 SmallVector<Expr *, 8> Privates;
10958 /// LHS expressions for the reduction_op expressions.
10959 SmallVector<Expr *, 8> LHSs;
10960 /// RHS expressions for the reduction_op expressions.
10961 SmallVector<Expr *, 8> RHSs;
10962 /// Reduction operation expression.
10963 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010964 /// Taskgroup descriptors for the corresponding reduction items in
10965 /// in_reduction clauses.
10966 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010967 /// List of captures for clause.
10968 SmallVector<Decl *, 4> ExprCaptures;
10969 /// List of postupdate expressions.
10970 SmallVector<Expr *, 4> ExprPostUpdates;
10971 ReductionData() = delete;
10972 /// Reserves required memory for the reduction data.
10973 ReductionData(unsigned Size) {
10974 Vars.reserve(Size);
10975 Privates.reserve(Size);
10976 LHSs.reserve(Size);
10977 RHSs.reserve(Size);
10978 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010979 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010980 ExprCaptures.reserve(Size);
10981 ExprPostUpdates.reserve(Size);
10982 }
10983 /// Stores reduction item and reduction operation only (required for dependent
10984 /// reduction item).
10985 void push(Expr *Item, Expr *ReductionOp) {
10986 Vars.emplace_back(Item);
10987 Privates.emplace_back(nullptr);
10988 LHSs.emplace_back(nullptr);
10989 RHSs.emplace_back(nullptr);
10990 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010991 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010992 }
10993 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010994 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10995 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010996 Vars.emplace_back(Item);
10997 Privates.emplace_back(Private);
10998 LHSs.emplace_back(LHS);
10999 RHSs.emplace_back(RHS);
11000 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011001 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011002 }
11003};
11004} // namespace
11005
Alexey Bataeve3727102018-04-18 15:57:46 +000011006static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011007 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11008 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11009 const Expr *Length = OASE->getLength();
11010 if (Length == nullptr) {
11011 // For array sections of the form [1:] or [:], we would need to analyze
11012 // the lower bound...
11013 if (OASE->getColonLoc().isValid())
11014 return false;
11015
11016 // This is an array subscript which has implicit length 1!
11017 SingleElement = true;
11018 ArraySizes.push_back(llvm::APSInt::get(1));
11019 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011020 Expr::EvalResult Result;
11021 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011022 return false;
11023
Fangrui Song407659a2018-11-30 23:41:18 +000011024 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011025 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11026 ArraySizes.push_back(ConstantLengthValue);
11027 }
11028
11029 // Get the base of this array section and walk up from there.
11030 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11031
11032 // We require length = 1 for all array sections except the right-most to
11033 // guarantee that the memory region is contiguous and has no holes in it.
11034 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11035 Length = TempOASE->getLength();
11036 if (Length == nullptr) {
11037 // For array sections of the form [1:] or [:], we would need to analyze
11038 // the lower bound...
11039 if (OASE->getColonLoc().isValid())
11040 return false;
11041
11042 // This is an array subscript which has implicit length 1!
11043 ArraySizes.push_back(llvm::APSInt::get(1));
11044 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011045 Expr::EvalResult Result;
11046 if (!Length->EvaluateAsInt(Result, Context))
11047 return false;
11048
11049 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11050 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011051 return false;
11052
11053 ArraySizes.push_back(ConstantLengthValue);
11054 }
11055 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11056 }
11057
11058 // If we have a single element, we don't need to add the implicit lengths.
11059 if (!SingleElement) {
11060 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11061 // Has implicit length 1!
11062 ArraySizes.push_back(llvm::APSInt::get(1));
11063 Base = TempASE->getBase()->IgnoreParenImpCasts();
11064 }
11065 }
11066
11067 // This array section can be privatized as a single value or as a constant
11068 // sized array.
11069 return true;
11070}
11071
Alexey Bataeve3727102018-04-18 15:57:46 +000011072static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011073 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11074 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11075 SourceLocation ColonLoc, SourceLocation EndLoc,
11076 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011077 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011078 DeclarationName DN = ReductionId.getName();
11079 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011080 BinaryOperatorKind BOK = BO_Comma;
11081
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011082 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011083 // OpenMP [2.14.3.6, reduction clause]
11084 // C
11085 // reduction-identifier is either an identifier or one of the following
11086 // operators: +, -, *, &, |, ^, && and ||
11087 // C++
11088 // reduction-identifier is either an id-expression or one of the following
11089 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011090 switch (OOK) {
11091 case OO_Plus:
11092 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011093 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011094 break;
11095 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011096 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011097 break;
11098 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011099 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011100 break;
11101 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011102 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011103 break;
11104 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011105 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011106 break;
11107 case OO_AmpAmp:
11108 BOK = BO_LAnd;
11109 break;
11110 case OO_PipePipe:
11111 BOK = BO_LOr;
11112 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011113 case OO_New:
11114 case OO_Delete:
11115 case OO_Array_New:
11116 case OO_Array_Delete:
11117 case OO_Slash:
11118 case OO_Percent:
11119 case OO_Tilde:
11120 case OO_Exclaim:
11121 case OO_Equal:
11122 case OO_Less:
11123 case OO_Greater:
11124 case OO_LessEqual:
11125 case OO_GreaterEqual:
11126 case OO_PlusEqual:
11127 case OO_MinusEqual:
11128 case OO_StarEqual:
11129 case OO_SlashEqual:
11130 case OO_PercentEqual:
11131 case OO_CaretEqual:
11132 case OO_AmpEqual:
11133 case OO_PipeEqual:
11134 case OO_LessLess:
11135 case OO_GreaterGreater:
11136 case OO_LessLessEqual:
11137 case OO_GreaterGreaterEqual:
11138 case OO_EqualEqual:
11139 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011140 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011141 case OO_PlusPlus:
11142 case OO_MinusMinus:
11143 case OO_Comma:
11144 case OO_ArrowStar:
11145 case OO_Arrow:
11146 case OO_Call:
11147 case OO_Subscript:
11148 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011149 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011150 case NUM_OVERLOADED_OPERATORS:
11151 llvm_unreachable("Unexpected reduction identifier");
11152 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011153 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011154 if (II->isStr("max"))
11155 BOK = BO_GT;
11156 else if (II->isStr("min"))
11157 BOK = BO_LT;
11158 }
11159 break;
11160 }
11161 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011162 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011163 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011164 else
11165 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011166 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011167
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011168 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11169 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011170 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011171 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011172 // OpenMP [2.1, C/C++]
11173 // A list item is a variable or array section, subject to the restrictions
11174 // specified in Section 2.4 on page 42 and in each of the sections
11175 // describing clauses and directives for which a list appears.
11176 // OpenMP [2.14.3.3, Restrictions, p.1]
11177 // A variable that is part of another variable (as an array or
11178 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011179 if (!FirstIter && IR != ER)
11180 ++IR;
11181 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011182 SourceLocation ELoc;
11183 SourceRange ERange;
11184 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011185 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011186 /*AllowArraySection=*/true);
11187 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011188 // Try to find 'declare reduction' corresponding construct before using
11189 // builtin/overloaded operators.
11190 QualType Type = Context.DependentTy;
11191 CXXCastPath BasePath;
11192 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011193 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011194 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011195 Expr *ReductionOp = nullptr;
11196 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011197 (DeclareReductionRef.isUnset() ||
11198 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011199 ReductionOp = DeclareReductionRef.get();
11200 // It will be analyzed later.
11201 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011202 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011203 ValueDecl *D = Res.first;
11204 if (!D)
11205 continue;
11206
Alexey Bataev88202be2017-07-27 13:20:36 +000011207 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011208 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011209 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11210 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011211 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011212 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011213 } else if (OASE) {
11214 QualType BaseType =
11215 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11216 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011217 Type = ATy->getElementType();
11218 else
11219 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011220 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011221 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011222 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011223 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011224 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011225
Alexey Bataevc5e02582014-06-16 07:08:35 +000011226 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11227 // A variable that appears in a private clause must not have an incomplete
11228 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011229 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011230 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011231 continue;
11232 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011233 // A list item that appears in a reduction clause must not be
11234 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011235 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11236 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011237 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011238
11239 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011240 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11241 // If a list-item is a reference type then it must bind to the same object
11242 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011243 if (!ASE && !OASE) {
11244 if (VD) {
11245 VarDecl *VDDef = VD->getDefinition();
11246 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11247 DSARefChecker Check(Stack);
11248 if (Check.Visit(VDDef->getInit())) {
11249 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11250 << getOpenMPClauseName(ClauseKind) << ERange;
11251 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11252 continue;
11253 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011254 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011255 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011256
Alexey Bataevbc529672018-09-28 19:33:14 +000011257 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11258 // in a Construct]
11259 // Variables with the predetermined data-sharing attributes may not be
11260 // listed in data-sharing attributes clauses, except for the cases
11261 // listed below. For these exceptions only, listing a predetermined
11262 // variable in a data-sharing attribute clause is allowed and overrides
11263 // the variable's predetermined data-sharing attributes.
11264 // OpenMP [2.14.3.6, Restrictions, p.3]
11265 // Any number of reduction clauses can be specified on the directive,
11266 // but a list item can appear only once in the reduction clauses for that
11267 // directive.
11268 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11269 if (DVar.CKind == OMPC_reduction) {
11270 S.Diag(ELoc, diag::err_omp_once_referenced)
11271 << getOpenMPClauseName(ClauseKind);
11272 if (DVar.RefExpr)
11273 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11274 continue;
11275 }
11276 if (DVar.CKind != OMPC_unknown) {
11277 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11278 << getOpenMPClauseName(DVar.CKind)
11279 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011280 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011281 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011282 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011283
11284 // OpenMP [2.14.3.6, Restrictions, p.1]
11285 // A list item that appears in a reduction clause of a worksharing
11286 // construct must be shared in the parallel regions to which any of the
11287 // worksharing regions arising from the worksharing construct bind.
11288 if (isOpenMPWorksharingDirective(CurrDir) &&
11289 !isOpenMPParallelDirective(CurrDir) &&
11290 !isOpenMPTeamsDirective(CurrDir)) {
11291 DVar = Stack->getImplicitDSA(D, true);
11292 if (DVar.CKind != OMPC_shared) {
11293 S.Diag(ELoc, diag::err_omp_required_access)
11294 << getOpenMPClauseName(OMPC_reduction)
11295 << getOpenMPClauseName(OMPC_shared);
11296 reportOriginalDsa(S, Stack, D, DVar);
11297 continue;
11298 }
11299 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011300 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011301
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011302 // Try to find 'declare reduction' corresponding construct before using
11303 // builtin/overloaded operators.
11304 CXXCastPath BasePath;
11305 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011306 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011307 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11308 if (DeclareReductionRef.isInvalid())
11309 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011310 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011311 (DeclareReductionRef.isUnset() ||
11312 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011313 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011314 continue;
11315 }
11316 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11317 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011318 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011319 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011320 << Type << ReductionIdRange;
11321 continue;
11322 }
11323
11324 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11325 // The type of a list item that appears in a reduction clause must be valid
11326 // for the reduction-identifier. For a max or min reduction in C, the type
11327 // of the list item must be an allowed arithmetic data type: char, int,
11328 // float, double, or _Bool, possibly modified with long, short, signed, or
11329 // unsigned. For a max or min reduction in C++, the type of the list item
11330 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11331 // double, or bool, possibly modified with long, short, signed, or unsigned.
11332 if (DeclareReductionRef.isUnset()) {
11333 if ((BOK == BO_GT || BOK == BO_LT) &&
11334 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011335 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11336 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011337 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011338 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011339 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11340 VarDecl::DeclarationOnly;
11341 S.Diag(D->getLocation(),
11342 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011343 << D;
11344 }
11345 continue;
11346 }
11347 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011348 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011349 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11350 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011351 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011352 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11353 VarDecl::DeclarationOnly;
11354 S.Diag(D->getLocation(),
11355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011356 << D;
11357 }
11358 continue;
11359 }
11360 }
11361
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011362 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011363 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11364 D->hasAttrs() ? &D->getAttrs() : nullptr);
11365 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11366 D->hasAttrs() ? &D->getAttrs() : nullptr);
11367 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011368
11369 // Try if we can determine constant lengths for all array sections and avoid
11370 // the VLA.
11371 bool ConstantLengthOASE = false;
11372 if (OASE) {
11373 bool SingleElement;
11374 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011375 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011376 Context, OASE, SingleElement, ArraySizes);
11377
11378 // If we don't have a single element, we must emit a constant array type.
11379 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011380 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011381 PrivateTy = Context.getConstantArrayType(
11382 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011383 }
11384 }
11385
11386 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011387 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011388 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011389 if (!Context.getTargetInfo().isVLASupported() &&
11390 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11391 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11392 S.Diag(ELoc, diag::note_vla_unsupported);
11393 continue;
11394 }
David Majnemer9d168222016-08-05 17:44:54 +000011395 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011396 // Create pseudo array type for private copy. The size for this array will
11397 // be generated during codegen.
11398 // For array subscripts or single variables Private Ty is the same as Type
11399 // (type of the variable or single array element).
11400 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011401 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011402 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011403 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011404 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011405 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011406 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011407 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011408 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011409 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011410 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11411 D->hasAttrs() ? &D->getAttrs() : nullptr,
11412 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011413 // Add initializer for private variable.
11414 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011415 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11416 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011417 if (DeclareReductionRef.isUsable()) {
11418 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11419 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11420 if (DRD->getInitializer()) {
11421 Init = DRDRef;
11422 RHSVD->setInit(DRDRef);
11423 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011424 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011425 } else {
11426 switch (BOK) {
11427 case BO_Add:
11428 case BO_Xor:
11429 case BO_Or:
11430 case BO_LOr:
11431 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11432 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011433 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011434 break;
11435 case BO_Mul:
11436 case BO_LAnd:
11437 if (Type->isScalarType() || Type->isAnyComplexType()) {
11438 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011439 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011440 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011441 break;
11442 case BO_And: {
11443 // '&' reduction op - initializer is '~0'.
11444 QualType OrigType = Type;
11445 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11446 Type = ComplexTy->getElementType();
11447 if (Type->isRealFloatingType()) {
11448 llvm::APFloat InitValue =
11449 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11450 /*isIEEE=*/true);
11451 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11452 Type, ELoc);
11453 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011454 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011455 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11456 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11457 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11458 }
11459 if (Init && OrigType->isAnyComplexType()) {
11460 // Init = 0xFFFF + 0xFFFFi;
11461 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011462 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011463 }
11464 Type = OrigType;
11465 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011466 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011467 case BO_LT:
11468 case BO_GT: {
11469 // 'min' reduction op - initializer is 'Largest representable number in
11470 // the reduction list item type'.
11471 // 'max' reduction op - initializer is 'Least representable number in
11472 // the reduction list item type'.
11473 if (Type->isIntegerType() || Type->isPointerType()) {
11474 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011475 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011476 QualType IntTy =
11477 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11478 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011479 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11480 : llvm::APInt::getMinValue(Size)
11481 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11482 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011483 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11484 if (Type->isPointerType()) {
11485 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011486 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011487 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011488 if (CastExpr.isInvalid())
11489 continue;
11490 Init = CastExpr.get();
11491 }
11492 } else if (Type->isRealFloatingType()) {
11493 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11494 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11495 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11496 Type, ELoc);
11497 }
11498 break;
11499 }
11500 case BO_PtrMemD:
11501 case BO_PtrMemI:
11502 case BO_MulAssign:
11503 case BO_Div:
11504 case BO_Rem:
11505 case BO_Sub:
11506 case BO_Shl:
11507 case BO_Shr:
11508 case BO_LE:
11509 case BO_GE:
11510 case BO_EQ:
11511 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011512 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011513 case BO_AndAssign:
11514 case BO_XorAssign:
11515 case BO_OrAssign:
11516 case BO_Assign:
11517 case BO_AddAssign:
11518 case BO_SubAssign:
11519 case BO_DivAssign:
11520 case BO_RemAssign:
11521 case BO_ShlAssign:
11522 case BO_ShrAssign:
11523 case BO_Comma:
11524 llvm_unreachable("Unexpected reduction operation");
11525 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011526 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011527 if (Init && DeclareReductionRef.isUnset())
11528 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11529 else if (!Init)
11530 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011531 if (RHSVD->isInvalidDecl())
11532 continue;
11533 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011534 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11535 << Type << ReductionIdRange;
11536 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11537 VarDecl::DeclarationOnly;
11538 S.Diag(D->getLocation(),
11539 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011540 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011541 continue;
11542 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011543 // Store initializer for single element in private copy. Will be used during
11544 // codegen.
11545 PrivateVD->setInit(RHSVD->getInit());
11546 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011547 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011548 ExprResult ReductionOp;
11549 if (DeclareReductionRef.isUsable()) {
11550 QualType RedTy = DeclareReductionRef.get()->getType();
11551 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011552 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11553 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011554 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011555 LHS = S.DefaultLvalueConversion(LHS.get());
11556 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011557 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11558 CK_UncheckedDerivedToBase, LHS.get(),
11559 &BasePath, LHS.get()->getValueKind());
11560 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11561 CK_UncheckedDerivedToBase, RHS.get(),
11562 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011563 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011564 FunctionProtoType::ExtProtoInfo EPI;
11565 QualType Params[] = {PtrRedTy, PtrRedTy};
11566 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11567 auto *OVE = new (Context) OpaqueValueExpr(
11568 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011569 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011570 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011571 ReductionOp =
11572 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011573 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011574 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011575 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011576 if (ReductionOp.isUsable()) {
11577 if (BOK != BO_LT && BOK != BO_GT) {
11578 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011579 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011580 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011581 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011582 auto *ConditionalOp = new (Context)
11583 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11584 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011585 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011586 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011587 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011588 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011589 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011590 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11591 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011592 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011593 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011594 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011595 }
11596
Alexey Bataevfa312f32017-07-21 18:48:21 +000011597 // OpenMP [2.15.4.6, Restrictions, p.2]
11598 // A list item that appears in an in_reduction clause of a task construct
11599 // must appear in a task_reduction clause of a construct associated with a
11600 // taskgroup region that includes the participating task in its taskgroup
11601 // set. The construct associated with the innermost region that meets this
11602 // condition must specify the same reduction-identifier as the in_reduction
11603 // clause.
11604 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011605 SourceRange ParentSR;
11606 BinaryOperatorKind ParentBOK;
11607 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011608 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011609 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011610 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11611 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011612 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011613 Stack->getTopMostTaskgroupReductionData(
11614 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011615 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11616 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11617 if (!IsParentBOK && !IsParentReductionOp) {
11618 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11619 continue;
11620 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011621 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11622 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11623 IsParentReductionOp) {
11624 bool EmitError = true;
11625 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11626 llvm::FoldingSetNodeID RedId, ParentRedId;
11627 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11628 DeclareReductionRef.get()->Profile(RedId, Context,
11629 /*Canonical=*/true);
11630 EmitError = RedId != ParentRedId;
11631 }
11632 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011633 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011634 diag::err_omp_reduction_identifier_mismatch)
11635 << ReductionIdRange << RefExpr->getSourceRange();
11636 S.Diag(ParentSR.getBegin(),
11637 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011638 << ParentSR
11639 << (IsParentBOK ? ParentBOKDSA.RefExpr
11640 : ParentReductionOpDSA.RefExpr)
11641 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011642 continue;
11643 }
11644 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011645 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11646 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011647 }
11648
Alexey Bataev60da77e2016-02-29 05:54:20 +000011649 DeclRefExpr *Ref = nullptr;
11650 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011651 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011652 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011653 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011654 VarsExpr =
11655 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11656 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011657 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011658 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011659 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011660 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011661 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011662 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011663 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011664 if (!RefRes.isUsable())
11665 continue;
11666 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011667 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11668 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011669 if (!PostUpdateRes.isUsable())
11670 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011671 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11672 Stack->getCurrentDirective() == OMPD_taskgroup) {
11673 S.Diag(RefExpr->getExprLoc(),
11674 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011675 << RefExpr->getSourceRange();
11676 continue;
11677 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011678 RD.ExprPostUpdates.emplace_back(
11679 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011680 }
11681 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011682 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011683 // All reduction items are still marked as reduction (to do not increase
11684 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011685 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011686 if (CurrDir == OMPD_taskgroup) {
11687 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011688 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11689 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011690 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011691 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011692 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011693 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11694 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011695 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011696 return RD.Vars.empty();
11697}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011698
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011699OMPClause *Sema::ActOnOpenMPReductionClause(
11700 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11701 SourceLocation ColonLoc, SourceLocation EndLoc,
11702 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11703 ArrayRef<Expr *> UnresolvedReductions) {
11704 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011705 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011706 StartLoc, LParenLoc, ColonLoc, EndLoc,
11707 ReductionIdScopeSpec, ReductionId,
11708 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011709 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011710
Alexey Bataevc5e02582014-06-16 07:08:35 +000011711 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011712 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11713 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11714 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11715 buildPreInits(Context, RD.ExprCaptures),
11716 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011717}
11718
Alexey Bataev169d96a2017-07-18 20:17:46 +000011719OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11720 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11721 SourceLocation ColonLoc, SourceLocation EndLoc,
11722 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11723 ArrayRef<Expr *> UnresolvedReductions) {
11724 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011725 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11726 StartLoc, LParenLoc, ColonLoc, EndLoc,
11727 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011728 UnresolvedReductions, RD))
11729 return nullptr;
11730
11731 return OMPTaskReductionClause::Create(
11732 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11733 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11734 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11735 buildPreInits(Context, RD.ExprCaptures),
11736 buildPostUpdate(*this, RD.ExprPostUpdates));
11737}
11738
Alexey Bataevfa312f32017-07-21 18:48:21 +000011739OMPClause *Sema::ActOnOpenMPInReductionClause(
11740 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11741 SourceLocation ColonLoc, SourceLocation EndLoc,
11742 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11743 ArrayRef<Expr *> UnresolvedReductions) {
11744 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011745 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011746 StartLoc, LParenLoc, ColonLoc, EndLoc,
11747 ReductionIdScopeSpec, ReductionId,
11748 UnresolvedReductions, RD))
11749 return nullptr;
11750
11751 return OMPInReductionClause::Create(
11752 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11753 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011754 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011755 buildPreInits(Context, RD.ExprCaptures),
11756 buildPostUpdate(*this, RD.ExprPostUpdates));
11757}
11758
Alexey Bataevecba70f2016-04-12 11:02:11 +000011759bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11760 SourceLocation LinLoc) {
11761 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11762 LinKind == OMPC_LINEAR_unknown) {
11763 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11764 return true;
11765 }
11766 return false;
11767}
11768
Alexey Bataeve3727102018-04-18 15:57:46 +000011769bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011770 OpenMPLinearClauseKind LinKind,
11771 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011772 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011773 // A variable must not have an incomplete type or a reference type.
11774 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11775 return true;
11776 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11777 !Type->isReferenceType()) {
11778 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11779 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11780 return true;
11781 }
11782 Type = Type.getNonReferenceType();
11783
Joel E. Dennybae586f2019-01-04 22:12:13 +000011784 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11785 // A variable that is privatized must not have a const-qualified type
11786 // unless it is of class type with a mutable member. This restriction does
11787 // not apply to the firstprivate clause.
11788 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011789 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011790
11791 // A list item must be of integral or pointer type.
11792 Type = Type.getUnqualifiedType().getCanonicalType();
11793 const auto *Ty = Type.getTypePtrOrNull();
11794 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11795 !Ty->isPointerType())) {
11796 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11797 if (D) {
11798 bool IsDecl =
11799 !VD ||
11800 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11801 Diag(D->getLocation(),
11802 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11803 << D;
11804 }
11805 return true;
11806 }
11807 return false;
11808}
11809
Alexey Bataev182227b2015-08-20 10:54:39 +000011810OMPClause *Sema::ActOnOpenMPLinearClause(
11811 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11812 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11813 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011814 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011815 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000011816 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011817 SmallVector<Decl *, 4> ExprCaptures;
11818 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011819 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000011820 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000011821 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011822 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011823 SourceLocation ELoc;
11824 SourceRange ERange;
11825 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011826 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011827 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011828 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011829 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011830 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000011831 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000011832 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011833 ValueDecl *D = Res.first;
11834 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000011835 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000011836
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011837 QualType Type = D->getType();
11838 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000011839
11840 // OpenMP [2.14.3.7, linear clause]
11841 // A list-item cannot appear in more than one linear clause.
11842 // A list-item that appears in a linear clause cannot appear in any
11843 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011844 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000011845 if (DVar.RefExpr) {
11846 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11847 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000011848 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000011849 continue;
11850 }
11851
Alexey Bataevecba70f2016-04-12 11:02:11 +000011852 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000011853 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011854 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000011855
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011856 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000011857 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011858 buildVarDecl(*this, ELoc, Type, D->getName(),
11859 D->hasAttrs() ? &D->getAttrs() : nullptr,
11860 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011861 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011862 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011863 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011864 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011865 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011866 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011867 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011868 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011869 ExprCaptures.push_back(Ref->getDecl());
11870 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11871 ExprResult RefRes = DefaultLvalueConversion(Ref);
11872 if (!RefRes.isUsable())
11873 continue;
11874 ExprResult PostUpdateRes =
11875 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11876 SimpleRefExpr, RefRes.get());
11877 if (!PostUpdateRes.isUsable())
11878 continue;
11879 ExprPostUpdates.push_back(
11880 IgnoredValueConversions(PostUpdateRes.get()).get());
11881 }
11882 }
11883 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011884 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011885 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011886 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011887 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011888 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011889 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011890 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011891
11892 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011893 Vars.push_back((VD || CurContext->isDependentContext())
11894 ? RefExpr->IgnoreParens()
11895 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011896 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000011897 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000011898 }
11899
11900 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011901 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011902
11903 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000011904 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011905 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11906 !Step->isInstantiationDependent() &&
11907 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011908 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011909 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000011910 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011911 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011912 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000011913
Alexander Musman3276a272015-03-21 10:12:56 +000011914 // Build var to save the step value.
11915 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011916 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000011917 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011918 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011919 ExprResult CalcStep =
11920 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011921 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011922
Alexander Musman8dba6642014-04-22 13:09:42 +000011923 // Warn about zero linear step (it would be probably better specified as
11924 // making corresponding variables 'const').
11925 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011926 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11927 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011928 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11929 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011930 if (!IsConstant && CalcStep.isUsable()) {
11931 // Calculate the step beforehand instead of doing this on each iteration.
11932 // (This is not used if the number of iterations may be kfold-ed).
11933 CalcStepExpr = CalcStep.get();
11934 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011935 }
11936
Alexey Bataev182227b2015-08-20 10:54:39 +000011937 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11938 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011939 StepExpr, CalcStepExpr,
11940 buildPreInits(Context, ExprCaptures),
11941 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011942}
11943
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011944static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11945 Expr *NumIterations, Sema &SemaRef,
11946 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011947 // Walk the vars and build update/final expressions for the CodeGen.
11948 SmallVector<Expr *, 8> Updates;
11949 SmallVector<Expr *, 8> Finals;
11950 Expr *Step = Clause.getStep();
11951 Expr *CalcStep = Clause.getCalcStep();
11952 // OpenMP [2.14.3.7, linear clause]
11953 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000011954 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000011955 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011956 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000011957 Step = cast<BinaryOperator>(CalcStep)->getLHS();
11958 bool HasErrors = false;
11959 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011960 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000011961 OpenMPLinearClauseKind LinKind = Clause.getModifier();
11962 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011963 SourceLocation ELoc;
11964 SourceRange ERange;
11965 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011966 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011967 ValueDecl *D = Res.first;
11968 if (Res.second || !D) {
11969 Updates.push_back(nullptr);
11970 Finals.push_back(nullptr);
11971 HasErrors = true;
11972 continue;
11973 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011974 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011975 // OpenMP [2.15.11, distribute simd Construct]
11976 // A list item may not appear in a linear clause, unless it is the loop
11977 // iteration variable.
11978 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11979 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11980 SemaRef.Diag(ELoc,
11981 diag::err_omp_linear_distribute_var_non_loop_iteration);
11982 Updates.push_back(nullptr);
11983 Finals.push_back(nullptr);
11984 HasErrors = true;
11985 continue;
11986 }
Alexander Musman3276a272015-03-21 10:12:56 +000011987 Expr *InitExpr = *CurInit;
11988
11989 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011990 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011991 Expr *CapturedRef;
11992 if (LinKind == OMPC_LINEAR_uval)
11993 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11994 else
11995 CapturedRef =
11996 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11997 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11998 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011999
12000 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012001 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012002 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012003 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012004 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012005 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012006 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012007 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012008 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012009 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012010
12011 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012012 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012013 if (!Info.first)
12014 Final =
12015 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12016 InitExpr, NumIterations, Step, /*Subtract=*/false);
12017 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012018 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012019 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012020 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012021
Alexander Musman3276a272015-03-21 10:12:56 +000012022 if (!Update.isUsable() || !Final.isUsable()) {
12023 Updates.push_back(nullptr);
12024 Finals.push_back(nullptr);
12025 HasErrors = true;
12026 } else {
12027 Updates.push_back(Update.get());
12028 Finals.push_back(Final.get());
12029 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012030 ++CurInit;
12031 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012032 }
12033 Clause.setUpdates(Updates);
12034 Clause.setFinals(Finals);
12035 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012036}
12037
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012038OMPClause *Sema::ActOnOpenMPAlignedClause(
12039 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12040 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012041 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012042 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012043 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12044 SourceLocation ELoc;
12045 SourceRange ERange;
12046 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012047 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012048 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012049 // It will be analyzed later.
12050 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012051 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012052 ValueDecl *D = Res.first;
12053 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012054 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012055
Alexey Bataev1efd1662016-03-29 10:59:56 +000012056 QualType QType = D->getType();
12057 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012058
12059 // OpenMP [2.8.1, simd construct, Restrictions]
12060 // The type of list items appearing in the aligned clause must be
12061 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012062 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012063 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012064 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012065 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012066 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012067 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012068 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012069 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012070 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012071 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012072 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012073 continue;
12074 }
12075
12076 // OpenMP [2.8.1, simd construct, Restrictions]
12077 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012078 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012079 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012080 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12081 << getOpenMPClauseName(OMPC_aligned);
12082 continue;
12083 }
12084
Alexey Bataev1efd1662016-03-29 10:59:56 +000012085 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012086 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012087 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12088 Vars.push_back(DefaultFunctionArrayConversion(
12089 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12090 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012091 }
12092
12093 // OpenMP [2.8.1, simd construct, Description]
12094 // The parameter of the aligned clause, alignment, must be a constant
12095 // positive integer expression.
12096 // If no optional parameter is specified, implementation-defined default
12097 // alignments for SIMD instructions on the target platforms are assumed.
12098 if (Alignment != nullptr) {
12099 ExprResult AlignResult =
12100 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12101 if (AlignResult.isInvalid())
12102 return nullptr;
12103 Alignment = AlignResult.get();
12104 }
12105 if (Vars.empty())
12106 return nullptr;
12107
12108 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12109 EndLoc, Vars, Alignment);
12110}
12111
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012112OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12113 SourceLocation StartLoc,
12114 SourceLocation LParenLoc,
12115 SourceLocation EndLoc) {
12116 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012117 SmallVector<Expr *, 8> SrcExprs;
12118 SmallVector<Expr *, 8> DstExprs;
12119 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012120 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012121 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12122 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012123 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012124 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012125 SrcExprs.push_back(nullptr);
12126 DstExprs.push_back(nullptr);
12127 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012128 continue;
12129 }
12130
Alexey Bataeved09d242014-05-28 05:53:51 +000012131 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012132 // OpenMP [2.1, C/C++]
12133 // A list item is a variable name.
12134 // OpenMP [2.14.4.1, Restrictions, p.1]
12135 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012136 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012137 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012138 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12139 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012140 continue;
12141 }
12142
12143 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012144 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012145
12146 QualType Type = VD->getType();
12147 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12148 // It will be analyzed later.
12149 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012150 SrcExprs.push_back(nullptr);
12151 DstExprs.push_back(nullptr);
12152 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012153 continue;
12154 }
12155
12156 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12157 // A list item that appears in a copyin clause must be threadprivate.
12158 if (!DSAStack->isThreadPrivate(VD)) {
12159 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012160 << getOpenMPClauseName(OMPC_copyin)
12161 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012162 continue;
12163 }
12164
12165 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12166 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012167 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012168 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012169 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12170 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012171 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012172 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012173 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012174 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012175 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012176 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012177 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012178 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012179 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012180 // For arrays generate assignment operation for single element and replace
12181 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012182 ExprResult AssignmentOp =
12183 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12184 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012185 if (AssignmentOp.isInvalid())
12186 continue;
12187 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012188 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012189 if (AssignmentOp.isInvalid())
12190 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012191
12192 DSAStack->addDSA(VD, DE, OMPC_copyin);
12193 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012194 SrcExprs.push_back(PseudoSrcExpr);
12195 DstExprs.push_back(PseudoDstExpr);
12196 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012197 }
12198
Alexey Bataeved09d242014-05-28 05:53:51 +000012199 if (Vars.empty())
12200 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012201
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012202 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12203 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012204}
12205
Alexey Bataevbae9a792014-06-27 10:37:06 +000012206OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12207 SourceLocation StartLoc,
12208 SourceLocation LParenLoc,
12209 SourceLocation EndLoc) {
12210 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012211 SmallVector<Expr *, 8> SrcExprs;
12212 SmallVector<Expr *, 8> DstExprs;
12213 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012214 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012215 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12216 SourceLocation ELoc;
12217 SourceRange ERange;
12218 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012219 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012220 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012221 // It will be analyzed later.
12222 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012223 SrcExprs.push_back(nullptr);
12224 DstExprs.push_back(nullptr);
12225 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012226 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012227 ValueDecl *D = Res.first;
12228 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012229 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012230
Alexey Bataeve122da12016-03-17 10:50:17 +000012231 QualType Type = D->getType();
12232 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012233
12234 // OpenMP [2.14.4.2, Restrictions, p.2]
12235 // A list item that appears in a copyprivate clause may not appear in a
12236 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012237 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012238 DSAStackTy::DSAVarData DVar =
12239 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012240 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12241 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012242 Diag(ELoc, diag::err_omp_wrong_dsa)
12243 << getOpenMPClauseName(DVar.CKind)
12244 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012245 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012246 continue;
12247 }
12248
12249 // OpenMP [2.11.4.2, Restrictions, p.1]
12250 // All list items that appear in a copyprivate clause must be either
12251 // threadprivate or private in the enclosing context.
12252 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012253 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012254 if (DVar.CKind == OMPC_shared) {
12255 Diag(ELoc, diag::err_omp_required_access)
12256 << getOpenMPClauseName(OMPC_copyprivate)
12257 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012258 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012259 continue;
12260 }
12261 }
12262 }
12263
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012264 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012265 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012266 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012267 << getOpenMPClauseName(OMPC_copyprivate) << Type
12268 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012269 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012270 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012271 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012272 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012273 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012274 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012275 continue;
12276 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012277
Alexey Bataevbae9a792014-06-27 10:37:06 +000012278 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12279 // A variable of class type (or array thereof) that appears in a
12280 // copyin clause requires an accessible, unambiguous copy assignment
12281 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012282 Type = Context.getBaseElementType(Type.getNonReferenceType())
12283 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012284 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012285 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012286 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012287 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12288 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012289 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012290 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012291 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12292 ExprResult AssignmentOp = BuildBinOp(
12293 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012294 if (AssignmentOp.isInvalid())
12295 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012296 AssignmentOp =
12297 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012298 if (AssignmentOp.isInvalid())
12299 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012300
12301 // No need to mark vars as copyprivate, they are already threadprivate or
12302 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012303 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012304 Vars.push_back(
12305 VD ? RefExpr->IgnoreParens()
12306 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012307 SrcExprs.push_back(PseudoSrcExpr);
12308 DstExprs.push_back(PseudoDstExpr);
12309 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012310 }
12311
12312 if (Vars.empty())
12313 return nullptr;
12314
Alexey Bataeva63048e2015-03-23 06:18:07 +000012315 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12316 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012317}
12318
Alexey Bataev6125da92014-07-21 11:26:11 +000012319OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12320 SourceLocation StartLoc,
12321 SourceLocation LParenLoc,
12322 SourceLocation EndLoc) {
12323 if (VarList.empty())
12324 return nullptr;
12325
12326 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12327}
Alexey Bataevdea47612014-07-23 07:46:59 +000012328
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012329OMPClause *
12330Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12331 SourceLocation DepLoc, SourceLocation ColonLoc,
12332 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12333 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012334 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012335 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012336 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012337 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012338 return nullptr;
12339 }
12340 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012341 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12342 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012343 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012344 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012345 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12346 /*Last=*/OMPC_DEPEND_unknown, Except)
12347 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012348 return nullptr;
12349 }
12350 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012351 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012352 llvm::APSInt DepCounter(/*BitWidth=*/32);
12353 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012354 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12355 if (const Expr *OrderedCountExpr =
12356 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012357 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12358 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012359 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012360 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012361 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012362 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12363 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12364 // It will be analyzed later.
12365 Vars.push_back(RefExpr);
12366 continue;
12367 }
12368
12369 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012370 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012371 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012372 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012373 DepCounter >= TotalDepCount) {
12374 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12375 continue;
12376 }
12377 ++DepCounter;
12378 // OpenMP [2.13.9, Summary]
12379 // depend(dependence-type : vec), where dependence-type is:
12380 // 'sink' and where vec is the iteration vector, which has the form:
12381 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12382 // where n is the value specified by the ordered clause in the loop
12383 // directive, xi denotes the loop iteration variable of the i-th nested
12384 // loop associated with the loop directive, and di is a constant
12385 // non-negative integer.
12386 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012387 // It will be analyzed later.
12388 Vars.push_back(RefExpr);
12389 continue;
12390 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012391 SimpleExpr = SimpleExpr->IgnoreImplicit();
12392 OverloadedOperatorKind OOK = OO_None;
12393 SourceLocation OOLoc;
12394 Expr *LHS = SimpleExpr;
12395 Expr *RHS = nullptr;
12396 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12397 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12398 OOLoc = BO->getOperatorLoc();
12399 LHS = BO->getLHS()->IgnoreParenImpCasts();
12400 RHS = BO->getRHS()->IgnoreParenImpCasts();
12401 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12402 OOK = OCE->getOperator();
12403 OOLoc = OCE->getOperatorLoc();
12404 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12405 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12406 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12407 OOK = MCE->getMethodDecl()
12408 ->getNameInfo()
12409 .getName()
12410 .getCXXOverloadedOperator();
12411 OOLoc = MCE->getCallee()->getExprLoc();
12412 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12413 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012414 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012415 SourceLocation ELoc;
12416 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012417 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012418 if (Res.second) {
12419 // It will be analyzed later.
12420 Vars.push_back(RefExpr);
12421 }
12422 ValueDecl *D = Res.first;
12423 if (!D)
12424 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012425
Alexey Bataev17daedf2018-02-15 22:42:57 +000012426 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12427 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12428 continue;
12429 }
12430 if (RHS) {
12431 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12432 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12433 if (RHSRes.isInvalid())
12434 continue;
12435 }
12436 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012437 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012438 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012439 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012440 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012441 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012442 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12443 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012444 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012445 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012446 continue;
12447 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012448 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012449 } else {
12450 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12451 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12452 (ASE &&
12453 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12454 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12455 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12456 << RefExpr->getSourceRange();
12457 continue;
12458 }
12459 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12460 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12461 ExprResult Res =
12462 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12463 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12464 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12465 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12466 << RefExpr->getSourceRange();
12467 continue;
12468 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012469 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012470 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012471 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012472
12473 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12474 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012475 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012476 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12477 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12478 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12479 }
12480 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12481 Vars.empty())
12482 return nullptr;
12483
Alexey Bataev8b427062016-05-25 12:36:08 +000012484 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012485 DepKind, DepLoc, ColonLoc, Vars,
12486 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012487 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12488 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012489 DSAStack->addDoacrossDependClause(C, OpsOffs);
12490 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012491}
Michael Wonge710d542015-08-07 16:16:36 +000012492
12493OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12494 SourceLocation LParenLoc,
12495 SourceLocation EndLoc) {
12496 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012497 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012498
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012499 // OpenMP [2.9.1, Restrictions]
12500 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012501 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012502 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012503 return nullptr;
12504
Alexey Bataev931e19b2017-10-02 16:32:39 +000012505 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012506 OpenMPDirectiveKind CaptureRegion =
12507 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12508 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012509 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012510 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012511 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12512 HelperValStmt = buildPreInits(Context, Captures);
12513 }
12514
Alexey Bataev8451efa2018-01-15 19:06:12 +000012515 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12516 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012517}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012518
Alexey Bataeve3727102018-04-18 15:57:46 +000012519static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012520 DSAStackTy *Stack, QualType QTy,
12521 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012522 NamedDecl *ND;
12523 if (QTy->isIncompleteType(&ND)) {
12524 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12525 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012526 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012527 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12528 !QTy.isTrivialType(SemaRef.Context))
12529 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012530 return true;
12531}
12532
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012533/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012534/// (array section or array subscript) does NOT specify the whole size of the
12535/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012536static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012537 const Expr *E,
12538 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012539 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012540
12541 // If this is an array subscript, it refers to the whole size if the size of
12542 // the dimension is constant and equals 1. Also, an array section assumes the
12543 // format of an array subscript if no colon is used.
12544 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012545 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012546 return ATy->getSize().getSExtValue() != 1;
12547 // Size can't be evaluated statically.
12548 return false;
12549 }
12550
12551 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012552 const Expr *LowerBound = OASE->getLowerBound();
12553 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012554
12555 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012556 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012557 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012558 Expr::EvalResult Result;
12559 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012560 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012561
12562 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012563 if (ConstLowerBound.getSExtValue())
12564 return true;
12565 }
12566
12567 // If we don't have a length we covering the whole dimension.
12568 if (!Length)
12569 return false;
12570
12571 // If the base is a pointer, we don't have a way to get the size of the
12572 // pointee.
12573 if (BaseQTy->isPointerType())
12574 return false;
12575
12576 // We can only check if the length is the same as the size of the dimension
12577 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012578 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012579 if (!CATy)
12580 return false;
12581
Fangrui Song407659a2018-11-30 23:41:18 +000012582 Expr::EvalResult Result;
12583 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012584 return false; // Can't get the integer value as a constant.
12585
Fangrui Song407659a2018-11-30 23:41:18 +000012586 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012587 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12588}
12589
12590// Return true if it can be proven that the provided array expression (array
12591// section or array subscript) does NOT specify a single element of the array
12592// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012593static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012594 const Expr *E,
12595 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012596 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012597
12598 // An array subscript always refer to a single element. Also, an array section
12599 // assumes the format of an array subscript if no colon is used.
12600 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12601 return false;
12602
12603 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012604 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012605
12606 // If we don't have a length we have to check if the array has unitary size
12607 // for this dimension. Also, we should always expect a length if the base type
12608 // is pointer.
12609 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012610 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012611 return ATy->getSize().getSExtValue() != 1;
12612 // We cannot assume anything.
12613 return false;
12614 }
12615
12616 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012617 Expr::EvalResult Result;
12618 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012619 return false; // Can't get the integer value as a constant.
12620
Fangrui Song407659a2018-11-30 23:41:18 +000012621 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012622 return ConstLength.getSExtValue() != 1;
12623}
12624
Samuel Antao661c0902016-05-26 17:39:58 +000012625// Return the expression of the base of the mappable expression or null if it
12626// cannot be determined and do all the necessary checks to see if the expression
12627// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012628// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012629static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012630 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012631 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012632 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012633 SourceLocation ELoc = E->getExprLoc();
12634 SourceRange ERange = E->getSourceRange();
12635
12636 // The base of elements of list in a map clause have to be either:
12637 // - a reference to variable or field.
12638 // - a member expression.
12639 // - an array expression.
12640 //
12641 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12642 // reference to 'r'.
12643 //
12644 // If we have:
12645 //
12646 // struct SS {
12647 // Bla S;
12648 // foo() {
12649 // #pragma omp target map (S.Arr[:12]);
12650 // }
12651 // }
12652 //
12653 // We want to retrieve the member expression 'this->S';
12654
Alexey Bataeve3727102018-04-18 15:57:46 +000012655 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012656
Samuel Antao5de996e2016-01-22 20:21:36 +000012657 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12658 // If a list item is an array section, it must specify contiguous storage.
12659 //
12660 // For this restriction it is sufficient that we make sure only references
12661 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012662 // exist except in the rightmost expression (unless they cover the whole
12663 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012664 //
12665 // r.ArrS[3:5].Arr[6:7]
12666 //
12667 // r.ArrS[3:5].x
12668 //
12669 // but these would be valid:
12670 // r.ArrS[3].Arr[6:7]
12671 //
12672 // r.ArrS[3].x
12673
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012674 bool AllowUnitySizeArraySection = true;
12675 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012676
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012677 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012678 E = E->IgnoreParenImpCasts();
12679
12680 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12681 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012682 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012683
12684 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012685
12686 // If we got a reference to a declaration, we should not expect any array
12687 // section before that.
12688 AllowUnitySizeArraySection = false;
12689 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012690
12691 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012692 CurComponents.emplace_back(CurE, CurE->getDecl());
12693 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012694 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012695
12696 if (isa<CXXThisExpr>(BaseE))
12697 // We found a base expression: this->Val.
12698 RelevantExpr = CurE;
12699 else
12700 E = BaseE;
12701
12702 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012703 if (!NoDiagnose) {
12704 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12705 << CurE->getSourceRange();
12706 return nullptr;
12707 }
12708 if (RelevantExpr)
12709 return nullptr;
12710 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012711 }
12712
12713 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12714
12715 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12716 // A bit-field cannot appear in a map clause.
12717 //
12718 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012719 if (!NoDiagnose) {
12720 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12721 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12722 return nullptr;
12723 }
12724 if (RelevantExpr)
12725 return nullptr;
12726 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012727 }
12728
12729 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12730 // If the type of a list item is a reference to a type T then the type
12731 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012732 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012733
12734 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12735 // A list item cannot be a variable that is a member of a structure with
12736 // a union type.
12737 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012738 if (CurType->isUnionType()) {
12739 if (!NoDiagnose) {
12740 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12741 << CurE->getSourceRange();
12742 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012743 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012744 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012745 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012746
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012747 // If we got a member expression, we should not expect any array section
12748 // before that:
12749 //
12750 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12751 // If a list item is an element of a structure, only the rightmost symbol
12752 // of the variable reference can be an array section.
12753 //
12754 AllowUnitySizeArraySection = false;
12755 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012756
12757 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012758 CurComponents.emplace_back(CurE, FD);
12759 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012760 E = CurE->getBase()->IgnoreParenImpCasts();
12761
12762 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012763 if (!NoDiagnose) {
12764 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12765 << 0 << CurE->getSourceRange();
12766 return nullptr;
12767 }
12768 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012769 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012770
12771 // If we got an array subscript that express the whole dimension we
12772 // can have any array expressions before. If it only expressing part of
12773 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012774 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012775 E->getType()))
12776 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012777
Patrick Lystere13b1e32019-01-02 19:28:48 +000012778 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12779 Expr::EvalResult Result;
12780 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12781 if (!Result.Val.getInt().isNullValue()) {
12782 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12783 diag::err_omp_invalid_map_this_expr);
12784 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12785 diag::note_omp_invalid_subscript_on_this_ptr_map);
12786 }
12787 }
12788 RelevantExpr = TE;
12789 }
12790
Samuel Antao90927002016-04-26 14:54:23 +000012791 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012792 CurComponents.emplace_back(CurE, nullptr);
12793 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012794 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000012795 E = CurE->getBase()->IgnoreParenImpCasts();
12796
Alexey Bataev27041fa2017-12-05 15:22:49 +000012797 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012798 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12799
Samuel Antao5de996e2016-01-22 20:21:36 +000012800 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12801 // If the type of a list item is a reference to a type T then the type
12802 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000012803 if (CurType->isReferenceType())
12804 CurType = CurType->getPointeeType();
12805
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012806 bool IsPointer = CurType->isAnyPointerType();
12807
12808 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012809 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12810 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012811 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012812 }
12813
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012814 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000012815 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012816 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000012817 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012818
Samuel Antaodab51bb2016-07-18 23:22:11 +000012819 if (AllowWholeSizeArraySection) {
12820 // Any array section is currently allowed. Allowing a whole size array
12821 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012822 //
12823 // If this array section refers to the whole dimension we can still
12824 // accept other array sections before this one, except if the base is a
12825 // pointer. Otherwise, only unitary sections are accepted.
12826 if (NotWhole || IsPointer)
12827 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000012828 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012829 // A unity or whole array section is not allowed and that is not
12830 // compatible with the properties of the current array section.
12831 SemaRef.Diag(
12832 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12833 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012834 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012835 }
Samuel Antao90927002016-04-26 14:54:23 +000012836
Patrick Lystere13b1e32019-01-02 19:28:48 +000012837 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12838 Expr::EvalResult ResultR;
12839 Expr::EvalResult ResultL;
12840 if (CurE->getLength()->EvaluateAsInt(ResultR,
12841 SemaRef.getASTContext())) {
12842 if (!ResultR.Val.getInt().isOneValue()) {
12843 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12844 diag::err_omp_invalid_map_this_expr);
12845 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12846 diag::note_omp_invalid_length_on_this_ptr_mapping);
12847 }
12848 }
12849 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
12850 ResultL, SemaRef.getASTContext())) {
12851 if (!ResultL.Val.getInt().isNullValue()) {
12852 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12853 diag::err_omp_invalid_map_this_expr);
12854 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12855 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
12856 }
12857 }
12858 RelevantExpr = TE;
12859 }
12860
Samuel Antao90927002016-04-26 14:54:23 +000012861 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012862 CurComponents.emplace_back(CurE, nullptr);
12863 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012864 if (!NoDiagnose) {
12865 // If nothing else worked, this is not a valid map clause expression.
12866 SemaRef.Diag(
12867 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12868 << ERange;
12869 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000012870 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012871 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012872 }
12873
12874 return RelevantExpr;
12875}
12876
12877// Return true if expression E associated with value VD has conflicts with other
12878// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000012879static bool checkMapConflicts(
12880 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000012881 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000012882 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12883 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012884 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000012885 SourceLocation ELoc = E->getExprLoc();
12886 SourceRange ERange = E->getSourceRange();
12887
12888 // In order to easily check the conflicts we need to match each component of
12889 // the expression under test with the components of the expressions that are
12890 // already in the stack.
12891
Samuel Antao5de996e2016-01-22 20:21:36 +000012892 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012893 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012894 "Map clause expression with unexpected base!");
12895
12896 // Variables to help detecting enclosing problems in data environment nests.
12897 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000012898 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012899
Samuel Antao90927002016-04-26 14:54:23 +000012900 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12901 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000012902 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12903 ERange, CKind, &EnclosingExpr,
12904 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12905 StackComponents,
12906 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012907 assert(!StackComponents.empty() &&
12908 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012909 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012910 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000012911 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012912
Samuel Antao90927002016-04-26 14:54:23 +000012913 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000012914 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000012915
Samuel Antao5de996e2016-01-22 20:21:36 +000012916 // Expressions must start from the same base. Here we detect at which
12917 // point both expressions diverge from each other and see if we can
12918 // detect if the memory referred to both expressions is contiguous and
12919 // do not overlap.
12920 auto CI = CurComponents.rbegin();
12921 auto CE = CurComponents.rend();
12922 auto SI = StackComponents.rbegin();
12923 auto SE = StackComponents.rend();
12924 for (; CI != CE && SI != SE; ++CI, ++SI) {
12925
12926 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12927 // At most one list item can be an array item derived from a given
12928 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000012929 if (CurrentRegionOnly &&
12930 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12931 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12932 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12933 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12934 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000012935 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000012936 << CI->getAssociatedExpression()->getSourceRange();
12937 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12938 diag::note_used_here)
12939 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000012940 return true;
12941 }
12942
12943 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000012944 if (CI->getAssociatedExpression()->getStmtClass() !=
12945 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000012946 break;
12947
12948 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000012949 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000012950 break;
12951 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000012952 // Check if the extra components of the expressions in the enclosing
12953 // data environment are redundant for the current base declaration.
12954 // If they are, the maps completely overlap, which is legal.
12955 for (; SI != SE; ++SI) {
12956 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000012957 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000012958 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012959 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012960 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000012961 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012962 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000012963 Type =
12964 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12965 }
12966 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012967 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000012968 SemaRef, SI->getAssociatedExpression(), Type))
12969 break;
12970 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012971
12972 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12973 // List items of map clauses in the same construct must not share
12974 // original storage.
12975 //
12976 // If the expressions are exactly the same or one is a subset of the
12977 // other, it means they are sharing storage.
12978 if (CI == CE && SI == SE) {
12979 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012980 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000012981 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012982 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012983 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012984 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12985 << ERange;
12986 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012987 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12988 << RE->getSourceRange();
12989 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012990 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012991 // If we find the same expression in the enclosing data environment,
12992 // that is legal.
12993 IsEnclosedByDataEnvironmentExpr = true;
12994 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000012995 }
12996
Samuel Antao90927002016-04-26 14:54:23 +000012997 QualType DerivedType =
12998 std::prev(CI)->getAssociatedDeclaration()->getType();
12999 SourceLocation DerivedLoc =
13000 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013001
13002 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13003 // If the type of a list item is a reference to a type T then the type
13004 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013005 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013006
13007 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13008 // A variable for which the type is pointer and an array section
13009 // derived from that variable must not appear as list items of map
13010 // clauses of the same construct.
13011 //
13012 // Also, cover one of the cases in:
13013 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13014 // If any part of the original storage of a list item has corresponding
13015 // storage in the device data environment, all of the original storage
13016 // must have corresponding storage in the device data environment.
13017 //
13018 if (DerivedType->isAnyPointerType()) {
13019 if (CI == CE || SI == SE) {
13020 SemaRef.Diag(
13021 DerivedLoc,
13022 diag::err_omp_pointer_mapped_along_with_derived_section)
13023 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013024 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13025 << RE->getSourceRange();
13026 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013027 }
13028 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013029 SI->getAssociatedExpression()->getStmtClass() ||
13030 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13031 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013032 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013033 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013034 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013035 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13036 << RE->getSourceRange();
13037 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013038 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013039 }
13040
13041 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13042 // List items of map clauses in the same construct must not share
13043 // original storage.
13044 //
13045 // An expression is a subset of the other.
13046 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013047 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013048 if (CI != CE || SI != SE) {
13049 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13050 // a pointer.
13051 auto Begin =
13052 CI != CE ? CurComponents.begin() : StackComponents.begin();
13053 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13054 auto It = Begin;
13055 while (It != End && !It->getAssociatedDeclaration())
13056 std::advance(It, 1);
13057 assert(It != End &&
13058 "Expected at least one component with the declaration.");
13059 if (It != Begin && It->getAssociatedDeclaration()
13060 ->getType()
13061 .getCanonicalType()
13062 ->isAnyPointerType()) {
13063 IsEnclosedByDataEnvironmentExpr = false;
13064 EnclosingExpr = nullptr;
13065 return false;
13066 }
13067 }
Samuel Antao661c0902016-05-26 17:39:58 +000013068 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013069 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013070 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013071 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13072 << ERange;
13073 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013074 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13075 << RE->getSourceRange();
13076 return true;
13077 }
13078
13079 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013080 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013081 if (!CurrentRegionOnly && SI != SE)
13082 EnclosingExpr = RE;
13083
13084 // The current expression is a subset of the expression in the data
13085 // environment.
13086 IsEnclosedByDataEnvironmentExpr |=
13087 (!CurrentRegionOnly && CI != CE && SI == SE);
13088
13089 return false;
13090 });
13091
13092 if (CurrentRegionOnly)
13093 return FoundError;
13094
13095 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13096 // If any part of the original storage of a list item has corresponding
13097 // storage in the device data environment, all of the original storage must
13098 // have corresponding storage in the device data environment.
13099 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13100 // If a list item is an element of a structure, and a different element of
13101 // the structure has a corresponding list item in the device data environment
13102 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013103 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013104 // data environment prior to the task encountering the construct.
13105 //
13106 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13107 SemaRef.Diag(ELoc,
13108 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13109 << ERange;
13110 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13111 << EnclosingExpr->getSourceRange();
13112 return true;
13113 }
13114
13115 return FoundError;
13116}
13117
Michael Kruse4304e9d2019-02-19 16:38:20 +000013118// Look up the user-defined mapper given the mapper name and mapped type, and
13119// build a reference to it.
13120ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13121 CXXScopeSpec &MapperIdScopeSpec,
13122 const DeclarationNameInfo &MapperId,
13123 QualType Type, Expr *UnresolvedMapper) {
13124 if (MapperIdScopeSpec.isInvalid())
13125 return ExprError();
13126 // Find all user-defined mappers with the given MapperId.
13127 SmallVector<UnresolvedSet<8>, 4> Lookups;
13128 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13129 Lookup.suppressDiagnostics();
13130 if (S) {
13131 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13132 NamedDecl *D = Lookup.getRepresentativeDecl();
13133 while (S && !S->isDeclScope(D))
13134 S = S->getParent();
13135 if (S)
13136 S = S->getParent();
13137 Lookups.emplace_back();
13138 Lookups.back().append(Lookup.begin(), Lookup.end());
13139 Lookup.clear();
13140 }
13141 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13142 // Extract the user-defined mappers with the given MapperId.
13143 Lookups.push_back(UnresolvedSet<8>());
13144 for (NamedDecl *D : ULE->decls()) {
13145 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13146 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13147 Lookups.back().addDecl(DMD);
13148 }
13149 }
13150 // Defer the lookup for dependent types. The results will be passed through
13151 // UnresolvedMapper on instantiation.
13152 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13153 Type->isInstantiationDependentType() ||
13154 Type->containsUnexpandedParameterPack() ||
13155 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13156 return !D->isInvalidDecl() &&
13157 (D->getType()->isDependentType() ||
13158 D->getType()->isInstantiationDependentType() ||
13159 D->getType()->containsUnexpandedParameterPack());
13160 })) {
13161 UnresolvedSet<8> URS;
13162 for (const UnresolvedSet<8> &Set : Lookups) {
13163 if (Set.empty())
13164 continue;
13165 URS.append(Set.begin(), Set.end());
13166 }
13167 return UnresolvedLookupExpr::Create(
13168 SemaRef.Context, /*NamingClass=*/nullptr,
13169 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13170 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13171 }
13172 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13173 // The type must be of struct, union or class type in C and C++
13174 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13175 return ExprEmpty();
13176 SourceLocation Loc = MapperId.getLoc();
13177 // Perform argument dependent lookup.
13178 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13179 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13180 // Return the first user-defined mapper with the desired type.
13181 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13182 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13183 if (!D->isInvalidDecl() &&
13184 SemaRef.Context.hasSameType(D->getType(), Type))
13185 return D;
13186 return nullptr;
13187 }))
13188 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13189 // Find the first user-defined mapper with a type derived from the desired
13190 // type.
13191 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13192 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13193 if (!D->isInvalidDecl() &&
13194 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13195 !Type.isMoreQualifiedThan(D->getType()))
13196 return D;
13197 return nullptr;
13198 })) {
13199 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13200 /*DetectVirtual=*/false);
13201 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13202 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13203 VD->getType().getUnqualifiedType()))) {
13204 if (SemaRef.CheckBaseClassAccess(
13205 Loc, VD->getType(), Type, Paths.front(),
13206 /*DiagID=*/0) != Sema::AR_inaccessible) {
13207 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13208 }
13209 }
13210 }
13211 }
13212 // Report error if a mapper is specified, but cannot be found.
13213 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13214 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13215 << Type << MapperId.getName();
13216 return ExprError();
13217 }
13218 return ExprEmpty();
13219}
13220
Samuel Antao661c0902016-05-26 17:39:58 +000013221namespace {
13222// Utility struct that gathers all the related lists associated with a mappable
13223// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013224struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013225 // The list of expressions.
13226 ArrayRef<Expr *> VarList;
13227 // The list of processed expressions.
13228 SmallVector<Expr *, 16> ProcessedVarList;
13229 // The mappble components for each expression.
13230 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13231 // The base declaration of the variable.
13232 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013233 // The reference to the user-defined mapper associated with every expression.
13234 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013235
13236 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13237 // We have a list of components and base declarations for each entry in the
13238 // variable list.
13239 VarComponents.reserve(VarList.size());
13240 VarBaseDeclarations.reserve(VarList.size());
13241 }
13242};
13243}
13244
13245// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013246// \a CKind. In the check process the valid expressions, mappable expression
13247// components, variables, and user-defined mappers are extracted and used to
13248// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13249// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13250// and \a MapperId are expected to be valid if the clause kind is 'map'.
13251static void checkMappableExpressionList(
13252 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13253 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013254 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13255 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013256 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013257 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013258 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13259 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013260 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013261
13262 // If the identifier of user-defined mapper is not specified, it is "default".
13263 // We do not change the actual name in this clause to distinguish whether a
13264 // mapper is specified explicitly, i.e., it is not explicitly specified when
13265 // MapperId.getName() is empty.
13266 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13267 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13268 MapperId.setName(DeclNames.getIdentifier(
13269 &SemaRef.getASTContext().Idents.get("default")));
13270 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013271
13272 // Iterators to find the current unresolved mapper expression.
13273 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13274 bool UpdateUMIt = false;
13275 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013276
Samuel Antao90927002016-04-26 14:54:23 +000013277 // Keep track of the mappable components and base declarations in this clause.
13278 // Each entry in the list is going to have a list of components associated. We
13279 // record each set of the components so that we can build the clause later on.
13280 // In the end we should have the same amount of declarations and component
13281 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013282
Alexey Bataeve3727102018-04-18 15:57:46 +000013283 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013284 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013285 SourceLocation ELoc = RE->getExprLoc();
13286
Michael Kruse4304e9d2019-02-19 16:38:20 +000013287 // Find the current unresolved mapper expression.
13288 if (UpdateUMIt && UMIt != UMEnd) {
13289 UMIt++;
13290 assert(
13291 UMIt != UMEnd &&
13292 "Expect the size of UnresolvedMappers to match with that of VarList");
13293 }
13294 UpdateUMIt = true;
13295 if (UMIt != UMEnd)
13296 UnresolvedMapper = *UMIt;
13297
Alexey Bataeve3727102018-04-18 15:57:46 +000013298 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013299
13300 if (VE->isValueDependent() || VE->isTypeDependent() ||
13301 VE->isInstantiationDependent() ||
13302 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013303 // Try to find the associated user-defined mapper.
13304 ExprResult ER = buildUserDefinedMapperRef(
13305 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13306 VE->getType().getCanonicalType(), UnresolvedMapper);
13307 if (ER.isInvalid())
13308 continue;
13309 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013310 // We can only analyze this information once the missing information is
13311 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013312 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013313 continue;
13314 }
13315
Alexey Bataeve3727102018-04-18 15:57:46 +000013316 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013317
Samuel Antao5de996e2016-01-22 20:21:36 +000013318 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013319 SemaRef.Diag(ELoc,
13320 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013321 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013322 continue;
13323 }
13324
Samuel Antao90927002016-04-26 14:54:23 +000013325 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13326 ValueDecl *CurDeclaration = nullptr;
13327
13328 // Obtain the array or member expression bases if required. Also, fill the
13329 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013330 const Expr *BE = checkMapClauseExpressionBase(
13331 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013332 if (!BE)
13333 continue;
13334
Samuel Antao90927002016-04-26 14:54:23 +000013335 assert(!CurComponents.empty() &&
13336 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013337
Patrick Lystere13b1e32019-01-02 19:28:48 +000013338 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13339 // Add store "this" pointer to class in DSAStackTy for future checking
13340 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013341 // Try to find the associated user-defined mapper.
13342 ExprResult ER = buildUserDefinedMapperRef(
13343 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13344 VE->getType().getCanonicalType(), UnresolvedMapper);
13345 if (ER.isInvalid())
13346 continue;
13347 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013348 // Skip restriction checking for variable or field declarations
13349 MVLI.ProcessedVarList.push_back(RE);
13350 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13351 MVLI.VarComponents.back().append(CurComponents.begin(),
13352 CurComponents.end());
13353 MVLI.VarBaseDeclarations.push_back(nullptr);
13354 continue;
13355 }
13356
Samuel Antao90927002016-04-26 14:54:23 +000013357 // For the following checks, we rely on the base declaration which is
13358 // expected to be associated with the last component. The declaration is
13359 // expected to be a variable or a field (if 'this' is being mapped).
13360 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13361 assert(CurDeclaration && "Null decl on map clause.");
13362 assert(
13363 CurDeclaration->isCanonicalDecl() &&
13364 "Expecting components to have associated only canonical declarations.");
13365
13366 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013367 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013368
13369 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013370 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013371
13372 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013373 // threadprivate variables cannot appear in a map clause.
13374 // OpenMP 4.5 [2.10.5, target update Construct]
13375 // threadprivate variables cannot appear in a from clause.
13376 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013377 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013378 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13379 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013380 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013381 continue;
13382 }
13383
Samuel Antao5de996e2016-01-22 20:21:36 +000013384 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13385 // A list item cannot appear in both a map clause and a data-sharing
13386 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013387
Samuel Antao5de996e2016-01-22 20:21:36 +000013388 // Check conflicts with other map clause expressions. We check the conflicts
13389 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013390 // environment, because the restrictions are different. We only have to
13391 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013392 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013393 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013394 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013395 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013396 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013397 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013398 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013399
Samuel Antao661c0902016-05-26 17:39:58 +000013400 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013401 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13402 // If the type of a list item is a reference to a type T then the type will
13403 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013404 auto I = llvm::find_if(
13405 CurComponents,
13406 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13407 return MC.getAssociatedDeclaration();
13408 });
13409 assert(I != CurComponents.end() && "Null decl on map clause.");
13410 QualType Type =
13411 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013412
Samuel Antao661c0902016-05-26 17:39:58 +000013413 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13414 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013415 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013416 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013417 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013418 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013419 continue;
13420
Samuel Antao661c0902016-05-26 17:39:58 +000013421 if (CKind == OMPC_map) {
13422 // target enter data
13423 // OpenMP [2.10.2, Restrictions, p. 99]
13424 // A map-type must be specified in all map clauses and must be either
13425 // to or alloc.
13426 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13427 if (DKind == OMPD_target_enter_data &&
13428 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13429 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13430 << (IsMapTypeImplicit ? 1 : 0)
13431 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13432 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013433 continue;
13434 }
Samuel Antao661c0902016-05-26 17:39:58 +000013435
13436 // target exit_data
13437 // OpenMP [2.10.3, Restrictions, p. 102]
13438 // A map-type must be specified in all map clauses and must be either
13439 // from, release, or delete.
13440 if (DKind == OMPD_target_exit_data &&
13441 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13442 MapType == OMPC_MAP_delete)) {
13443 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13444 << (IsMapTypeImplicit ? 1 : 0)
13445 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13446 << getOpenMPDirectiveName(DKind);
13447 continue;
13448 }
13449
13450 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13451 // A list item cannot appear in both a map clause and a data-sharing
13452 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013453 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13454 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013455 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013456 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013457 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013458 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013459 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013460 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013461 continue;
13462 }
13463 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013464 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013465
Michael Kruse01f670d2019-02-22 22:29:42 +000013466 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013467 ExprResult ER = buildUserDefinedMapperRef(
13468 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13469 Type.getCanonicalType(), UnresolvedMapper);
13470 if (ER.isInvalid())
13471 continue;
13472 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013473
Samuel Antao90927002016-04-26 14:54:23 +000013474 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013475 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013476
13477 // Store the components in the stack so that they can be used to check
13478 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013479 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13480 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013481
13482 // Save the components and declaration to create the clause. For purposes of
13483 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013484 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013485 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13486 MVLI.VarComponents.back().append(CurComponents.begin(),
13487 CurComponents.end());
13488 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13489 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013490 }
Samuel Antao661c0902016-05-26 17:39:58 +000013491}
13492
Michael Kruse4304e9d2019-02-19 16:38:20 +000013493OMPClause *Sema::ActOnOpenMPMapClause(
13494 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13495 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13496 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13497 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13498 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13499 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13500 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13501 OMPC_MAP_MODIFIER_unknown,
13502 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013503 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13504
13505 // Process map-type-modifiers, flag errors for duplicate modifiers.
13506 unsigned Count = 0;
13507 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13508 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13509 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13510 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13511 continue;
13512 }
13513 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013514 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013515 Modifiers[Count] = MapTypeModifiers[I];
13516 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13517 ++Count;
13518 }
13519
Michael Kruse4304e9d2019-02-19 16:38:20 +000013520 MappableVarListInfo MVLI(VarList);
13521 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013522 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13523 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013524
Samuel Antao5de996e2016-01-22 20:21:36 +000013525 // We need to produce a map clause even if we don't have variables so that
13526 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013527 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13528 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13529 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13530 MapperIdScopeSpec.getWithLocInContext(Context),
13531 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013532}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013533
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013534QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13535 TypeResult ParsedType) {
13536 assert(ParsedType.isUsable());
13537
13538 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13539 if (ReductionType.isNull())
13540 return QualType();
13541
13542 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13543 // A type name in a declare reduction directive cannot be a function type, an
13544 // array type, a reference type, or a type qualified with const, volatile or
13545 // restrict.
13546 if (ReductionType.hasQualifiers()) {
13547 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13548 return QualType();
13549 }
13550
13551 if (ReductionType->isFunctionType()) {
13552 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13553 return QualType();
13554 }
13555 if (ReductionType->isReferenceType()) {
13556 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13557 return QualType();
13558 }
13559 if (ReductionType->isArrayType()) {
13560 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13561 return QualType();
13562 }
13563 return ReductionType;
13564}
13565
13566Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13567 Scope *S, DeclContext *DC, DeclarationName Name,
13568 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13569 AccessSpecifier AS, Decl *PrevDeclInScope) {
13570 SmallVector<Decl *, 8> Decls;
13571 Decls.reserve(ReductionTypes.size());
13572
13573 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013574 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013575 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13576 // A reduction-identifier may not be re-declared in the current scope for the
13577 // same type or for a type that is compatible according to the base language
13578 // rules.
13579 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13580 OMPDeclareReductionDecl *PrevDRD = nullptr;
13581 bool InCompoundScope = true;
13582 if (S != nullptr) {
13583 // Find previous declaration with the same name not referenced in other
13584 // declarations.
13585 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13586 InCompoundScope =
13587 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13588 LookupName(Lookup, S);
13589 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13590 /*AllowInlineNamespace=*/false);
13591 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013592 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013593 while (Filter.hasNext()) {
13594 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13595 if (InCompoundScope) {
13596 auto I = UsedAsPrevious.find(PrevDecl);
13597 if (I == UsedAsPrevious.end())
13598 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013599 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013600 UsedAsPrevious[D] = true;
13601 }
13602 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13603 PrevDecl->getLocation();
13604 }
13605 Filter.done();
13606 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013607 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013608 if (!PrevData.second) {
13609 PrevDRD = PrevData.first;
13610 break;
13611 }
13612 }
13613 }
13614 } else if (PrevDeclInScope != nullptr) {
13615 auto *PrevDRDInScope = PrevDRD =
13616 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13617 do {
13618 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13619 PrevDRDInScope->getLocation();
13620 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13621 } while (PrevDRDInScope != nullptr);
13622 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013623 for (const auto &TyData : ReductionTypes) {
13624 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013625 bool Invalid = false;
13626 if (I != PreviousRedeclTypes.end()) {
13627 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13628 << TyData.first;
13629 Diag(I->second, diag::note_previous_definition);
13630 Invalid = true;
13631 }
13632 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13633 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13634 Name, TyData.first, PrevDRD);
13635 DC->addDecl(DRD);
13636 DRD->setAccess(AS);
13637 Decls.push_back(DRD);
13638 if (Invalid)
13639 DRD->setInvalidDecl();
13640 else
13641 PrevDRD = DRD;
13642 }
13643
13644 return DeclGroupPtrTy::make(
13645 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13646}
13647
13648void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13649 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13650
13651 // Enter new function scope.
13652 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013653 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013654 getCurFunction()->setHasOMPDeclareReductionCombiner();
13655
13656 if (S != nullptr)
13657 PushDeclContext(S, DRD);
13658 else
13659 CurContext = DRD;
13660
Faisal Valid143a0c2017-04-01 21:30:49 +000013661 PushExpressionEvaluationContext(
13662 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013663
13664 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013665 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13666 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13667 // uses semantics of argument handles by value, but it should be passed by
13668 // reference. C lang does not support references, so pass all parameters as
13669 // pointers.
13670 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013671 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013672 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013673 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13674 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13675 // uses semantics of argument handles by value, but it should be passed by
13676 // reference. C lang does not support references, so pass all parameters as
13677 // pointers.
13678 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013679 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013680 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13681 if (S != nullptr) {
13682 PushOnScopeChains(OmpInParm, S);
13683 PushOnScopeChains(OmpOutParm, S);
13684 } else {
13685 DRD->addDecl(OmpInParm);
13686 DRD->addDecl(OmpOutParm);
13687 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013688 Expr *InE =
13689 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13690 Expr *OutE =
13691 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13692 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013693}
13694
13695void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13696 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13697 DiscardCleanupsInEvaluationContext();
13698 PopExpressionEvaluationContext();
13699
13700 PopDeclContext();
13701 PopFunctionScopeInfo();
13702
13703 if (Combiner != nullptr)
13704 DRD->setCombiner(Combiner);
13705 else
13706 DRD->setInvalidDecl();
13707}
13708
Alexey Bataev070f43a2017-09-06 14:49:58 +000013709VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013710 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13711
13712 // Enter new function scope.
13713 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013714 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013715
13716 if (S != nullptr)
13717 PushDeclContext(S, DRD);
13718 else
13719 CurContext = DRD;
13720
Faisal Valid143a0c2017-04-01 21:30:49 +000013721 PushExpressionEvaluationContext(
13722 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013723
13724 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013725 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13726 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13727 // uses semantics of argument handles by value, but it should be passed by
13728 // reference. C lang does not support references, so pass all parameters as
13729 // pointers.
13730 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013731 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013732 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013733 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13734 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13735 // uses semantics of argument handles by value, but it should be passed by
13736 // reference. C lang does not support references, so pass all parameters as
13737 // pointers.
13738 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013739 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013740 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013741 if (S != nullptr) {
13742 PushOnScopeChains(OmpPrivParm, S);
13743 PushOnScopeChains(OmpOrigParm, S);
13744 } else {
13745 DRD->addDecl(OmpPrivParm);
13746 DRD->addDecl(OmpOrigParm);
13747 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013748 Expr *OrigE =
13749 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13750 Expr *PrivE =
13751 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13752 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013753 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013754}
13755
Alexey Bataev070f43a2017-09-06 14:49:58 +000013756void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13757 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013758 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13759 DiscardCleanupsInEvaluationContext();
13760 PopExpressionEvaluationContext();
13761
13762 PopDeclContext();
13763 PopFunctionScopeInfo();
13764
Alexey Bataev070f43a2017-09-06 14:49:58 +000013765 if (Initializer != nullptr) {
13766 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13767 } else if (OmpPrivParm->hasInit()) {
13768 DRD->setInitializer(OmpPrivParm->getInit(),
13769 OmpPrivParm->isDirectInit()
13770 ? OMPDeclareReductionDecl::DirectInit
13771 : OMPDeclareReductionDecl::CopyInit);
13772 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013773 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013774 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013775}
13776
13777Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13778 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013779 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013780 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013781 if (S)
13782 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13783 /*AddToContext=*/false);
13784 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013785 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013786 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013787 }
13788 return DeclReductions;
13789}
13790
Michael Kruse251e1482019-02-01 20:25:04 +000013791TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13792 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13793 QualType T = TInfo->getType();
13794 if (D.isInvalidType())
13795 return true;
13796
13797 if (getLangOpts().CPlusPlus) {
13798 // Check that there are no default arguments (C++ only).
13799 CheckExtraCXXDefaultArguments(D);
13800 }
13801
13802 return CreateParsedType(T, TInfo);
13803}
13804
13805QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
13806 TypeResult ParsedType) {
13807 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
13808
13809 QualType MapperType = GetTypeFromParser(ParsedType.get());
13810 assert(!MapperType.isNull() && "Expect valid mapper type");
13811
13812 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13813 // The type must be of struct, union or class type in C and C++
13814 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
13815 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
13816 return QualType();
13817 }
13818 return MapperType;
13819}
13820
13821OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
13822 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
13823 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
13824 Decl *PrevDeclInScope) {
13825 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
13826 forRedeclarationInCurContext());
13827 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13828 // A mapper-identifier may not be redeclared in the current scope for the
13829 // same type or for a type that is compatible according to the base language
13830 // rules.
13831 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13832 OMPDeclareMapperDecl *PrevDMD = nullptr;
13833 bool InCompoundScope = true;
13834 if (S != nullptr) {
13835 // Find previous declaration with the same name not referenced in other
13836 // declarations.
13837 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13838 InCompoundScope =
13839 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13840 LookupName(Lookup, S);
13841 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13842 /*AllowInlineNamespace=*/false);
13843 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
13844 LookupResult::Filter Filter = Lookup.makeFilter();
13845 while (Filter.hasNext()) {
13846 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
13847 if (InCompoundScope) {
13848 auto I = UsedAsPrevious.find(PrevDecl);
13849 if (I == UsedAsPrevious.end())
13850 UsedAsPrevious[PrevDecl] = false;
13851 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
13852 UsedAsPrevious[D] = true;
13853 }
13854 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13855 PrevDecl->getLocation();
13856 }
13857 Filter.done();
13858 if (InCompoundScope) {
13859 for (const auto &PrevData : UsedAsPrevious) {
13860 if (!PrevData.second) {
13861 PrevDMD = PrevData.first;
13862 break;
13863 }
13864 }
13865 }
13866 } else if (PrevDeclInScope) {
13867 auto *PrevDMDInScope = PrevDMD =
13868 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
13869 do {
13870 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
13871 PrevDMDInScope->getLocation();
13872 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
13873 } while (PrevDMDInScope != nullptr);
13874 }
13875 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
13876 bool Invalid = false;
13877 if (I != PreviousRedeclTypes.end()) {
13878 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
13879 << MapperType << Name;
13880 Diag(I->second, diag::note_previous_definition);
13881 Invalid = true;
13882 }
13883 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
13884 MapperType, VN, PrevDMD);
13885 DC->addDecl(DMD);
13886 DMD->setAccess(AS);
13887 if (Invalid)
13888 DMD->setInvalidDecl();
13889
13890 // Enter new function scope.
13891 PushFunctionScope();
13892 setFunctionHasBranchProtectedScope();
13893
13894 CurContext = DMD;
13895
13896 return DMD;
13897}
13898
13899void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
13900 Scope *S,
13901 QualType MapperType,
13902 SourceLocation StartLoc,
13903 DeclarationName VN) {
13904 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
13905 if (S)
13906 PushOnScopeChains(VD, S);
13907 else
13908 DMD->addDecl(VD);
13909 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
13910 DMD->setMapperVarRef(MapperVarRefExpr);
13911}
13912
13913Sema::DeclGroupPtrTy
13914Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
13915 ArrayRef<OMPClause *> ClauseList) {
13916 PopDeclContext();
13917 PopFunctionScopeInfo();
13918
13919 if (D) {
13920 if (S)
13921 PushOnScopeChains(D, S, /*AddToContext=*/false);
13922 D->CreateClauses(Context, ClauseList);
13923 }
13924
13925 return DeclGroupPtrTy::make(DeclGroupRef(D));
13926}
13927
David Majnemer9d168222016-08-05 17:44:54 +000013928OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000013929 SourceLocation StartLoc,
13930 SourceLocation LParenLoc,
13931 SourceLocation EndLoc) {
13932 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013933 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013934
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013935 // OpenMP [teams Constrcut, Restrictions]
13936 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013937 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000013938 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013939 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013940
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013941 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013942 OpenMPDirectiveKind CaptureRegion =
13943 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13944 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013945 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013946 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013947 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13948 HelperValStmt = buildPreInits(Context, Captures);
13949 }
13950
13951 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13952 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000013953}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013954
13955OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13956 SourceLocation StartLoc,
13957 SourceLocation LParenLoc,
13958 SourceLocation EndLoc) {
13959 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013960 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013961
13962 // OpenMP [teams Constrcut, Restrictions]
13963 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013964 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000013965 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013966 return nullptr;
13967
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013968 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013969 OpenMPDirectiveKind CaptureRegion =
13970 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13971 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013972 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013973 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013974 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13975 HelperValStmt = buildPreInits(Context, Captures);
13976 }
13977
13978 return new (Context) OMPThreadLimitClause(
13979 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013980}
Alexey Bataeva0569352015-12-01 10:17:31 +000013981
13982OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13983 SourceLocation StartLoc,
13984 SourceLocation LParenLoc,
13985 SourceLocation EndLoc) {
13986 Expr *ValExpr = Priority;
13987
13988 // OpenMP [2.9.1, task Constrcut]
13989 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013990 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000013991 /*StrictlyPositive=*/false))
13992 return nullptr;
13993
13994 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13995}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013996
13997OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13998 SourceLocation StartLoc,
13999 SourceLocation LParenLoc,
14000 SourceLocation EndLoc) {
14001 Expr *ValExpr = Grainsize;
14002
14003 // OpenMP [2.9.2, taskloop Constrcut]
14004 // The parameter of the grainsize clause must be a positive integer
14005 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014006 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014007 /*StrictlyPositive=*/true))
14008 return nullptr;
14009
14010 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14011}
Alexey Bataev382967a2015-12-08 12:06:20 +000014012
14013OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14014 SourceLocation StartLoc,
14015 SourceLocation LParenLoc,
14016 SourceLocation EndLoc) {
14017 Expr *ValExpr = NumTasks;
14018
14019 // OpenMP [2.9.2, taskloop Constrcut]
14020 // The parameter of the num_tasks clause must be a positive integer
14021 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014022 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014023 /*StrictlyPositive=*/true))
14024 return nullptr;
14025
14026 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14027}
14028
Alexey Bataev28c75412015-12-15 08:19:24 +000014029OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14030 SourceLocation LParenLoc,
14031 SourceLocation EndLoc) {
14032 // OpenMP [2.13.2, critical construct, Description]
14033 // ... where hint-expression is an integer constant expression that evaluates
14034 // to a valid lock hint.
14035 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14036 if (HintExpr.isInvalid())
14037 return nullptr;
14038 return new (Context)
14039 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14040}
14041
Carlo Bertollib4adf552016-01-15 18:50:31 +000014042OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14043 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14044 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14045 SourceLocation EndLoc) {
14046 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14047 std::string Values;
14048 Values += "'";
14049 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14050 Values += "'";
14051 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14052 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14053 return nullptr;
14054 }
14055 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014056 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014057 if (ChunkSize) {
14058 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14059 !ChunkSize->isInstantiationDependent() &&
14060 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014061 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014062 ExprResult Val =
14063 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14064 if (Val.isInvalid())
14065 return nullptr;
14066
14067 ValExpr = Val.get();
14068
14069 // OpenMP [2.7.1, Restrictions]
14070 // chunk_size must be a loop invariant integer expression with a positive
14071 // value.
14072 llvm::APSInt Result;
14073 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14074 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14075 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14076 << "dist_schedule" << ChunkSize->getSourceRange();
14077 return nullptr;
14078 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014079 } else if (getOpenMPCaptureRegionForClause(
14080 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14081 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014082 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014083 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014084 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014085 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14086 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014087 }
14088 }
14089 }
14090
14091 return new (Context)
14092 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014093 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014094}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014095
14096OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14097 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14098 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14099 SourceLocation KindLoc, SourceLocation EndLoc) {
14100 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014101 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014102 std::string Value;
14103 SourceLocation Loc;
14104 Value += "'";
14105 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14106 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014107 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014108 Loc = MLoc;
14109 } else {
14110 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014111 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014112 Loc = KindLoc;
14113 }
14114 Value += "'";
14115 Diag(Loc, diag::err_omp_unexpected_clause_value)
14116 << Value << getOpenMPClauseName(OMPC_defaultmap);
14117 return nullptr;
14118 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014119 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014120
14121 return new (Context)
14122 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14123}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014124
14125bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14126 DeclContext *CurLexicalContext = getCurLexicalContext();
14127 if (!CurLexicalContext->isFileContext() &&
14128 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014129 !CurLexicalContext->isExternCXXContext() &&
14130 !isa<CXXRecordDecl>(CurLexicalContext) &&
14131 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14132 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14133 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014134 Diag(Loc, diag::err_omp_region_not_file_context);
14135 return false;
14136 }
Kelvin Libc38e632018-09-10 02:07:09 +000014137 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014138 return true;
14139}
14140
14141void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014142 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014143 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014144 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014145}
14146
David Majnemer9d168222016-08-05 17:44:54 +000014147void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14148 CXXScopeSpec &ScopeSpec,
14149 const DeclarationNameInfo &Id,
14150 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14151 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014152 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14153 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14154
14155 if (Lookup.isAmbiguous())
14156 return;
14157 Lookup.suppressDiagnostics();
14158
14159 if (!Lookup.isSingleResult()) {
14160 if (TypoCorrection Corrected =
14161 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14162 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14163 CTK_ErrorRecovery)) {
14164 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14165 << Id.getName());
14166 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14167 return;
14168 }
14169
14170 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14171 return;
14172 }
14173
14174 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014175 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14176 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014177 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14178 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014179 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14180 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14181 cast<ValueDecl>(ND));
14182 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014183 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014184 ND->addAttr(A);
14185 if (ASTMutationListener *ML = Context.getASTMutationListener())
14186 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014187 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014188 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014189 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14190 << Id.getName();
14191 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014192 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014193 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014194 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014195}
14196
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014197static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14198 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014199 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014200 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014201 auto *VD = cast<VarDecl>(D);
14202 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14203 return;
14204 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14205 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014206}
14207
14208static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14209 Sema &SemaRef, DSAStackTy *Stack,
14210 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014211 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14212 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14213 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014214}
14215
Kelvin Li1ce87c72017-12-12 20:08:12 +000014216void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14217 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014218 if (!D || D->isInvalidDecl())
14219 return;
14220 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014221 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014222 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014223 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014224 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14225 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014226 return;
14227 // 2.10.6: threadprivate variable cannot appear in a declare target
14228 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014229 if (DSAStack->isThreadPrivate(VD)) {
14230 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014231 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014232 return;
14233 }
14234 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014235 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14236 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014237 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014238 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14239 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14240 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014241 assert(IdLoc.isValid() && "Source location is expected");
14242 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14243 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14244 return;
14245 }
14246 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014247 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14248 // Problem if any with var declared with incomplete type will be reported
14249 // as normal, so no need to check it here.
14250 if ((E || !VD->getType()->isIncompleteType()) &&
14251 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14252 return;
14253 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14254 // Checking declaration inside declare target region.
14255 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14256 isa<FunctionTemplateDecl>(D)) {
14257 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14258 Context, OMPDeclareTargetDeclAttr::MT_To);
14259 D->addAttr(A);
14260 if (ASTMutationListener *ML = Context.getASTMutationListener())
14261 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14262 }
14263 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014264 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014265 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014266 if (!E)
14267 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014268 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14269}
Samuel Antao661c0902016-05-26 17:39:58 +000014270
14271OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014272 CXXScopeSpec &MapperIdScopeSpec,
14273 DeclarationNameInfo &MapperId,
14274 const OMPVarListLocTy &Locs,
14275 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014276 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014277 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14278 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014279 if (MVLI.ProcessedVarList.empty())
14280 return nullptr;
14281
Michael Kruse01f670d2019-02-22 22:29:42 +000014282 return OMPToClause::Create(
14283 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14284 MVLI.VarComponents, MVLI.UDMapperList,
14285 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014286}
Samuel Antaoec172c62016-05-26 17:49:04 +000014287
14288OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014289 CXXScopeSpec &MapperIdScopeSpec,
14290 DeclarationNameInfo &MapperId,
14291 const OMPVarListLocTy &Locs,
14292 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014293 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014294 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14295 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014296 if (MVLI.ProcessedVarList.empty())
14297 return nullptr;
14298
Michael Kruse0336c752019-02-25 20:34:15 +000014299 return OMPFromClause::Create(
14300 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14301 MVLI.VarComponents, MVLI.UDMapperList,
14302 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014303}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014304
14305OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014306 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014307 MappableVarListInfo MVLI(VarList);
14308 SmallVector<Expr *, 8> PrivateCopies;
14309 SmallVector<Expr *, 8> Inits;
14310
Alexey Bataeve3727102018-04-18 15:57:46 +000014311 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014312 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14313 SourceLocation ELoc;
14314 SourceRange ERange;
14315 Expr *SimpleRefExpr = RefExpr;
14316 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14317 if (Res.second) {
14318 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014319 MVLI.ProcessedVarList.push_back(RefExpr);
14320 PrivateCopies.push_back(nullptr);
14321 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014322 }
14323 ValueDecl *D = Res.first;
14324 if (!D)
14325 continue;
14326
14327 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014328 Type = Type.getNonReferenceType().getUnqualifiedType();
14329
14330 auto *VD = dyn_cast<VarDecl>(D);
14331
14332 // Item should be a pointer or reference to pointer.
14333 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014334 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14335 << 0 << RefExpr->getSourceRange();
14336 continue;
14337 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014338
14339 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014340 auto VDPrivate =
14341 buildVarDecl(*this, ELoc, Type, D->getName(),
14342 D->hasAttrs() ? &D->getAttrs() : nullptr,
14343 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014344 if (VDPrivate->isInvalidDecl())
14345 continue;
14346
14347 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014348 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014349 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14350
14351 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014352 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014353 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014354 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14355 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014356 AddInitializerToDecl(VDPrivate,
14357 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014358 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014359
14360 // If required, build a capture to implement the privatization initialized
14361 // with the current list item value.
14362 DeclRefExpr *Ref = nullptr;
14363 if (!VD)
14364 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14365 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14366 PrivateCopies.push_back(VDPrivateRefExpr);
14367 Inits.push_back(VDInitRefExpr);
14368
14369 // We need to add a data sharing attribute for this variable to make sure it
14370 // is correctly captured. A variable that shows up in a use_device_ptr has
14371 // similar properties of a first private variable.
14372 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14373
14374 // Create a mappable component for the list item. List items in this clause
14375 // only need a component.
14376 MVLI.VarBaseDeclarations.push_back(D);
14377 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14378 MVLI.VarComponents.back().push_back(
14379 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014380 }
14381
Samuel Antaocc10b852016-07-28 14:23:26 +000014382 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014383 return nullptr;
14384
Samuel Antaocc10b852016-07-28 14:23:26 +000014385 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014386 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14387 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014388}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014389
14390OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014391 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014392 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014393 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014394 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014395 SourceLocation ELoc;
14396 SourceRange ERange;
14397 Expr *SimpleRefExpr = RefExpr;
14398 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14399 if (Res.second) {
14400 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014401 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014402 }
14403 ValueDecl *D = Res.first;
14404 if (!D)
14405 continue;
14406
14407 QualType Type = D->getType();
14408 // item should be a pointer or array or reference to pointer or array
14409 if (!Type.getNonReferenceType()->isPointerType() &&
14410 !Type.getNonReferenceType()->isArrayType()) {
14411 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14412 << 0 << RefExpr->getSourceRange();
14413 continue;
14414 }
Samuel Antao6890b092016-07-28 14:25:09 +000014415
14416 // Check if the declaration in the clause does not show up in any data
14417 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014418 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014419 if (isOpenMPPrivate(DVar.CKind)) {
14420 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14421 << getOpenMPClauseName(DVar.CKind)
14422 << getOpenMPClauseName(OMPC_is_device_ptr)
14423 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014424 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014425 continue;
14426 }
14427
Alexey Bataeve3727102018-04-18 15:57:46 +000014428 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014429 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014430 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014431 [&ConflictExpr](
14432 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14433 OpenMPClauseKind) -> bool {
14434 ConflictExpr = R.front().getAssociatedExpression();
14435 return true;
14436 })) {
14437 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14438 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14439 << ConflictExpr->getSourceRange();
14440 continue;
14441 }
14442
14443 // Store the components in the stack so that they can be used to check
14444 // against other clauses later on.
14445 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14446 DSAStack->addMappableExpressionComponents(
14447 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14448
14449 // Record the expression we've just processed.
14450 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14451
14452 // Create a mappable component for the list item. List items in this clause
14453 // only need a component. We use a null declaration to signal fields in
14454 // 'this'.
14455 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14456 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14457 "Unexpected device pointer expression!");
14458 MVLI.VarBaseDeclarations.push_back(
14459 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14460 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14461 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014462 }
14463
Samuel Antao6890b092016-07-28 14:25:09 +000014464 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014465 return nullptr;
14466
Michael Kruse4304e9d2019-02-19 16:38:20 +000014467 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14468 MVLI.VarBaseDeclarations,
14469 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014470}