blob: a36eaefecfb7fe4f172684b7c913283a6446dc99 [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
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002197Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2198 SourceLocation Loc, ArrayRef<Expr *> VarList,
2199 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2200 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2201 Expr *Allocator = nullptr;
2202 if (!Clauses.empty())
2203 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002204 SmallVector<Expr *, 8> Vars;
2205 for (Expr *RefExpr : VarList) {
2206 auto *DE = cast<DeclRefExpr>(RefExpr);
2207 auto *VD = cast<VarDecl>(DE->getDecl());
2208
2209 // Check if this is a TLS variable or global register.
2210 if (VD->getTLSKind() != VarDecl::TLS_None ||
2211 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2212 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2213 !VD->isLocalVarDecl()))
2214 continue;
2215 // Do not apply for parameters.
2216 if (isa<ParmVarDecl>(VD))
2217 continue;
2218
Alexey Bataev282555a2019-03-19 20:33:44 +00002219 // If the used several times in the allocate directive, the same allocator
2220 // must be used.
2221 if (VD->hasAttr<OMPAllocateDeclAttr>()) {
2222 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2223 const Expr *PrevAllocator = A->getAllocator();
2224 bool AllocatorsMatch = false;
2225 if (Allocator && PrevAllocator) {
2226 const Expr *AE = Allocator->IgnoreParenImpCasts();
2227 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2228 llvm::FoldingSetNodeID AEId, PAEId;
2229 AE->Profile(AEId, Context, /*Canonical=*/true);
2230 PAE->Profile(PAEId, Context, /*Canonical=*/true);
2231 AllocatorsMatch = AEId == PAEId;
2232 } else if (!Allocator && !PrevAllocator) {
2233 AllocatorsMatch = true;
2234 } else {
2235 const Expr *AE = Allocator ? Allocator : PrevAllocator;
2236 // In this case the specified allocator must be the default one.
2237 AE = AE->IgnoreParenImpCasts();
2238 if (const auto *DRE = dyn_cast<DeclRefExpr>(AE)) {
2239 DeclarationName DN = DRE->getDecl()->getDeclName();
2240 AllocatorsMatch =
2241 DN.isIdentifier() &&
2242 DN.getAsIdentifierInfo()->isStr("omp_default_mem_alloc");
2243 }
2244 }
2245 if (!AllocatorsMatch) {
2246 SmallString<256> AllocatorBuffer;
2247 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2248 if (Allocator)
2249 Allocator->printPretty(AllocatorStream, nullptr, getPrintingPolicy());
2250 SmallString<256> PrevAllocatorBuffer;
2251 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2252 if (PrevAllocator)
2253 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2254 getPrintingPolicy());
2255
2256 SourceLocation AllocatorLoc =
2257 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2258 SourceRange AllocatorRange =
2259 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2260 SourceLocation PrevAllocatorLoc =
2261 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2262 SourceRange PrevAllocatorRange =
2263 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2264 Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2265 << (Allocator ? 1 : 0) << AllocatorStream.str()
2266 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2267 << AllocatorRange;
2268 Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2269 << PrevAllocatorRange;
2270 continue;
2271 }
2272 }
2273
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002274 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2275 // If a list item has a static storage type, the allocator expression in the
2276 // allocator clause must be a constant expression that evaluates to one of
2277 // the predefined memory allocator values.
2278 if (Allocator && VD->hasGlobalStorage()) {
2279 bool IsPredefinedAllocator = false;
2280 if (const auto *DRE =
2281 dyn_cast<DeclRefExpr>(Allocator->IgnoreParenImpCasts())) {
2282 if (DRE->getType().isConstant(getASTContext())) {
2283 DeclarationName DN = DRE->getDecl()->getDeclName();
2284 if (DN.isIdentifier()) {
2285 StringRef PredefinedAllocators[] = {
2286 "omp_default_mem_alloc", "omp_large_cap_mem_alloc",
2287 "omp_const_mem_alloc", "omp_high_bw_mem_alloc",
2288 "omp_low_lat_mem_alloc", "omp_cgroup_mem_alloc",
2289 "omp_pteam_mem_alloc", "omp_thread_mem_alloc",
2290 };
2291 IsPredefinedAllocator =
2292 llvm::any_of(PredefinedAllocators, [&DN](StringRef S) {
2293 return DN.getAsIdentifierInfo()->isStr(S);
2294 });
2295 }
2296 }
2297 }
2298 if (!IsPredefinedAllocator) {
2299 Diag(Allocator->getExprLoc(),
2300 diag::err_omp_expected_predefined_allocator)
2301 << Allocator->getSourceRange();
2302 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2303 VarDecl::DeclarationOnly;
2304 Diag(VD->getLocation(),
2305 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2306 << VD;
2307 continue;
2308 }
2309 }
2310
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002311 Vars.push_back(RefExpr);
Alexey Bataev282555a2019-03-19 20:33:44 +00002312 if ((!Allocator || (Allocator && !Allocator->isTypeDependent() &&
2313 !Allocator->isValueDependent() &&
2314 !Allocator->isInstantiationDependent() &&
2315 !Allocator->containsUnexpandedParameterPack())) &&
2316 !VD->hasAttr<OMPAllocateDeclAttr>()) {
2317 Attr *A = OMPAllocateDeclAttr::CreateImplicit(Context, Allocator,
2318 DE->getSourceRange());
2319 VD->addAttr(A);
2320 if (ASTMutationListener *ML = Context.getASTMutationListener())
2321 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2322 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002323 }
2324 if (Vars.empty())
2325 return nullptr;
2326 if (!Owner)
2327 Owner = getCurLexicalContext();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002328 OMPAllocateDecl *D =
2329 OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002330 D->setAccess(AS_public);
2331 Owner->addDecl(D);
2332 return DeclGroupPtrTy::make(DeclGroupRef(D));
2333}
2334
2335Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002336Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2337 ArrayRef<OMPClause *> ClauseList) {
2338 OMPRequiresDecl *D = nullptr;
2339 if (!CurContext->isFileContext()) {
2340 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2341 } else {
2342 D = CheckOMPRequiresDecl(Loc, ClauseList);
2343 if (D) {
2344 CurContext->addDecl(D);
2345 DSAStack->addRequiresDecl(D);
2346 }
2347 }
2348 return DeclGroupPtrTy::make(DeclGroupRef(D));
2349}
2350
2351OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2352 ArrayRef<OMPClause *> ClauseList) {
2353 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2354 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2355 ClauseList);
2356 return nullptr;
2357}
2358
Alexey Bataeve3727102018-04-18 15:57:46 +00002359static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2360 const ValueDecl *D,
2361 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002362 bool IsLoopIterVar = false) {
2363 if (DVar.RefExpr) {
2364 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2365 << getOpenMPClauseName(DVar.CKind);
2366 return;
2367 }
2368 enum {
2369 PDSA_StaticMemberShared,
2370 PDSA_StaticLocalVarShared,
2371 PDSA_LoopIterVarPrivate,
2372 PDSA_LoopIterVarLinear,
2373 PDSA_LoopIterVarLastprivate,
2374 PDSA_ConstVarShared,
2375 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002376 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002377 PDSA_LocalVarPrivate,
2378 PDSA_Implicit
2379 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002380 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002381 auto ReportLoc = D->getLocation();
2382 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002383 if (IsLoopIterVar) {
2384 if (DVar.CKind == OMPC_private)
2385 Reason = PDSA_LoopIterVarPrivate;
2386 else if (DVar.CKind == OMPC_lastprivate)
2387 Reason = PDSA_LoopIterVarLastprivate;
2388 else
2389 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002390 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2391 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002392 Reason = PDSA_TaskVarFirstprivate;
2393 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002394 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002395 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002396 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002397 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002398 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002399 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002400 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002401 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002402 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002403 ReportHint = true;
2404 Reason = PDSA_LocalVarPrivate;
2405 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002406 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002407 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002408 << Reason << ReportHint
2409 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2410 } else if (DVar.ImplicitDSALoc.isValid()) {
2411 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2412 << getOpenMPClauseName(DVar.CKind);
2413 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002414}
2415
Alexey Bataev758e55e2013-09-06 18:03:48 +00002416namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002417class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002418 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002419 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002420 bool ErrorFound = false;
2421 CapturedStmt *CS = nullptr;
2422 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2423 llvm::SmallVector<Expr *, 4> ImplicitMap;
2424 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2425 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002426
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002427 void VisitSubCaptures(OMPExecutableDirective *S) {
2428 // Check implicitly captured variables.
2429 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2430 return;
2431 for (const CapturedStmt::Capture &Cap :
2432 S->getInnermostCapturedStmt()->captures()) {
2433 if (!Cap.capturesVariable())
2434 continue;
2435 VarDecl *VD = Cap.getCapturedVar();
2436 // Do not try to map the variable if it or its sub-component was mapped
2437 // already.
2438 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2439 Stack->checkMappableExprComponentListsForDecl(
2440 VD, /*CurrentRegionOnly=*/true,
2441 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2442 OpenMPClauseKind) { return true; }))
2443 continue;
2444 DeclRefExpr *DRE = buildDeclRefExpr(
2445 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2446 Cap.getLocation(), /*RefersToCapture=*/true);
2447 Visit(DRE);
2448 }
2449 }
2450
Alexey Bataev758e55e2013-09-06 18:03:48 +00002451public:
2452 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002453 if (E->isTypeDependent() || E->isValueDependent() ||
2454 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2455 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002456 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002457 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002458 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002459 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002460 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002461
Alexey Bataeve3727102018-04-18 15:57:46 +00002462 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002463 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002464 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002465 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002466
Alexey Bataevafe50572017-10-06 17:00:28 +00002467 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002468 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002469 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002470 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2471 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002472 return;
2473
Alexey Bataeve3727102018-04-18 15:57:46 +00002474 SourceLocation ELoc = E->getExprLoc();
2475 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002476 // The default(none) clause requires that each variable that is referenced
2477 // in the construct, and does not have a predetermined data-sharing
2478 // attribute, must have its data-sharing attribute explicitly determined
2479 // by being listed in a data-sharing attribute clause.
2480 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002481 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002482 VarsWithInheritedDSA.count(VD) == 0) {
2483 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002484 return;
2485 }
2486
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002487 if (isOpenMPTargetExecutionDirective(DKind) &&
2488 !Stack->isLoopControlVariable(VD).first) {
2489 if (!Stack->checkMappableExprComponentListsForDecl(
2490 VD, /*CurrentRegionOnly=*/true,
2491 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2492 StackComponents,
2493 OpenMPClauseKind) {
2494 // Variable is used if it has been marked as an array, array
2495 // section or the variable iself.
2496 return StackComponents.size() == 1 ||
2497 std::all_of(
2498 std::next(StackComponents.rbegin()),
2499 StackComponents.rend(),
2500 [](const OMPClauseMappableExprCommon::
2501 MappableComponent &MC) {
2502 return MC.getAssociatedDeclaration() ==
2503 nullptr &&
2504 (isa<OMPArraySectionExpr>(
2505 MC.getAssociatedExpression()) ||
2506 isa<ArraySubscriptExpr>(
2507 MC.getAssociatedExpression()));
2508 });
2509 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002510 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002511 // By default lambdas are captured as firstprivates.
2512 if (const auto *RD =
2513 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002514 IsFirstprivate = RD->isLambda();
2515 IsFirstprivate =
2516 IsFirstprivate ||
2517 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002518 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002519 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002520 ImplicitFirstprivate.emplace_back(E);
2521 else
2522 ImplicitMap.emplace_back(E);
2523 return;
2524 }
2525 }
2526
Alexey Bataev758e55e2013-09-06 18:03:48 +00002527 // OpenMP [2.9.3.6, Restrictions, p.2]
2528 // A list item that appears in a reduction clause of the innermost
2529 // enclosing worksharing or parallel construct may not be accessed in an
2530 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002531 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002532 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2533 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002534 return isOpenMPParallelDirective(K) ||
2535 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2536 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002537 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002538 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002539 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002540 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002541 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002542 return;
2543 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002544
2545 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002546 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002547 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002548 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002549 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002550 return;
2551 }
2552
2553 // Store implicitly used globals with declare target link for parent
2554 // target.
2555 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2556 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2557 Stack->addToParentTargetRegionLinkGlobals(E);
2558 return;
2559 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002560 }
2561 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002562 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002563 if (E->isTypeDependent() || E->isValueDependent() ||
2564 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2565 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002566 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002567 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002568 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002569 if (!FD)
2570 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002571 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002572 // Check if the variable has explicit DSA set and stop analysis if it
2573 // so.
2574 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2575 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002576
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002577 if (isOpenMPTargetExecutionDirective(DKind) &&
2578 !Stack->isLoopControlVariable(FD).first &&
2579 !Stack->checkMappableExprComponentListsForDecl(
2580 FD, /*CurrentRegionOnly=*/true,
2581 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2582 StackComponents,
2583 OpenMPClauseKind) {
2584 return isa<CXXThisExpr>(
2585 cast<MemberExpr>(
2586 StackComponents.back().getAssociatedExpression())
2587 ->getBase()
2588 ->IgnoreParens());
2589 })) {
2590 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2591 // A bit-field cannot appear in a map clause.
2592 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002593 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002594 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002595
2596 // Check to see if the member expression is referencing a class that
2597 // has already been explicitly mapped
2598 if (Stack->isClassPreviouslyMapped(TE->getType()))
2599 return;
2600
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002601 ImplicitMap.emplace_back(E);
2602 return;
2603 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002604
Alexey Bataeve3727102018-04-18 15:57:46 +00002605 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002606 // OpenMP [2.9.3.6, Restrictions, p.2]
2607 // A list item that appears in a reduction clause of the innermost
2608 // enclosing worksharing or parallel construct may not be accessed in
2609 // an explicit task.
2610 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002611 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2612 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002613 return isOpenMPParallelDirective(K) ||
2614 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2615 },
2616 /*FromParent=*/true);
2617 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2618 ErrorFound = true;
2619 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002620 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002621 return;
2622 }
2623
2624 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002625 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002626 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002627 !Stack->isLoopControlVariable(FD).first) {
2628 // Check if there is a captured expression for the current field in the
2629 // region. Do not mark it as firstprivate unless there is no captured
2630 // expression.
2631 // TODO: try to make it firstprivate.
2632 if (DVar.CKind != OMPC_unknown)
2633 ImplicitFirstprivate.push_back(E);
2634 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002635 return;
2636 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002637 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002638 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002639 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002640 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002641 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002642 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002643 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2644 if (!Stack->checkMappableExprComponentListsForDecl(
2645 VD, /*CurrentRegionOnly=*/true,
2646 [&CurComponents](
2647 OMPClauseMappableExprCommon::MappableExprComponentListRef
2648 StackComponents,
2649 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002650 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002651 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002652 for (const auto &SC : llvm::reverse(StackComponents)) {
2653 // Do both expressions have the same kind?
2654 if (CCI->getAssociatedExpression()->getStmtClass() !=
2655 SC.getAssociatedExpression()->getStmtClass())
2656 if (!(isa<OMPArraySectionExpr>(
2657 SC.getAssociatedExpression()) &&
2658 isa<ArraySubscriptExpr>(
2659 CCI->getAssociatedExpression())))
2660 return false;
2661
Alexey Bataeve3727102018-04-18 15:57:46 +00002662 const Decl *CCD = CCI->getAssociatedDeclaration();
2663 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002664 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2665 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2666 if (SCD != CCD)
2667 return false;
2668 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002669 if (CCI == CCE)
2670 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002671 }
2672 return true;
2673 })) {
2674 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002675 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002676 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002677 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002678 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002679 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002680 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002681 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002682 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002683 // for task|target directives.
2684 // Skip analysis of arguments of implicitly defined map clause for target
2685 // directives.
2686 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2687 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002688 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002689 if (CC)
2690 Visit(CC);
2691 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002692 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002693 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002694 // Check implicitly captured variables.
2695 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002696 }
2697 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002698 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002699 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002700 // Check implicitly captured variables in the task-based directives to
2701 // check if they must be firstprivatized.
2702 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002703 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002704 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002705 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002706
Alexey Bataeve3727102018-04-18 15:57:46 +00002707 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002708 ArrayRef<Expr *> getImplicitFirstprivate() const {
2709 return ImplicitFirstprivate;
2710 }
2711 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002712 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002713 return VarsWithInheritedDSA;
2714 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002715
Alexey Bataev7ff55242014-06-19 09:13:45 +00002716 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002717 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2718 // Process declare target link variables for the target directives.
2719 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2720 for (DeclRefExpr *E : Stack->getLinkGlobals())
2721 Visit(E);
2722 }
2723 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002724};
Alexey Bataeved09d242014-05-28 05:53:51 +00002725} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002726
Alexey Bataevbae9a792014-06-27 10:37:06 +00002727void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002728 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002729 case OMPD_parallel:
2730 case OMPD_parallel_for:
2731 case OMPD_parallel_for_simd:
2732 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002733 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002734 case OMPD_teams_distribute:
2735 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002736 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002737 QualType KmpInt32PtrTy =
2738 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002739 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002740 std::make_pair(".global_tid.", KmpInt32PtrTy),
2741 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2742 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002743 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002744 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2745 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002746 break;
2747 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002748 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002749 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002750 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002751 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002752 case OMPD_target_teams_distribute:
2753 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002754 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2755 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2756 QualType KmpInt32PtrTy =
2757 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2758 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002759 FunctionProtoType::ExtProtoInfo EPI;
2760 EPI.Variadic = true;
2761 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2762 Sema::CapturedParamNameType Params[] = {
2763 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002764 std::make_pair(".part_id.", KmpInt32PtrTy),
2765 std::make_pair(".privates.", VoidPtrTy),
2766 std::make_pair(
2767 ".copy_fn.",
2768 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002769 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2770 std::make_pair(StringRef(), QualType()) // __context with shared vars
2771 };
2772 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2773 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002774 // Mark this captured region as inlined, because we don't use outlined
2775 // function directly.
2776 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2777 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002778 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002779 Sema::CapturedParamNameType ParamsTarget[] = {
2780 std::make_pair(StringRef(), QualType()) // __context with shared vars
2781 };
2782 // Start a captured region for 'target' with no implicit parameters.
2783 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2784 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002785 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002786 std::make_pair(".global_tid.", KmpInt32PtrTy),
2787 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2788 std::make_pair(StringRef(), QualType()) // __context with shared vars
2789 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002790 // Start a captured region for 'teams' or 'parallel'. Both regions have
2791 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002792 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002793 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002794 break;
2795 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002796 case OMPD_target:
2797 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002798 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2799 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2800 QualType KmpInt32PtrTy =
2801 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2802 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002803 FunctionProtoType::ExtProtoInfo EPI;
2804 EPI.Variadic = true;
2805 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2806 Sema::CapturedParamNameType Params[] = {
2807 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002808 std::make_pair(".part_id.", KmpInt32PtrTy),
2809 std::make_pair(".privates.", VoidPtrTy),
2810 std::make_pair(
2811 ".copy_fn.",
2812 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002813 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2814 std::make_pair(StringRef(), QualType()) // __context with shared vars
2815 };
2816 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2817 Params);
2818 // Mark this captured region as inlined, because we don't use outlined
2819 // function directly.
2820 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2821 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002822 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002823 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2824 std::make_pair(StringRef(), QualType()));
2825 break;
2826 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002827 case OMPD_simd:
2828 case OMPD_for:
2829 case OMPD_for_simd:
2830 case OMPD_sections:
2831 case OMPD_section:
2832 case OMPD_single:
2833 case OMPD_master:
2834 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002835 case OMPD_taskgroup:
2836 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002837 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002838 case OMPD_ordered:
2839 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002840 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002841 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002842 std::make_pair(StringRef(), QualType()) // __context with shared vars
2843 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2845 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002846 break;
2847 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002848 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002849 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2850 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2851 QualType KmpInt32PtrTy =
2852 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2853 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002854 FunctionProtoType::ExtProtoInfo EPI;
2855 EPI.Variadic = true;
2856 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002857 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002858 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002859 std::make_pair(".part_id.", KmpInt32PtrTy),
2860 std::make_pair(".privates.", VoidPtrTy),
2861 std::make_pair(
2862 ".copy_fn.",
2863 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002864 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002865 std::make_pair(StringRef(), QualType()) // __context with shared vars
2866 };
2867 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2868 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002869 // Mark this captured region as inlined, because we don't use outlined
2870 // function directly.
2871 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2872 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002873 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002874 break;
2875 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002876 case OMPD_taskloop:
2877 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002878 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002879 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2880 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002881 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002882 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2883 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002884 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002885 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2886 .withConst();
2887 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2888 QualType KmpInt32PtrTy =
2889 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2890 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002891 FunctionProtoType::ExtProtoInfo EPI;
2892 EPI.Variadic = true;
2893 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002894 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002895 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002896 std::make_pair(".part_id.", KmpInt32PtrTy),
2897 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002898 std::make_pair(
2899 ".copy_fn.",
2900 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2901 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2902 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002903 std::make_pair(".ub.", KmpUInt64Ty),
2904 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002905 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002906 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002907 std::make_pair(StringRef(), QualType()) // __context with shared vars
2908 };
2909 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2910 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002911 // Mark this captured region as inlined, because we don't use outlined
2912 // function directly.
2913 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2914 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002915 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002916 break;
2917 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002918 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002919 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002920 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002921 QualType KmpInt32PtrTy =
2922 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2923 Sema::CapturedParamNameType Params[] = {
2924 std::make_pair(".global_tid.", KmpInt32PtrTy),
2925 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002926 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2927 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002928 std::make_pair(StringRef(), QualType()) // __context with shared vars
2929 };
2930 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2931 Params);
2932 break;
2933 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002934 case OMPD_target_teams_distribute_parallel_for:
2935 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002936 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002937 QualType KmpInt32PtrTy =
2938 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002939 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002940
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002941 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002942 FunctionProtoType::ExtProtoInfo EPI;
2943 EPI.Variadic = true;
2944 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2945 Sema::CapturedParamNameType Params[] = {
2946 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002947 std::make_pair(".part_id.", KmpInt32PtrTy),
2948 std::make_pair(".privates.", VoidPtrTy),
2949 std::make_pair(
2950 ".copy_fn.",
2951 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002952 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2953 std::make_pair(StringRef(), QualType()) // __context with shared vars
2954 };
2955 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2956 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002957 // Mark this captured region as inlined, because we don't use outlined
2958 // function directly.
2959 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2960 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002961 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002962 Sema::CapturedParamNameType ParamsTarget[] = {
2963 std::make_pair(StringRef(), QualType()) // __context with shared vars
2964 };
2965 // Start a captured region for 'target' with no implicit parameters.
2966 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2967 ParamsTarget);
2968
2969 Sema::CapturedParamNameType ParamsTeams[] = {
2970 std::make_pair(".global_tid.", KmpInt32PtrTy),
2971 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2972 std::make_pair(StringRef(), QualType()) // __context with shared vars
2973 };
2974 // Start a captured region for 'target' with no implicit parameters.
2975 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2976 ParamsTeams);
2977
2978 Sema::CapturedParamNameType ParamsParallel[] = {
2979 std::make_pair(".global_tid.", KmpInt32PtrTy),
2980 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002981 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2982 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002983 std::make_pair(StringRef(), QualType()) // __context with shared vars
2984 };
2985 // Start a captured region for 'teams' or 'parallel'. Both regions have
2986 // the same implicit parameters.
2987 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2988 ParamsParallel);
2989 break;
2990 }
2991
Alexey Bataev46506272017-12-05 17:41:34 +00002992 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002993 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002994 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002995 QualType KmpInt32PtrTy =
2996 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2997
2998 Sema::CapturedParamNameType ParamsTeams[] = {
2999 std::make_pair(".global_tid.", KmpInt32PtrTy),
3000 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3001 std::make_pair(StringRef(), QualType()) // __context with shared vars
3002 };
3003 // Start a captured region for 'target' with no implicit parameters.
3004 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3005 ParamsTeams);
3006
3007 Sema::CapturedParamNameType ParamsParallel[] = {
3008 std::make_pair(".global_tid.", KmpInt32PtrTy),
3009 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003010 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3011 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003012 std::make_pair(StringRef(), QualType()) // __context with shared vars
3013 };
3014 // Start a captured region for 'teams' or 'parallel'. Both regions have
3015 // the same implicit parameters.
3016 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3017 ParamsParallel);
3018 break;
3019 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003020 case OMPD_target_update:
3021 case OMPD_target_enter_data:
3022 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003023 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3024 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3025 QualType KmpInt32PtrTy =
3026 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3027 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003028 FunctionProtoType::ExtProtoInfo EPI;
3029 EPI.Variadic = true;
3030 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3031 Sema::CapturedParamNameType Params[] = {
3032 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003033 std::make_pair(".part_id.", KmpInt32PtrTy),
3034 std::make_pair(".privates.", VoidPtrTy),
3035 std::make_pair(
3036 ".copy_fn.",
3037 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003038 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3039 std::make_pair(StringRef(), QualType()) // __context with shared vars
3040 };
3041 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3042 Params);
3043 // Mark this captured region as inlined, because we don't use outlined
3044 // function directly.
3045 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3046 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003047 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003048 break;
3049 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003050 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003051 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003052 case OMPD_taskyield:
3053 case OMPD_barrier:
3054 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003055 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003056 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003057 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003058 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003059 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003060 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003061 case OMPD_declare_target:
3062 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003063 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003064 llvm_unreachable("OpenMP Directive is not allowed");
3065 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003066 llvm_unreachable("Unknown OpenMP directive");
3067 }
3068}
3069
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003070int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3071 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3072 getOpenMPCaptureRegions(CaptureRegions, DKind);
3073 return CaptureRegions.size();
3074}
3075
Alexey Bataev3392d762016-02-16 11:18:12 +00003076static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003077 Expr *CaptureExpr, bool WithInit,
3078 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003079 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003080 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003081 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003082 QualType Ty = Init->getType();
3083 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003084 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003085 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003086 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003087 Ty = C.getPointerType(Ty);
3088 ExprResult Res =
3089 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3090 if (!Res.isUsable())
3091 return nullptr;
3092 Init = Res.get();
3093 }
Alexey Bataev61205072016-03-02 04:57:40 +00003094 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003095 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003096 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003097 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003098 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003099 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003100 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003101 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003102 return CED;
3103}
3104
Alexey Bataev61205072016-03-02 04:57:40 +00003105static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3106 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003107 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003108 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003109 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003110 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003111 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3112 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003113 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003114 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003115}
3116
Alexey Bataev5a3af132016-03-29 08:58:54 +00003117static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003118 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003119 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003120 OMPCapturedExprDecl *CD = buildCaptureDecl(
3121 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3122 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003123 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3124 CaptureExpr->getExprLoc());
3125 }
3126 ExprResult Res = Ref;
3127 if (!S.getLangOpts().CPlusPlus &&
3128 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003129 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003130 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003131 if (!Res.isUsable())
3132 return ExprError();
3133 }
3134 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003135}
3136
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003137namespace {
3138// OpenMP directives parsed in this section are represented as a
3139// CapturedStatement with an associated statement. If a syntax error
3140// is detected during the parsing of the associated statement, the
3141// compiler must abort processing and close the CapturedStatement.
3142//
3143// Combined directives such as 'target parallel' have more than one
3144// nested CapturedStatements. This RAII ensures that we unwind out
3145// of all the nested CapturedStatements when an error is found.
3146class CaptureRegionUnwinderRAII {
3147private:
3148 Sema &S;
3149 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003150 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003151
3152public:
3153 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3154 OpenMPDirectiveKind DKind)
3155 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3156 ~CaptureRegionUnwinderRAII() {
3157 if (ErrorFound) {
3158 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3159 while (--ThisCaptureLevel >= 0)
3160 S.ActOnCapturedRegionError();
3161 }
3162 }
3163};
3164} // namespace
3165
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003166StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3167 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003168 bool ErrorFound = false;
3169 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3170 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003171 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003172 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003173 return StmtError();
3174 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003175
Alexey Bataev2ba67042017-11-28 21:11:44 +00003176 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3177 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003178 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003179 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003180 SmallVector<const OMPLinearClause *, 4> LCs;
3181 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003182 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003183 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003184 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3185 Clause->getClauseKind() == OMPC_in_reduction) {
3186 // Capture taskgroup task_reduction descriptors inside the tasking regions
3187 // with the corresponding in_reduction items.
3188 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003189 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003190 if (E)
3191 MarkDeclarationsReferencedInExpr(E);
3192 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003193 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003194 Clause->getClauseKind() == OMPC_copyprivate ||
3195 (getLangOpts().OpenMPUseTLS &&
3196 getASTContext().getTargetInfo().isTLSSupported() &&
3197 Clause->getClauseKind() == OMPC_copyin)) {
3198 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003199 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003200 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003201 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003202 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003203 }
3204 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003205 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003206 } else if (CaptureRegions.size() > 1 ||
3207 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003208 if (auto *C = OMPClauseWithPreInit::get(Clause))
3209 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003210 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003211 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003212 MarkDeclarationsReferencedInExpr(E);
3213 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003214 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003215 if (Clause->getClauseKind() == OMPC_schedule)
3216 SC = cast<OMPScheduleClause>(Clause);
3217 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003218 OC = cast<OMPOrderedClause>(Clause);
3219 else if (Clause->getClauseKind() == OMPC_linear)
3220 LCs.push_back(cast<OMPLinearClause>(Clause));
3221 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003222 // OpenMP, 2.7.1 Loop Construct, Restrictions
3223 // The nonmonotonic modifier cannot be specified if an ordered clause is
3224 // specified.
3225 if (SC &&
3226 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3227 SC->getSecondScheduleModifier() ==
3228 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3229 OC) {
3230 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3231 ? SC->getFirstScheduleModifierLoc()
3232 : SC->getSecondScheduleModifierLoc(),
3233 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003234 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003235 ErrorFound = true;
3236 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003237 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003238 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003239 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003240 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003241 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003242 ErrorFound = true;
3243 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003244 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3245 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3246 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003247 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003248 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3249 ErrorFound = true;
3250 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003251 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003252 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003253 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003254 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003255 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003256 // Mark all variables in private list clauses as used in inner region.
3257 // Required for proper codegen of combined directives.
3258 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003259 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003260 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003261 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3262 // Find the particular capture region for the clause if the
3263 // directive is a combined one with multiple capture regions.
3264 // If the directive is not a combined one, the capture region
3265 // associated with the clause is OMPD_unknown and is generated
3266 // only once.
3267 if (CaptureRegion == ThisCaptureRegion ||
3268 CaptureRegion == OMPD_unknown) {
3269 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003270 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003271 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3272 }
3273 }
3274 }
3275 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003276 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003277 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003278 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003279}
3280
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003281static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3282 OpenMPDirectiveKind CancelRegion,
3283 SourceLocation StartLoc) {
3284 // CancelRegion is only needed for cancel and cancellation_point.
3285 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3286 return false;
3287
3288 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3289 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3290 return false;
3291
3292 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3293 << getOpenMPDirectiveName(CancelRegion);
3294 return true;
3295}
3296
Alexey Bataeve3727102018-04-18 15:57:46 +00003297static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003298 OpenMPDirectiveKind CurrentRegion,
3299 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003300 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003301 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003302 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003303 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3304 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003305 bool NestingProhibited = false;
3306 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003307 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003308 enum {
3309 NoRecommend,
3310 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003311 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003312 ShouldBeInTargetRegion,
3313 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003314 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003315 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003316 // OpenMP [2.16, Nesting of Regions]
3317 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003318 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003319 // An ordered construct with the simd clause is the only OpenMP
3320 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003321 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003322 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3323 // message.
3324 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3325 ? diag::err_omp_prohibited_region_simd
3326 : diag::warn_omp_nesting_simd);
3327 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003328 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003329 if (ParentRegion == OMPD_atomic) {
3330 // OpenMP [2.16, Nesting of Regions]
3331 // OpenMP constructs may not be nested inside an atomic region.
3332 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3333 return true;
3334 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003335 if (CurrentRegion == OMPD_section) {
3336 // OpenMP [2.7.2, sections Construct, Restrictions]
3337 // Orphaned section directives are prohibited. That is, the section
3338 // directives must appear within the sections construct and must not be
3339 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003340 if (ParentRegion != OMPD_sections &&
3341 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003342 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3343 << (ParentRegion != OMPD_unknown)
3344 << getOpenMPDirectiveName(ParentRegion);
3345 return true;
3346 }
3347 return false;
3348 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003349 // Allow some constructs (except teams and cancellation constructs) to be
3350 // orphaned (they could be used in functions, called from OpenMP regions
3351 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003352 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003353 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3354 CurrentRegion != OMPD_cancellation_point &&
3355 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003356 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003357 if (CurrentRegion == OMPD_cancellation_point ||
3358 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003359 // OpenMP [2.16, Nesting of Regions]
3360 // A cancellation point construct for which construct-type-clause is
3361 // taskgroup must be nested inside a task construct. A cancellation
3362 // point construct for which construct-type-clause is not taskgroup must
3363 // be closely nested inside an OpenMP construct that matches the type
3364 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003365 // A cancel construct for which construct-type-clause is taskgroup must be
3366 // nested inside a task construct. A cancel construct for which
3367 // construct-type-clause is not taskgroup must be closely nested inside an
3368 // OpenMP construct that matches the type specified in
3369 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003370 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003371 !((CancelRegion == OMPD_parallel &&
3372 (ParentRegion == OMPD_parallel ||
3373 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003374 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003375 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003376 ParentRegion == OMPD_target_parallel_for ||
3377 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003378 ParentRegion == OMPD_teams_distribute_parallel_for ||
3379 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003380 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3381 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003382 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3383 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003384 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003385 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003386 // OpenMP [2.16, Nesting of Regions]
3387 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003388 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003389 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003390 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003391 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3392 // OpenMP [2.16, Nesting of Regions]
3393 // A critical region may not be nested (closely or otherwise) inside a
3394 // critical region with the same name. Note that this restriction is not
3395 // sufficient to prevent deadlock.
3396 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003397 bool DeadLock = Stack->hasDirective(
3398 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3399 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003400 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003401 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3402 PreviousCriticalLoc = Loc;
3403 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003404 }
3405 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003406 },
3407 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003408 if (DeadLock) {
3409 SemaRef.Diag(StartLoc,
3410 diag::err_omp_prohibited_region_critical_same_name)
3411 << CurrentName.getName();
3412 if (PreviousCriticalLoc.isValid())
3413 SemaRef.Diag(PreviousCriticalLoc,
3414 diag::note_omp_previous_critical_region);
3415 return true;
3416 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003417 } else if (CurrentRegion == OMPD_barrier) {
3418 // OpenMP [2.16, Nesting of Regions]
3419 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003420 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003421 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3422 isOpenMPTaskingDirective(ParentRegion) ||
3423 ParentRegion == OMPD_master ||
3424 ParentRegion == OMPD_critical ||
3425 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003426 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003427 !isOpenMPParallelDirective(CurrentRegion) &&
3428 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003429 // OpenMP [2.16, Nesting of Regions]
3430 // A worksharing region may not be closely nested inside a worksharing,
3431 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003432 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3433 isOpenMPTaskingDirective(ParentRegion) ||
3434 ParentRegion == OMPD_master ||
3435 ParentRegion == OMPD_critical ||
3436 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003437 Recommend = ShouldBeInParallelRegion;
3438 } else if (CurrentRegion == OMPD_ordered) {
3439 // OpenMP [2.16, Nesting of Regions]
3440 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003441 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003442 // An ordered region must be closely nested inside a loop region (or
3443 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003444 // OpenMP [2.8.1,simd Construct, Restrictions]
3445 // An ordered construct with the simd clause is the only OpenMP construct
3446 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003447 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003448 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003449 !(isOpenMPSimdDirective(ParentRegion) ||
3450 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003451 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003452 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003453 // OpenMP [2.16, Nesting of Regions]
3454 // If specified, a teams construct must be contained within a target
3455 // construct.
3456 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003457 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003458 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003459 }
Kelvin Libf594a52016-12-17 05:48:59 +00003460 if (!NestingProhibited &&
3461 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3462 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3463 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003464 // OpenMP [2.16, Nesting of Regions]
3465 // distribute, parallel, parallel sections, parallel workshare, and the
3466 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3467 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003468 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3469 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003470 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003471 }
David Majnemer9d168222016-08-05 17:44:54 +00003472 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003473 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003474 // OpenMP 4.5 [2.17 Nesting of Regions]
3475 // The region associated with the distribute construct must be strictly
3476 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003477 NestingProhibited =
3478 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003479 Recommend = ShouldBeInTeamsRegion;
3480 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003481 if (!NestingProhibited &&
3482 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3483 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3484 // OpenMP 4.5 [2.17 Nesting of Regions]
3485 // If a target, target update, target data, target enter data, or
3486 // target exit data construct is encountered during execution of a
3487 // target region, the behavior is unspecified.
3488 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003489 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003490 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003491 if (isOpenMPTargetExecutionDirective(K)) {
3492 OffendingRegion = K;
3493 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003494 }
3495 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003496 },
3497 false /* don't skip top directive */);
3498 CloseNesting = false;
3499 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003500 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003501 if (OrphanSeen) {
3502 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3503 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3504 } else {
3505 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3506 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3507 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3508 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003509 return true;
3510 }
3511 }
3512 return false;
3513}
3514
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003515static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3516 ArrayRef<OMPClause *> Clauses,
3517 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3518 bool ErrorFound = false;
3519 unsigned NamedModifiersNumber = 0;
3520 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3521 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003522 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003523 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003524 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3525 // At most one if clause without a directive-name-modifier can appear on
3526 // the directive.
3527 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3528 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003529 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003530 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3531 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3532 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003533 } else if (CurNM != OMPD_unknown) {
3534 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003535 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003536 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003537 FoundNameModifiers[CurNM] = IC;
3538 if (CurNM == OMPD_unknown)
3539 continue;
3540 // Check if the specified name modifier is allowed for the current
3541 // directive.
3542 // At most one if clause with the particular directive-name-modifier can
3543 // appear on the directive.
3544 bool MatchFound = false;
3545 for (auto NM : AllowedNameModifiers) {
3546 if (CurNM == NM) {
3547 MatchFound = true;
3548 break;
3549 }
3550 }
3551 if (!MatchFound) {
3552 S.Diag(IC->getNameModifierLoc(),
3553 diag::err_omp_wrong_if_directive_name_modifier)
3554 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3555 ErrorFound = true;
3556 }
3557 }
3558 }
3559 // If any if clause on the directive includes a directive-name-modifier then
3560 // all if clauses on the directive must include a directive-name-modifier.
3561 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3562 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003563 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003564 diag::err_omp_no_more_if_clause);
3565 } else {
3566 std::string Values;
3567 std::string Sep(", ");
3568 unsigned AllowedCnt = 0;
3569 unsigned TotalAllowedNum =
3570 AllowedNameModifiers.size() - NamedModifiersNumber;
3571 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3572 ++Cnt) {
3573 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3574 if (!FoundNameModifiers[NM]) {
3575 Values += "'";
3576 Values += getOpenMPDirectiveName(NM);
3577 Values += "'";
3578 if (AllowedCnt + 2 == TotalAllowedNum)
3579 Values += " or ";
3580 else if (AllowedCnt + 1 != TotalAllowedNum)
3581 Values += Sep;
3582 ++AllowedCnt;
3583 }
3584 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003585 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003586 diag::err_omp_unnamed_if_clause)
3587 << (TotalAllowedNum > 1) << Values;
3588 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003589 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003590 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3591 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003592 ErrorFound = true;
3593 }
3594 return ErrorFound;
3595}
3596
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003597StmtResult Sema::ActOnOpenMPExecutableDirective(
3598 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3599 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3600 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003601 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003602 // First check CancelRegion which is then used in checkNestingOfRegions.
3603 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3604 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003605 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003606 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003607
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003608 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003609 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003610 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003611 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003612 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003613 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3614
3615 // Check default data sharing attributes for referenced variables.
3616 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003617 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3618 Stmt *S = AStmt;
3619 while (--ThisCaptureLevel >= 0)
3620 S = cast<CapturedStmt>(S)->getCapturedStmt();
3621 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003622 if (DSAChecker.isErrorFound())
3623 return StmtError();
3624 // Generate list of implicitly defined firstprivate variables.
3625 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003626
Alexey Bataev88202be2017-07-27 13:20:36 +00003627 SmallVector<Expr *, 4> ImplicitFirstprivates(
3628 DSAChecker.getImplicitFirstprivate().begin(),
3629 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003630 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3631 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003632 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003633 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003634 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003635 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003636 if (E)
3637 ImplicitFirstprivates.emplace_back(E);
3638 }
3639 }
3640 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003641 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003642 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3643 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003644 ClausesWithImplicit.push_back(Implicit);
3645 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003646 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003647 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003648 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003649 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003650 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003651 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003652 CXXScopeSpec MapperIdScopeSpec;
3653 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003654 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003655 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3656 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3657 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003658 ClausesWithImplicit.emplace_back(Implicit);
3659 ErrorFound |=
3660 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003661 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003662 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003663 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003664 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003665 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003666
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003667 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003668 switch (Kind) {
3669 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003670 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3671 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003672 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003673 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003674 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003675 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3676 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003677 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003678 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003679 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3680 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003681 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003682 case OMPD_for_simd:
3683 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3684 EndLoc, VarsWithInheritedDSA);
3685 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003686 case OMPD_sections:
3687 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3688 EndLoc);
3689 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003690 case OMPD_section:
3691 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003692 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003693 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3694 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003695 case OMPD_single:
3696 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3697 EndLoc);
3698 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003699 case OMPD_master:
3700 assert(ClausesWithImplicit.empty() &&
3701 "No clauses are allowed for 'omp master' directive");
3702 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3703 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003704 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003705 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3706 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003707 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003708 case OMPD_parallel_for:
3709 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3710 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003711 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003712 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003713 case OMPD_parallel_for_simd:
3714 Res = ActOnOpenMPParallelForSimdDirective(
3715 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003716 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003717 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003718 case OMPD_parallel_sections:
3719 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3720 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003721 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003722 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003723 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003724 Res =
3725 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003726 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003727 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003728 case OMPD_taskyield:
3729 assert(ClausesWithImplicit.empty() &&
3730 "No clauses are allowed for 'omp taskyield' directive");
3731 assert(AStmt == nullptr &&
3732 "No associated statement allowed for 'omp taskyield' directive");
3733 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3734 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003735 case OMPD_barrier:
3736 assert(ClausesWithImplicit.empty() &&
3737 "No clauses are allowed for 'omp barrier' directive");
3738 assert(AStmt == nullptr &&
3739 "No associated statement allowed for 'omp barrier' directive");
3740 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3741 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003742 case OMPD_taskwait:
3743 assert(ClausesWithImplicit.empty() &&
3744 "No clauses are allowed for 'omp taskwait' directive");
3745 assert(AStmt == nullptr &&
3746 "No associated statement allowed for 'omp taskwait' directive");
3747 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3748 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003749 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003750 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3751 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003752 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003753 case OMPD_flush:
3754 assert(AStmt == nullptr &&
3755 "No associated statement allowed for 'omp flush' directive");
3756 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3757 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003758 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003759 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3760 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003761 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003762 case OMPD_atomic:
3763 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3764 EndLoc);
3765 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003766 case OMPD_teams:
3767 Res =
3768 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3769 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003770 case OMPD_target:
3771 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3772 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003773 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003774 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003775 case OMPD_target_parallel:
3776 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3777 StartLoc, EndLoc);
3778 AllowedNameModifiers.push_back(OMPD_target);
3779 AllowedNameModifiers.push_back(OMPD_parallel);
3780 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003781 case OMPD_target_parallel_for:
3782 Res = ActOnOpenMPTargetParallelForDirective(
3783 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3784 AllowedNameModifiers.push_back(OMPD_target);
3785 AllowedNameModifiers.push_back(OMPD_parallel);
3786 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003787 case OMPD_cancellation_point:
3788 assert(ClausesWithImplicit.empty() &&
3789 "No clauses are allowed for 'omp cancellation point' directive");
3790 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3791 "cancellation point' directive");
3792 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3793 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003794 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003795 assert(AStmt == nullptr &&
3796 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003797 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3798 CancelRegion);
3799 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003800 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003801 case OMPD_target_data:
3802 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3803 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003804 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003805 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003806 case OMPD_target_enter_data:
3807 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003808 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003809 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3810 break;
Samuel Antao72590762016-01-19 20:04:50 +00003811 case OMPD_target_exit_data:
3812 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003813 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003814 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3815 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003816 case OMPD_taskloop:
3817 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3818 EndLoc, VarsWithInheritedDSA);
3819 AllowedNameModifiers.push_back(OMPD_taskloop);
3820 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003821 case OMPD_taskloop_simd:
3822 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3823 EndLoc, VarsWithInheritedDSA);
3824 AllowedNameModifiers.push_back(OMPD_taskloop);
3825 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003826 case OMPD_distribute:
3827 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3828 EndLoc, VarsWithInheritedDSA);
3829 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003830 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003831 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3832 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003833 AllowedNameModifiers.push_back(OMPD_target_update);
3834 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003835 case OMPD_distribute_parallel_for:
3836 Res = ActOnOpenMPDistributeParallelForDirective(
3837 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3838 AllowedNameModifiers.push_back(OMPD_parallel);
3839 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003840 case OMPD_distribute_parallel_for_simd:
3841 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3842 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3843 AllowedNameModifiers.push_back(OMPD_parallel);
3844 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003845 case OMPD_distribute_simd:
3846 Res = ActOnOpenMPDistributeSimdDirective(
3847 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3848 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003849 case OMPD_target_parallel_for_simd:
3850 Res = ActOnOpenMPTargetParallelForSimdDirective(
3851 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3852 AllowedNameModifiers.push_back(OMPD_target);
3853 AllowedNameModifiers.push_back(OMPD_parallel);
3854 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003855 case OMPD_target_simd:
3856 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3857 EndLoc, VarsWithInheritedDSA);
3858 AllowedNameModifiers.push_back(OMPD_target);
3859 break;
Kelvin Li02532872016-08-05 14:37:37 +00003860 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003861 Res = ActOnOpenMPTeamsDistributeDirective(
3862 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003863 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003864 case OMPD_teams_distribute_simd:
3865 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3866 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3867 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003868 case OMPD_teams_distribute_parallel_for_simd:
3869 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3870 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3871 AllowedNameModifiers.push_back(OMPD_parallel);
3872 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003873 case OMPD_teams_distribute_parallel_for:
3874 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3875 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3876 AllowedNameModifiers.push_back(OMPD_parallel);
3877 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003878 case OMPD_target_teams:
3879 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3880 EndLoc);
3881 AllowedNameModifiers.push_back(OMPD_target);
3882 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003883 case OMPD_target_teams_distribute:
3884 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3885 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3886 AllowedNameModifiers.push_back(OMPD_target);
3887 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003888 case OMPD_target_teams_distribute_parallel_for:
3889 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3890 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3891 AllowedNameModifiers.push_back(OMPD_target);
3892 AllowedNameModifiers.push_back(OMPD_parallel);
3893 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003894 case OMPD_target_teams_distribute_parallel_for_simd:
3895 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3896 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3897 AllowedNameModifiers.push_back(OMPD_target);
3898 AllowedNameModifiers.push_back(OMPD_parallel);
3899 break;
Kelvin Lida681182017-01-10 18:08:18 +00003900 case OMPD_target_teams_distribute_simd:
3901 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3902 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3903 AllowedNameModifiers.push_back(OMPD_target);
3904 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003905 case OMPD_declare_target:
3906 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003907 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003908 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003909 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003910 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003911 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003912 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003913 llvm_unreachable("OpenMP Directive is not allowed");
3914 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003915 llvm_unreachable("Unknown OpenMP directive");
3916 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003917
Roman Lebedevb5700602019-03-20 16:32:36 +00003918 ErrorFound = Res.isInvalid() || ErrorFound;
3919
Alexey Bataeve3727102018-04-18 15:57:46 +00003920 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003921 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3922 << P.first << P.second->getSourceRange();
3923 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003924 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3925
3926 if (!AllowedNameModifiers.empty())
3927 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3928 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003929
Alexey Bataeved09d242014-05-28 05:53:51 +00003930 if (ErrorFound)
3931 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00003932
3933 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
3934 Res.getAs<OMPExecutableDirective>()
3935 ->getStructuredBlock()
3936 ->setIsOMPStructuredBlock(true);
3937 }
3938
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003939 return Res;
3940}
3941
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003942Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3943 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003944 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003945 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3946 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003947 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003948 assert(Linears.size() == LinModifiers.size());
3949 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003950 if (!DG || DG.get().isNull())
3951 return DeclGroupPtrTy();
3952
3953 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003954 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003955 return DG;
3956 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003957 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003958 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3959 ADecl = FTD->getTemplatedDecl();
3960
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003961 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3962 if (!FD) {
3963 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003964 return DeclGroupPtrTy();
3965 }
3966
Alexey Bataev2af33e32016-04-07 12:45:37 +00003967 // OpenMP [2.8.2, declare simd construct, Description]
3968 // The parameter of the simdlen clause must be a constant positive integer
3969 // expression.
3970 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003971 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003972 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003973 // OpenMP [2.8.2, declare simd construct, Description]
3974 // The special this pointer can be used as if was one of the arguments to the
3975 // function in any of the linear, aligned, or uniform clauses.
3976 // The uniform clause declares one or more arguments to have an invariant
3977 // value for all concurrent invocations of the function in the execution of a
3978 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003979 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3980 const Expr *UniformedLinearThis = nullptr;
3981 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003982 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003983 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3984 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003985 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3986 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003987 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00003988 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003989 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003990 }
3991 if (isa<CXXThisExpr>(E)) {
3992 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003993 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003994 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003995 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3996 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003997 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003998 // OpenMP [2.8.2, declare simd construct, Description]
3999 // The aligned clause declares that the object to which each list item points
4000 // is aligned to the number of bytes expressed in the optional parameter of
4001 // the aligned clause.
4002 // The special this pointer can be used as if was one of the arguments to the
4003 // function in any of the linear, aligned, or uniform clauses.
4004 // The type of list items appearing in the aligned clause must be array,
4005 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004006 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4007 const Expr *AlignedThis = nullptr;
4008 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004009 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004010 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4011 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4012 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004013 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4014 FD->getParamDecl(PVD->getFunctionScopeIndex())
4015 ->getCanonicalDecl() == CanonPVD) {
4016 // OpenMP [2.8.1, simd construct, Restrictions]
4017 // A list-item cannot appear in more than one aligned clause.
4018 if (AlignedArgs.count(CanonPVD) > 0) {
4019 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4020 << 1 << E->getSourceRange();
4021 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4022 diag::note_omp_explicit_dsa)
4023 << getOpenMPClauseName(OMPC_aligned);
4024 continue;
4025 }
4026 AlignedArgs[CanonPVD] = E;
4027 QualType QTy = PVD->getType()
4028 .getNonReferenceType()
4029 .getUnqualifiedType()
4030 .getCanonicalType();
4031 const Type *Ty = QTy.getTypePtrOrNull();
4032 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4033 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4034 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4035 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4036 }
4037 continue;
4038 }
4039 }
4040 if (isa<CXXThisExpr>(E)) {
4041 if (AlignedThis) {
4042 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4043 << 2 << E->getSourceRange();
4044 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4045 << getOpenMPClauseName(OMPC_aligned);
4046 }
4047 AlignedThis = E;
4048 continue;
4049 }
4050 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4051 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4052 }
4053 // The optional parameter of the aligned clause, alignment, must be a constant
4054 // positive integer expression. If no optional parameter is specified,
4055 // implementation-defined default alignments for SIMD instructions on the
4056 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004057 SmallVector<const Expr *, 4> NewAligns;
4058 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004059 ExprResult Align;
4060 if (E)
4061 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4062 NewAligns.push_back(Align.get());
4063 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004064 // OpenMP [2.8.2, declare simd construct, Description]
4065 // The linear clause declares one or more list items to be private to a SIMD
4066 // lane and to have a linear relationship with respect to the iteration space
4067 // of a loop.
4068 // The special this pointer can be used as if was one of the arguments to the
4069 // function in any of the linear, aligned, or uniform clauses.
4070 // When a linear-step expression is specified in a linear clause it must be
4071 // either a constant integer expression or an integer-typed parameter that is
4072 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004073 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004074 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4075 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004076 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004077 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4078 ++MI;
4079 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004080 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4081 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4082 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004083 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4084 FD->getParamDecl(PVD->getFunctionScopeIndex())
4085 ->getCanonicalDecl() == CanonPVD) {
4086 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4087 // A list-item cannot appear in more than one linear clause.
4088 if (LinearArgs.count(CanonPVD) > 0) {
4089 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4090 << getOpenMPClauseName(OMPC_linear)
4091 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4092 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4093 diag::note_omp_explicit_dsa)
4094 << getOpenMPClauseName(OMPC_linear);
4095 continue;
4096 }
4097 // Each argument can appear in at most one uniform or linear clause.
4098 if (UniformedArgs.count(CanonPVD) > 0) {
4099 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4100 << getOpenMPClauseName(OMPC_linear)
4101 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4102 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4103 diag::note_omp_explicit_dsa)
4104 << getOpenMPClauseName(OMPC_uniform);
4105 continue;
4106 }
4107 LinearArgs[CanonPVD] = E;
4108 if (E->isValueDependent() || E->isTypeDependent() ||
4109 E->isInstantiationDependent() ||
4110 E->containsUnexpandedParameterPack())
4111 continue;
4112 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4113 PVD->getOriginalType());
4114 continue;
4115 }
4116 }
4117 if (isa<CXXThisExpr>(E)) {
4118 if (UniformedLinearThis) {
4119 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4120 << getOpenMPClauseName(OMPC_linear)
4121 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4122 << E->getSourceRange();
4123 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4124 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4125 : OMPC_linear);
4126 continue;
4127 }
4128 UniformedLinearThis = E;
4129 if (E->isValueDependent() || E->isTypeDependent() ||
4130 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4131 continue;
4132 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4133 E->getType());
4134 continue;
4135 }
4136 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4137 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4138 }
4139 Expr *Step = nullptr;
4140 Expr *NewStep = nullptr;
4141 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004142 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004143 // Skip the same step expression, it was checked already.
4144 if (Step == E || !E) {
4145 NewSteps.push_back(E ? NewStep : nullptr);
4146 continue;
4147 }
4148 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004149 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4150 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4151 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004152 if (UniformedArgs.count(CanonPVD) == 0) {
4153 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4154 << Step->getSourceRange();
4155 } else if (E->isValueDependent() || E->isTypeDependent() ||
4156 E->isInstantiationDependent() ||
4157 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004158 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004159 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004160 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004161 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4162 << Step->getSourceRange();
4163 }
4164 continue;
4165 }
4166 NewStep = Step;
4167 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4168 !Step->isInstantiationDependent() &&
4169 !Step->containsUnexpandedParameterPack()) {
4170 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4171 .get();
4172 if (NewStep)
4173 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4174 }
4175 NewSteps.push_back(NewStep);
4176 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004177 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4178 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004179 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004180 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4181 const_cast<Expr **>(Linears.data()), Linears.size(),
4182 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4183 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004184 ADecl->addAttr(NewAttr);
4185 return ConvertDeclToDeclGroup(ADecl);
4186}
4187
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004188StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4189 Stmt *AStmt,
4190 SourceLocation StartLoc,
4191 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004192 if (!AStmt)
4193 return StmtError();
4194
Alexey Bataeve3727102018-04-18 15:57:46 +00004195 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004196 // 1.2.2 OpenMP Language Terminology
4197 // Structured block - An executable statement with a single entry at the
4198 // top and a single exit at the bottom.
4199 // The point of exit cannot be a branch out of the structured block.
4200 // longjmp() and throw() must not violate the entry/exit criteria.
4201 CS->getCapturedDecl()->setNothrow();
4202
Reid Kleckner87a31802018-03-12 21:43:02 +00004203 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004204
Alexey Bataev25e5b442015-09-15 12:52:43 +00004205 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4206 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004207}
4208
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004209namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004210/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004211/// extracting iteration space of each loop in the loop nest, that will be used
4212/// for IR generation.
4213class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004214 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004215 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004216 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004217 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004218 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004219 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004220 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004221 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004222 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004223 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004224 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004225 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004226 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004227 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004228 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004229 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004230 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004231 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004232 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004233 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004234 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004235 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004236 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004237 /// Var < UB
4238 /// Var <= UB
4239 /// UB > Var
4240 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004241 /// This will have no value when the condition is !=
4242 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004243 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004244 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004245 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004246 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004247
4248public:
4249 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004250 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004251 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004252 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004253 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004254 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004255 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004256 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004257 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004258 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004259 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004260 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004261 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004262 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004263 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004264 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004265 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004266 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004267 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004268 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004269 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004270 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004271 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004272 /// True, if the compare operator is strict (<, > or !=).
4273 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004274 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004275 Expr *buildNumIterations(
4276 Scope *S, const bool LimitedType,
4277 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004278 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004279 Expr *
4280 buildPreCond(Scope *S, Expr *Cond,
4281 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004282 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004283 DeclRefExpr *
4284 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4285 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004286 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004287 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004288 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004289 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004290 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004291 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004292 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004293 /// Build loop data with counter value for depend clauses in ordered
4294 /// directives.
4295 Expr *
4296 buildOrderedLoopData(Scope *S, Expr *Counter,
4297 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4298 SourceLocation Loc, Expr *Inc = nullptr,
4299 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004300 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004301 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004302
4303private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004304 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004305 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004306 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004307 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004308 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004309 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004310 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4311 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004312 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004313 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004314};
4315
Alexey Bataeve3727102018-04-18 15:57:46 +00004316bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004317 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004318 assert(!LB && !UB && !Step);
4319 return false;
4320 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004321 return LCDecl->getType()->isDependentType() ||
4322 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4323 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004324}
4325
Alexey Bataeve3727102018-04-18 15:57:46 +00004326bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004327 Expr *NewLCRefExpr,
4328 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004329 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004330 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004331 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004332 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004333 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004334 LCDecl = getCanonicalDecl(NewLCDecl);
4335 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004336 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4337 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004338 if ((Ctor->isCopyOrMoveConstructor() ||
4339 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4340 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004341 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004342 LB = NewLB;
4343 return false;
4344}
4345
Alexey Bataev316ccf62019-01-29 18:51:58 +00004346bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4347 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004348 bool StrictOp, SourceRange SR,
4349 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004350 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004351 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4352 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004353 if (!NewUB)
4354 return true;
4355 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004356 if (LessOp)
4357 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004358 TestIsStrictOp = StrictOp;
4359 ConditionSrcRange = SR;
4360 ConditionLoc = SL;
4361 return false;
4362}
4363
Alexey Bataeve3727102018-04-18 15:57:46 +00004364bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004365 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004366 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004367 if (!NewStep)
4368 return true;
4369 if (!NewStep->isValueDependent()) {
4370 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004371 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004372 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4373 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004374 if (Val.isInvalid())
4375 return true;
4376 NewStep = Val.get();
4377
4378 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4379 // If test-expr is of form var relational-op b and relational-op is < or
4380 // <= then incr-expr must cause var to increase on each iteration of the
4381 // loop. If test-expr is of form var relational-op b and relational-op is
4382 // > or >= then incr-expr must cause var to decrease on each iteration of
4383 // the loop.
4384 // If test-expr is of form b relational-op var and relational-op is < or
4385 // <= then incr-expr must cause var to decrease on each iteration of the
4386 // loop. If test-expr is of form b relational-op var and relational-op is
4387 // > or >= then incr-expr must cause var to increase on each iteration of
4388 // the loop.
4389 llvm::APSInt Result;
4390 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4391 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4392 bool IsConstNeg =
4393 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004394 bool IsConstPos =
4395 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004396 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004397
4398 // != with increment is treated as <; != with decrement is treated as >
4399 if (!TestIsLessOp.hasValue())
4400 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004401 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004402 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004403 (IsConstNeg || (IsUnsigned && Subtract)) :
4404 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004405 SemaRef.Diag(NewStep->getExprLoc(),
4406 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004407 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004408 SemaRef.Diag(ConditionLoc,
4409 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004410 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004411 return true;
4412 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004413 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004414 NewStep =
4415 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4416 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004417 Subtract = !Subtract;
4418 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004419 }
4420
4421 Step = NewStep;
4422 SubtractStep = Subtract;
4423 return false;
4424}
4425
Alexey Bataeve3727102018-04-18 15:57:46 +00004426bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004427 // Check init-expr for canonical loop form and save loop counter
4428 // variable - #Var and its initialization value - #LB.
4429 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4430 // var = lb
4431 // integer-type var = lb
4432 // random-access-iterator-type var = lb
4433 // pointer-type var = lb
4434 //
4435 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004436 if (EmitDiags) {
4437 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4438 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004439 return true;
4440 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004441 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4442 if (!ExprTemp->cleanupsHaveSideEffects())
4443 S = ExprTemp->getSubExpr();
4444
Alexander Musmana5f070a2014-10-01 06:03:56 +00004445 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004446 if (Expr *E = dyn_cast<Expr>(S))
4447 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004448 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004449 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004450 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004451 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4452 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4453 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004454 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4455 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004456 }
4457 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4458 if (ME->isArrow() &&
4459 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004460 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004461 }
4462 }
David Majnemer9d168222016-08-05 17:44:54 +00004463 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004464 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004465 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004466 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004467 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004468 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004469 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004470 diag::ext_omp_loop_not_canonical_init)
4471 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004472 return setLCDeclAndLB(
4473 Var,
4474 buildDeclRefExpr(SemaRef, Var,
4475 Var->getType().getNonReferenceType(),
4476 DS->getBeginLoc()),
4477 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004478 }
4479 }
4480 }
David Majnemer9d168222016-08-05 17:44:54 +00004481 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004482 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004483 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004484 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004485 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4486 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004487 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4488 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004489 }
4490 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4491 if (ME->isArrow() &&
4492 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004493 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004494 }
4495 }
4496 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004497
Alexey Bataeve3727102018-04-18 15:57:46 +00004498 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004499 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004500 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004501 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004502 << S->getSourceRange();
4503 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004504 return true;
4505}
4506
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004507/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004508/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004509static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004510 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004511 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004512 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004513 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004514 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004515 if ((Ctor->isCopyOrMoveConstructor() ||
4516 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4517 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004518 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4520 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004521 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004522 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004523 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004524 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4525 return getCanonicalDecl(ME->getMemberDecl());
4526 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004527}
4528
Alexey Bataeve3727102018-04-18 15:57:46 +00004529bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004530 // Check test-expr for canonical form, save upper-bound UB, flags for
4531 // less/greater and for strict/non-strict comparison.
4532 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4533 // var relational-op b
4534 // b relational-op var
4535 //
4536 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004537 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004538 return true;
4539 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004540 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004541 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004542 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004543 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004544 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4545 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004546 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4547 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4548 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004549 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4550 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004551 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4552 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4553 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004554 } else if (BO->getOpcode() == BO_NE)
4555 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4556 BO->getRHS() : BO->getLHS(),
4557 /*LessOp=*/llvm::None,
4558 /*StrictOp=*/true,
4559 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004560 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004561 if (CE->getNumArgs() == 2) {
4562 auto Op = CE->getOperator();
4563 switch (Op) {
4564 case OO_Greater:
4565 case OO_GreaterEqual:
4566 case OO_Less:
4567 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004568 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4569 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004570 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4571 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004572 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4573 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004574 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4575 CE->getOperatorLoc());
4576 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004577 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004578 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4579 CE->getArg(1) : CE->getArg(0),
4580 /*LessOp=*/llvm::None,
4581 /*StrictOp=*/true,
4582 CE->getSourceRange(),
4583 CE->getOperatorLoc());
4584 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004585 default:
4586 break;
4587 }
4588 }
4589 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004590 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004591 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004592 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004593 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004594 return true;
4595}
4596
Alexey Bataeve3727102018-04-18 15:57:46 +00004597bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004598 // RHS of canonical loop form increment can be:
4599 // var + incr
4600 // incr + var
4601 // var - incr
4602 //
4603 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004604 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004605 if (BO->isAdditiveOp()) {
4606 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004607 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4608 return setStep(BO->getRHS(), !IsAdd);
4609 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4610 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004611 }
David Majnemer9d168222016-08-05 17:44:54 +00004612 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004613 bool IsAdd = CE->getOperator() == OO_Plus;
4614 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004615 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4616 return setStep(CE->getArg(1), !IsAdd);
4617 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4618 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004619 }
4620 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004621 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004622 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004623 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004624 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004625 return true;
4626}
4627
Alexey Bataeve3727102018-04-18 15:57:46 +00004628bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004629 // Check incr-expr for canonical loop form and return true if it
4630 // does not conform.
4631 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4632 // ++var
4633 // var++
4634 // --var
4635 // var--
4636 // var += incr
4637 // var -= incr
4638 // var = var + incr
4639 // var = incr + var
4640 // var = var - incr
4641 //
4642 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004643 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004644 return true;
4645 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004646 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4647 if (!ExprTemp->cleanupsHaveSideEffects())
4648 S = ExprTemp->getSubExpr();
4649
Alexander Musmana5f070a2014-10-01 06:03:56 +00004650 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004651 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004652 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004653 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004654 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4655 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004656 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004657 (UO->isDecrementOp() ? -1 : 1))
4658 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004659 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004660 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004661 switch (BO->getOpcode()) {
4662 case BO_AddAssign:
4663 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004664 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4665 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004666 break;
4667 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004668 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4669 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004670 break;
4671 default:
4672 break;
4673 }
David Majnemer9d168222016-08-05 17:44:54 +00004674 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004675 switch (CE->getOperator()) {
4676 case OO_PlusPlus:
4677 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004678 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4679 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004680 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004681 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004682 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4683 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004684 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004685 break;
4686 case OO_PlusEqual:
4687 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004688 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4689 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004690 break;
4691 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004692 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4693 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004694 break;
4695 default:
4696 break;
4697 }
4698 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004699 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004700 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004701 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004702 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004703 return true;
4704}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004705
Alexey Bataev5a3af132016-03-29 08:58:54 +00004706static ExprResult
4707tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004708 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004709 if (SemaRef.CurContext->isDependentContext())
4710 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004711 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4712 return SemaRef.PerformImplicitConversion(
4713 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4714 /*AllowExplicit=*/true);
4715 auto I = Captures.find(Capture);
4716 if (I != Captures.end())
4717 return buildCapture(SemaRef, Capture, I->second);
4718 DeclRefExpr *Ref = nullptr;
4719 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4720 Captures[Capture] = Ref;
4721 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004722}
4723
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004724/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004725Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004726 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004727 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004728 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004729 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004730 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004731 SemaRef.getLangOpts().CPlusPlus) {
4732 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004733 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4734 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004735 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4736 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004737 if (!Upper || !Lower)
4738 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004739
4740 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4741
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004742 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004743 // BuildBinOp already emitted error, this one is to point user to upper
4744 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004745 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004746 << Upper->getSourceRange() << Lower->getSourceRange();
4747 return nullptr;
4748 }
4749 }
4750
4751 if (!Diff.isUsable())
4752 return nullptr;
4753
4754 // Upper - Lower [- 1]
4755 if (TestIsStrictOp)
4756 Diff = SemaRef.BuildBinOp(
4757 S, DefaultLoc, BO_Sub, Diff.get(),
4758 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4759 if (!Diff.isUsable())
4760 return nullptr;
4761
4762 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004763 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004764 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004765 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004766 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004767 if (!Diff.isUsable())
4768 return nullptr;
4769
4770 // Parentheses (for dumping/debugging purposes only).
4771 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4772 if (!Diff.isUsable())
4773 return nullptr;
4774
4775 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004776 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004777 if (!Diff.isUsable())
4778 return nullptr;
4779
Alexander Musman174b3ca2014-10-06 11:16:29 +00004780 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004781 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004782 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004783 bool UseVarType = VarType->hasIntegerRepresentation() &&
4784 C.getTypeSize(Type) > C.getTypeSize(VarType);
4785 if (!Type->isIntegerType() || UseVarType) {
4786 unsigned NewSize =
4787 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4788 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4789 : Type->hasSignedIntegerRepresentation();
4790 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004791 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4792 Diff = SemaRef.PerformImplicitConversion(
4793 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4794 if (!Diff.isUsable())
4795 return nullptr;
4796 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004797 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004798 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004799 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4800 if (NewSize != C.getTypeSize(Type)) {
4801 if (NewSize < C.getTypeSize(Type)) {
4802 assert(NewSize == 64 && "incorrect loop var size");
4803 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4804 << InitSrcRange << ConditionSrcRange;
4805 }
4806 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004807 NewSize, Type->hasSignedIntegerRepresentation() ||
4808 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004809 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4810 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4811 Sema::AA_Converting, true);
4812 if (!Diff.isUsable())
4813 return nullptr;
4814 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004815 }
4816 }
4817
Alexander Musmana5f070a2014-10-01 06:03:56 +00004818 return Diff.get();
4819}
4820
Alexey Bataeve3727102018-04-18 15:57:46 +00004821Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004822 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004823 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004824 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4825 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4826 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004827
Alexey Bataeve3727102018-04-18 15:57:46 +00004828 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4829 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004830 if (!NewLB.isUsable() || !NewUB.isUsable())
4831 return nullptr;
4832
Alexey Bataeve3727102018-04-18 15:57:46 +00004833 ExprResult CondExpr =
4834 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004835 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004836 (TestIsStrictOp ? BO_LT : BO_LE) :
4837 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004838 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004839 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004840 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4841 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004842 CondExpr = SemaRef.PerformImplicitConversion(
4843 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4844 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004845 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004846 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004847 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004848 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4849}
4850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004851/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004852DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004853 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4854 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004855 auto *VD = dyn_cast<VarDecl>(LCDecl);
4856 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004857 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4858 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004859 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004860 const DSAStackTy::DSAVarData Data =
4861 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004862 // If the loop control decl is explicitly marked as private, do not mark it
4863 // as captured again.
4864 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4865 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004866 return Ref;
4867 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00004868 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00004869}
4870
Alexey Bataeve3727102018-04-18 15:57:46 +00004871Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004872 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004873 QualType Type = LCDecl->getType().getNonReferenceType();
4874 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004875 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4876 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4877 isa<VarDecl>(LCDecl)
4878 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4879 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004880 if (PrivateVar->isInvalidDecl())
4881 return nullptr;
4882 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4883 }
4884 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004885}
4886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004887/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004888Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004890/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004891Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004892
Alexey Bataevf138fda2018-08-13 19:04:24 +00004893Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4894 Scope *S, Expr *Counter,
4895 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4896 Expr *Inc, OverloadedOperatorKind OOK) {
4897 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4898 if (!Cnt)
4899 return nullptr;
4900 if (Inc) {
4901 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4902 "Expected only + or - operations for depend clauses.");
4903 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4904 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4905 if (!Cnt)
4906 return nullptr;
4907 }
4908 ExprResult Diff;
4909 QualType VarType = LCDecl->getType().getNonReferenceType();
4910 if (VarType->isIntegerType() || VarType->isPointerType() ||
4911 SemaRef.getLangOpts().CPlusPlus) {
4912 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004913 Expr *Upper = TestIsLessOp.getValue()
4914 ? Cnt
4915 : tryBuildCapture(SemaRef, UB, Captures).get();
4916 Expr *Lower = TestIsLessOp.getValue()
4917 ? tryBuildCapture(SemaRef, LB, Captures).get()
4918 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004919 if (!Upper || !Lower)
4920 return nullptr;
4921
4922 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4923
4924 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4925 // BuildBinOp already emitted error, this one is to point user to upper
4926 // and lower bound, and to tell what is passed to 'operator-'.
4927 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4928 << Upper->getSourceRange() << Lower->getSourceRange();
4929 return nullptr;
4930 }
4931 }
4932
4933 if (!Diff.isUsable())
4934 return nullptr;
4935
4936 // Parentheses (for dumping/debugging purposes only).
4937 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4938 if (!Diff.isUsable())
4939 return nullptr;
4940
4941 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4942 if (!NewStep.isUsable())
4943 return nullptr;
4944 // (Upper - Lower) / Step
4945 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4946 if (!Diff.isUsable())
4947 return nullptr;
4948
4949 return Diff.get();
4950}
4951
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004952/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004953struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004954 /// True if the condition operator is the strict compare operator (<, > or
4955 /// !=).
4956 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004957 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004958 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004959 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004960 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004961 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004962 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004963 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004964 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004965 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004966 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004967 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004968 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004969 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004970 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004971 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004972 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004973 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004974 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004975 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004976 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004977 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004978 SourceRange IncSrcRange;
4979};
4980
Alexey Bataev23b69422014-06-18 07:08:49 +00004981} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004982
Alexey Bataev9c821032015-04-30 04:23:23 +00004983void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4984 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4985 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004986 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4987 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004988 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00004989 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00004990 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004991 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4992 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004993 auto *VD = dyn_cast<VarDecl>(D);
4994 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004995 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004996 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00004997 } else {
4998 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4999 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005000 VD = cast<VarDecl>(Ref->getDecl());
5001 }
5002 }
5003 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005004 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5005 if (LD != D->getCanonicalDecl()) {
5006 DSAStack->resetPossibleLoopCounter();
5007 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5008 MarkDeclarationsReferencedInExpr(
5009 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5010 Var->getType().getNonLValueExprType(Context),
5011 ForLoc, /*RefersToCapture=*/true));
5012 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005013 }
5014 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005015 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005016 }
5017}
5018
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005019/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005020/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005021static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005022 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5023 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005024 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5025 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005026 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005027 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005028 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005029 // OpenMP [2.6, Canonical Loop Form]
5030 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005031 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005032 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005033 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005034 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005035 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005036 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005037 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005038 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5039 SemaRef.Diag(DSA.getConstructLoc(),
5040 diag::note_omp_collapse_ordered_expr)
5041 << 2 << CollapseLoopCountExpr->getSourceRange()
5042 << OrderedLoopCountExpr->getSourceRange();
5043 else if (CollapseLoopCountExpr)
5044 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5045 diag::note_omp_collapse_ordered_expr)
5046 << 0 << CollapseLoopCountExpr->getSourceRange();
5047 else
5048 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5049 diag::note_omp_collapse_ordered_expr)
5050 << 1 << OrderedLoopCountExpr->getSourceRange();
5051 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005052 return true;
5053 }
5054 assert(For->getBody());
5055
5056 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5057
5058 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005059 Stmt *Init = For->getInit();
5060 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005061 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005062
5063 bool HasErrors = false;
5064
5065 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005066 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5067 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005068
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005069 // OpenMP [2.6, Canonical Loop Form]
5070 // Var is one of the following:
5071 // A variable of signed or unsigned integer type.
5072 // For C++, a variable of a random access iterator type.
5073 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005074 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005075 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5076 !VarType->isPointerType() &&
5077 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005078 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005079 << SemaRef.getLangOpts().CPlusPlus;
5080 HasErrors = true;
5081 }
5082
5083 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5084 // a Construct
5085 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5086 // parallel for construct is (are) private.
5087 // The loop iteration variable in the associated for-loop of a simd
5088 // construct with just one associated for-loop is linear with a
5089 // constant-linear-step that is the increment of the associated for-loop.
5090 // Exclude loop var from the list of variables with implicitly defined data
5091 // sharing attributes.
5092 VarsWithImplicitDSA.erase(LCDecl);
5093
5094 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5095 // in a Construct, C/C++].
5096 // The loop iteration variable in the associated for-loop of a simd
5097 // construct with just one associated for-loop may be listed in a linear
5098 // clause with a constant-linear-step that is the increment of the
5099 // associated for-loop.
5100 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5101 // parallel for construct may be listed in a private or lastprivate clause.
5102 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5103 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5104 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005105 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005106 isOpenMPSimdDirective(DKind)
5107 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5108 : OMPC_private;
5109 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5110 DVar.CKind != PredeterminedCKind) ||
5111 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5112 isOpenMPDistributeDirective(DKind)) &&
5113 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5114 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5115 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005116 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005117 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5118 << getOpenMPClauseName(PredeterminedCKind);
5119 if (DVar.RefExpr == nullptr)
5120 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005121 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005122 HasErrors = true;
5123 } else if (LoopDeclRefExpr != nullptr) {
5124 // Make the loop iteration variable private (for worksharing constructs),
5125 // linear (for simd directives with the only one associated loop) or
5126 // lastprivate (for simd directives with several collapsed or ordered
5127 // loops).
5128 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005129 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005130 }
5131
5132 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5133
5134 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005135 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005136
5137 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005138 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005139 }
5140
Alexey Bataeve3727102018-04-18 15:57:46 +00005141 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005142 return HasErrors;
5143
Alexander Musmana5f070a2014-10-01 06:03:56 +00005144 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005145 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005146 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5147 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005148 DSA.getCurScope(),
5149 (isOpenMPWorksharingDirective(DKind) ||
5150 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5151 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005152 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5153 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5154 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5155 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5156 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5157 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5158 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5159 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005160 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005161
Alexey Bataev62dbb972015-04-22 11:59:37 +00005162 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5163 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005164 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005165 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005166 ResultIterSpace.CounterInit == nullptr ||
5167 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005168 if (!HasErrors && DSA.isOrderedRegion()) {
5169 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5170 if (CurrentNestedLoopCount <
5171 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5172 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5173 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5174 DSA.getOrderedRegionParam().second->setLoopCounter(
5175 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5176 }
5177 }
5178 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5179 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5180 // Erroneous case - clause has some problems.
5181 continue;
5182 }
5183 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5184 Pair.second.size() <= CurrentNestedLoopCount) {
5185 // Erroneous case - clause has some problems.
5186 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5187 continue;
5188 }
5189 Expr *CntValue;
5190 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5191 CntValue = ISC.buildOrderedLoopData(
5192 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5193 Pair.first->getDependencyLoc());
5194 else
5195 CntValue = ISC.buildOrderedLoopData(
5196 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5197 Pair.first->getDependencyLoc(),
5198 Pair.second[CurrentNestedLoopCount].first,
5199 Pair.second[CurrentNestedLoopCount].second);
5200 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5201 }
5202 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005203
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005204 return HasErrors;
5205}
5206
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005207/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005208static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005209buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005210 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005211 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005212 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005213 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005214 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005215 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005216 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005217 VarRef.get()->getType())) {
5218 NewStart = SemaRef.PerformImplicitConversion(
5219 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5220 /*AllowExplicit=*/true);
5221 if (!NewStart.isUsable())
5222 return ExprError();
5223 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005224
Alexey Bataeve3727102018-04-18 15:57:46 +00005225 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005226 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5227 return Init;
5228}
5229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005230/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005231static ExprResult buildCounterUpdate(
5232 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5233 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5234 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005235 // Add parentheses (for debugging purposes only).
5236 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5237 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5238 !Step.isUsable())
5239 return ExprError();
5240
Alexey Bataev5a3af132016-03-29 08:58:54 +00005241 ExprResult NewStep = Step;
5242 if (Captures)
5243 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005244 if (NewStep.isInvalid())
5245 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005246 ExprResult Update =
5247 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005248 if (!Update.isUsable())
5249 return ExprError();
5250
Alexey Bataevc0214e02016-02-16 12:13:49 +00005251 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5252 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005253 ExprResult NewStart = Start;
5254 if (Captures)
5255 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005256 if (NewStart.isInvalid())
5257 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005258
Alexey Bataevc0214e02016-02-16 12:13:49 +00005259 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5260 ExprResult SavedUpdate = Update;
5261 ExprResult UpdateVal;
5262 if (VarRef.get()->getType()->isOverloadableType() ||
5263 NewStart.get()->getType()->isOverloadableType() ||
5264 Update.get()->getType()->isOverloadableType()) {
5265 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5266 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5267 Update =
5268 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5269 if (Update.isUsable()) {
5270 UpdateVal =
5271 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5272 VarRef.get(), SavedUpdate.get());
5273 if (UpdateVal.isUsable()) {
5274 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5275 UpdateVal.get());
5276 }
5277 }
5278 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5279 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005280
Alexey Bataevc0214e02016-02-16 12:13:49 +00005281 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5282 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5283 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5284 NewStart.get(), SavedUpdate.get());
5285 if (!Update.isUsable())
5286 return ExprError();
5287
Alexey Bataev11481f52016-02-17 10:29:05 +00005288 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5289 VarRef.get()->getType())) {
5290 Update = SemaRef.PerformImplicitConversion(
5291 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5292 if (!Update.isUsable())
5293 return ExprError();
5294 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005295
5296 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5297 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005298 return Update;
5299}
5300
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005301/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005302/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005303static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005304 if (E == nullptr)
5305 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005306 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005307 QualType OldType = E->getType();
5308 unsigned HasBits = C.getTypeSize(OldType);
5309 if (HasBits >= Bits)
5310 return ExprResult(E);
5311 // OK to convert to signed, because new type has more bits than old.
5312 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5313 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5314 true);
5315}
5316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005317/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005318/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005319static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005320 if (E == nullptr)
5321 return false;
5322 llvm::APSInt Result;
5323 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5324 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5325 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005326}
5327
Alexey Bataev5a3af132016-03-29 08:58:54 +00005328/// Build preinits statement for the given declarations.
5329static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005330 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005331 if (!PreInits.empty()) {
5332 return new (Context) DeclStmt(
5333 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5334 SourceLocation(), SourceLocation());
5335 }
5336 return nullptr;
5337}
5338
5339/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005340static Stmt *
5341buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005342 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005343 if (!Captures.empty()) {
5344 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005345 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005346 PreInits.push_back(Pair.second->getDecl());
5347 return buildPreInits(Context, PreInits);
5348 }
5349 return nullptr;
5350}
5351
5352/// Build postupdate expression for the given list of postupdates expressions.
5353static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5354 Expr *PostUpdate = nullptr;
5355 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005356 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005357 Expr *ConvE = S.BuildCStyleCastExpr(
5358 E->getExprLoc(),
5359 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5360 E->getExprLoc(), E)
5361 .get();
5362 PostUpdate = PostUpdate
5363 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5364 PostUpdate, ConvE)
5365 .get()
5366 : ConvE;
5367 }
5368 }
5369 return PostUpdate;
5370}
5371
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005372/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005373/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5374/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005375static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005376checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005377 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5378 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005379 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005380 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005381 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005382 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005383 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005384 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005385 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005386 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005387 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005388 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005389 if (OrderedLoopCountExpr) {
5390 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005391 Expr::EvalResult EVResult;
5392 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5393 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005394 if (Result.getLimitedValue() < NestedLoopCount) {
5395 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5396 diag::err_omp_wrong_ordered_loop_count)
5397 << OrderedLoopCountExpr->getSourceRange();
5398 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5399 diag::note_collapse_loop_count)
5400 << CollapseLoopCountExpr->getSourceRange();
5401 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005402 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005403 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005404 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005405 // This is helper routine for loop directives (e.g., 'for', 'simd',
5406 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005407 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005408 SmallVector<LoopIterationSpace, 4> IterSpaces(
5409 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005410 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005411 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005412 if (checkOpenMPIterationSpace(
5413 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5414 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5415 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5416 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005417 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005418 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005419 // OpenMP [2.8.1, simd construct, Restrictions]
5420 // All loops associated with the construct must be perfectly nested; that
5421 // is, there must be no intervening code nor any OpenMP directive between
5422 // any two loops.
5423 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005424 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005425 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5426 if (checkOpenMPIterationSpace(
5427 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5428 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5429 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5430 Captures))
5431 return 0;
5432 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5433 // Handle initialization of captured loop iterator variables.
5434 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5435 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5436 Captures[DRE] = DRE;
5437 }
5438 }
5439 // Move on to the next nested for loop, or to the loop body.
5440 // OpenMP [2.8.1, simd construct, Restrictions]
5441 // All loops associated with the construct must be perfectly nested; that
5442 // is, there must be no intervening code nor any OpenMP directive between
5443 // any two loops.
5444 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5445 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005446
Alexander Musmana5f070a2014-10-01 06:03:56 +00005447 Built.clear(/* size */ NestedLoopCount);
5448
5449 if (SemaRef.CurContext->isDependentContext())
5450 return NestedLoopCount;
5451
5452 // An example of what is generated for the following code:
5453 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005454 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005455 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005456 // for (k = 0; k < NK; ++k)
5457 // for (j = J0; j < NJ; j+=2) {
5458 // <loop body>
5459 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005460 //
5461 // We generate the code below.
5462 // Note: the loop body may be outlined in CodeGen.
5463 // Note: some counters may be C++ classes, operator- is used to find number of
5464 // iterations and operator+= to calculate counter value.
5465 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5466 // or i64 is currently supported).
5467 //
5468 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5469 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5470 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5471 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5472 // // similar updates for vars in clauses (e.g. 'linear')
5473 // <loop body (using local i and j)>
5474 // }
5475 // i = NI; // assign final values of counters
5476 // j = NJ;
5477 //
5478
5479 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5480 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005481 // Precondition tests if there is at least one iteration (all conditions are
5482 // true).
5483 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005484 Expr *N0 = IterSpaces[0].NumIterations;
5485 ExprResult LastIteration32 =
5486 widenIterationCount(/*Bits=*/32,
5487 SemaRef
5488 .PerformImplicitConversion(
5489 N0->IgnoreImpCasts(), N0->getType(),
5490 Sema::AA_Converting, /*AllowExplicit=*/true)
5491 .get(),
5492 SemaRef);
5493 ExprResult LastIteration64 = widenIterationCount(
5494 /*Bits=*/64,
5495 SemaRef
5496 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5497 Sema::AA_Converting,
5498 /*AllowExplicit=*/true)
5499 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005500 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005501
5502 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5503 return NestedLoopCount;
5504
Alexey Bataeve3727102018-04-18 15:57:46 +00005505 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005506 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5507
5508 Scope *CurScope = DSA.getCurScope();
5509 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005510 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005511 PreCond =
5512 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5513 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005514 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005515 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005516 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005517 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5518 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005519 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005520 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005521 SemaRef
5522 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5523 Sema::AA_Converting,
5524 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005525 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005526 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005527 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005528 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005529 SemaRef
5530 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5531 Sema::AA_Converting,
5532 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005533 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005534 }
5535
5536 // Choose either the 32-bit or 64-bit version.
5537 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005538 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5539 (LastIteration32.isUsable() &&
5540 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5541 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5542 fitsInto(
5543 /*Bits=*/32,
5544 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5545 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005546 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005547 QualType VType = LastIteration.get()->getType();
5548 QualType RealVType = VType;
5549 QualType StrideVType = VType;
5550 if (isOpenMPTaskLoopDirective(DKind)) {
5551 VType =
5552 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5553 StrideVType =
5554 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5555 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005556
5557 if (!LastIteration.isUsable())
5558 return 0;
5559
5560 // Save the number of iterations.
5561 ExprResult NumIterations = LastIteration;
5562 {
5563 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005564 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5565 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005566 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5567 if (!LastIteration.isUsable())
5568 return 0;
5569 }
5570
5571 // Calculate the last iteration number beforehand instead of doing this on
5572 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5573 llvm::APSInt Result;
5574 bool IsConstant =
5575 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5576 ExprResult CalcLastIteration;
5577 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005578 ExprResult SaveRef =
5579 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005580 LastIteration = SaveRef;
5581
5582 // Prepare SaveRef + 1.
5583 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005584 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005585 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5586 if (!NumIterations.isUsable())
5587 return 0;
5588 }
5589
5590 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5591
David Majnemer9d168222016-08-05 17:44:54 +00005592 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005593 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005594 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5595 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005596 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005597 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5598 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005599 SemaRef.AddInitializerToDecl(LBDecl,
5600 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5601 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005602
5603 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005604 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5605 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005606 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005607 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005608
5609 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5610 // This will be used to implement clause 'lastprivate'.
5611 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005612 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5613 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005614 SemaRef.AddInitializerToDecl(ILDecl,
5615 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5616 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005617
5618 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005619 VarDecl *STDecl =
5620 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5621 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005622 SemaRef.AddInitializerToDecl(STDecl,
5623 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5624 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005625
5626 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005627 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005628 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5629 UB.get(), LastIteration.get());
5630 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005631 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5632 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005633 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5634 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005635 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005636
5637 // If we have a combined directive that combines 'distribute', 'for' or
5638 // 'simd' we need to be able to access the bounds of the schedule of the
5639 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5640 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5641 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005642 // Lower bound variable, initialized with zero.
5643 VarDecl *CombLBDecl =
5644 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5645 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5646 SemaRef.AddInitializerToDecl(
5647 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5648 /*DirectInit*/ false);
5649
5650 // Upper bound variable, initialized with last iteration number.
5651 VarDecl *CombUBDecl =
5652 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5653 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5654 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5655 /*DirectInit*/ false);
5656
5657 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5658 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5659 ExprResult CombCondOp =
5660 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5661 LastIteration.get(), CombUB.get());
5662 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5663 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005664 CombEUB =
5665 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005666
Alexey Bataeve3727102018-04-18 15:57:46 +00005667 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005668 // We expect to have at least 2 more parameters than the 'parallel'
5669 // directive does - the lower and upper bounds of the previous schedule.
5670 assert(CD->getNumParams() >= 4 &&
5671 "Unexpected number of parameters in loop combined directive");
5672
5673 // Set the proper type for the bounds given what we learned from the
5674 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005675 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5676 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005677
5678 // Previous lower and upper bounds are obtained from the region
5679 // parameters.
5680 PrevLB =
5681 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5682 PrevUB =
5683 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5684 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005685 }
5686
5687 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005688 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005689 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005690 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005691 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5692 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005693 Expr *RHS =
5694 (isOpenMPWorksharingDirective(DKind) ||
5695 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5696 ? LB.get()
5697 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005698 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005699 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005700
5701 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5702 Expr *CombRHS =
5703 (isOpenMPWorksharingDirective(DKind) ||
5704 isOpenMPTaskLoopDirective(DKind) ||
5705 isOpenMPDistributeDirective(DKind))
5706 ? CombLB.get()
5707 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5708 CombInit =
5709 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005710 CombInit =
5711 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005712 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005713 }
5714
Alexey Bataev316ccf62019-01-29 18:51:58 +00005715 bool UseStrictCompare =
5716 RealVType->hasUnsignedIntegerRepresentation() &&
5717 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5718 return LIS.IsStrictCompare;
5719 });
5720 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5721 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005722 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005723 Expr *BoundUB = UB.get();
5724 if (UseStrictCompare) {
5725 BoundUB =
5726 SemaRef
5727 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5728 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5729 .get();
5730 BoundUB =
5731 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5732 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005733 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005734 (isOpenMPWorksharingDirective(DKind) ||
5735 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005736 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5737 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5738 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005739 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5740 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005741 ExprResult CombDistCond;
5742 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005743 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5744 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005745 }
5746
Carlo Bertolliffafe102017-04-20 00:39:39 +00005747 ExprResult CombCond;
5748 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005749 Expr *BoundCombUB = CombUB.get();
5750 if (UseStrictCompare) {
5751 BoundCombUB =
5752 SemaRef
5753 .BuildBinOp(
5754 CurScope, CondLoc, BO_Add, BoundCombUB,
5755 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5756 .get();
5757 BoundCombUB =
5758 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5759 .get();
5760 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005761 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005762 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5763 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005764 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005765 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005766 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005767 ExprResult Inc =
5768 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5769 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5770 if (!Inc.isUsable())
5771 return 0;
5772 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005773 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005774 if (!Inc.isUsable())
5775 return 0;
5776
5777 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5778 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005779 // In combined construct, add combined version that use CombLB and CombUB
5780 // base variables for the update
5781 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005782 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5783 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005784 // LB + ST
5785 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5786 if (!NextLB.isUsable())
5787 return 0;
5788 // LB = LB + ST
5789 NextLB =
5790 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005791 NextLB =
5792 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005793 if (!NextLB.isUsable())
5794 return 0;
5795 // UB + ST
5796 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5797 if (!NextUB.isUsable())
5798 return 0;
5799 // UB = UB + ST
5800 NextUB =
5801 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005802 NextUB =
5803 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005804 if (!NextUB.isUsable())
5805 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005806 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5807 CombNextLB =
5808 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5809 if (!NextLB.isUsable())
5810 return 0;
5811 // LB = LB + ST
5812 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5813 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005814 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5815 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005816 if (!CombNextLB.isUsable())
5817 return 0;
5818 // UB + ST
5819 CombNextUB =
5820 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5821 if (!CombNextUB.isUsable())
5822 return 0;
5823 // UB = UB + ST
5824 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5825 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005826 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5827 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005828 if (!CombNextUB.isUsable())
5829 return 0;
5830 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005831 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005832
Carlo Bertolliffafe102017-04-20 00:39:39 +00005833 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005834 // directive with for as IV = IV + ST; ensure upper bound expression based
5835 // on PrevUB instead of NumIterations - used to implement 'for' when found
5836 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005837 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005838 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005839 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005840 DistCond = SemaRef.BuildBinOp(
5841 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005842 assert(DistCond.isUsable() && "distribute cond expr was not built");
5843
5844 DistInc =
5845 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5846 assert(DistInc.isUsable() && "distribute inc expr was not built");
5847 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5848 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005849 DistInc =
5850 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005851 assert(DistInc.isUsable() && "distribute inc expr was not built");
5852
5853 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5854 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005855 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005856 ExprResult IsUBGreater =
5857 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5858 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5859 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5860 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5861 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005862 PrevEUB =
5863 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005864
Alexey Bataev316ccf62019-01-29 18:51:58 +00005865 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5866 // parallel for is in combination with a distribute directive with
5867 // schedule(static, 1)
5868 Expr *BoundPrevUB = PrevUB.get();
5869 if (UseStrictCompare) {
5870 BoundPrevUB =
5871 SemaRef
5872 .BuildBinOp(
5873 CurScope, CondLoc, BO_Add, BoundPrevUB,
5874 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5875 .get();
5876 BoundPrevUB =
5877 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5878 .get();
5879 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005880 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005881 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5882 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005883 }
5884
Alexander Musmana5f070a2014-10-01 06:03:56 +00005885 // Build updates and final values of the loop counters.
5886 bool HasErrors = false;
5887 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005888 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005889 Built.Updates.resize(NestedLoopCount);
5890 Built.Finals.resize(NestedLoopCount);
5891 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005892 // We implement the following algorithm for obtaining the
5893 // original loop iteration variable values based on the
5894 // value of the collapsed loop iteration variable IV.
5895 //
5896 // Let n+1 be the number of collapsed loops in the nest.
5897 // Iteration variables (I0, I1, .... In)
5898 // Iteration counts (N0, N1, ... Nn)
5899 //
5900 // Acc = IV;
5901 //
5902 // To compute Ik for loop k, 0 <= k <= n, generate:
5903 // Prod = N(k+1) * N(k+2) * ... * Nn;
5904 // Ik = Acc / Prod;
5905 // Acc -= Ik * Prod;
5906 //
5907 ExprResult Acc = IV;
5908 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005909 LoopIterationSpace &IS = IterSpaces[Cnt];
5910 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005911 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005912
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005913 // Compute prod
5914 ExprResult Prod =
5915 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5916 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5917 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5918 IterSpaces[K].NumIterations);
5919
5920 // Iter = Acc / Prod
5921 // If there is at least one more inner loop to avoid
5922 // multiplication by 1.
5923 if (Cnt + 1 < NestedLoopCount)
5924 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5925 Acc.get(), Prod.get());
5926 else
5927 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005928 if (!Iter.isUsable()) {
5929 HasErrors = true;
5930 break;
5931 }
5932
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005933 // Update Acc:
5934 // Acc -= Iter * Prod
5935 // Check if there is at least one more inner loop to avoid
5936 // multiplication by 1.
5937 if (Cnt + 1 < NestedLoopCount)
5938 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5939 Iter.get(), Prod.get());
5940 else
5941 Prod = Iter;
5942 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5943 Acc.get(), Prod.get());
5944
Alexey Bataev39f915b82015-05-08 10:41:21 +00005945 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005946 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005947 DeclRefExpr *CounterVar = buildDeclRefExpr(
5948 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5949 /*RefersToCapture=*/true);
5950 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005951 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005952 if (!Init.isUsable()) {
5953 HasErrors = true;
5954 break;
5955 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005956 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005957 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5958 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005959 if (!Update.isUsable()) {
5960 HasErrors = true;
5961 break;
5962 }
5963
5964 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005965 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005966 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005967 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005968 if (!Final.isUsable()) {
5969 HasErrors = true;
5970 break;
5971 }
5972
Alexander Musmana5f070a2014-10-01 06:03:56 +00005973 if (!Update.isUsable() || !Final.isUsable()) {
5974 HasErrors = true;
5975 break;
5976 }
5977 // Save results
5978 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005979 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005980 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005981 Built.Updates[Cnt] = Update.get();
5982 Built.Finals[Cnt] = Final.get();
5983 }
5984 }
5985
5986 if (HasErrors)
5987 return 0;
5988
5989 // Save results
5990 Built.IterationVarRef = IV.get();
5991 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005992 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005993 Built.CalcLastIteration = SemaRef
5994 .ActOnFinishFullExpr(CalcLastIteration.get(),
5995 /*DiscardedValue*/ false)
5996 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005997 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005998 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005999 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006000 Built.Init = Init.get();
6001 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006002 Built.LB = LB.get();
6003 Built.UB = UB.get();
6004 Built.IL = IL.get();
6005 Built.ST = ST.get();
6006 Built.EUB = EUB.get();
6007 Built.NLB = NextLB.get();
6008 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006009 Built.PrevLB = PrevLB.get();
6010 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006011 Built.DistInc = DistInc.get();
6012 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006013 Built.DistCombinedFields.LB = CombLB.get();
6014 Built.DistCombinedFields.UB = CombUB.get();
6015 Built.DistCombinedFields.EUB = CombEUB.get();
6016 Built.DistCombinedFields.Init = CombInit.get();
6017 Built.DistCombinedFields.Cond = CombCond.get();
6018 Built.DistCombinedFields.NLB = CombNextLB.get();
6019 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006020 Built.DistCombinedFields.DistCond = CombDistCond.get();
6021 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006022
Alexey Bataevabfc0692014-06-25 06:52:00 +00006023 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006024}
6025
Alexey Bataev10e775f2015-07-30 11:36:16 +00006026static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006027 auto CollapseClauses =
6028 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6029 if (CollapseClauses.begin() != CollapseClauses.end())
6030 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006031 return nullptr;
6032}
6033
Alexey Bataev10e775f2015-07-30 11:36:16 +00006034static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006035 auto OrderedClauses =
6036 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6037 if (OrderedClauses.begin() != OrderedClauses.end())
6038 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006039 return nullptr;
6040}
6041
Kelvin Lic5609492016-07-15 04:39:07 +00006042static bool checkSimdlenSafelenSpecified(Sema &S,
6043 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006044 const OMPSafelenClause *Safelen = nullptr;
6045 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006046
Alexey Bataeve3727102018-04-18 15:57:46 +00006047 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006048 if (Clause->getClauseKind() == OMPC_safelen)
6049 Safelen = cast<OMPSafelenClause>(Clause);
6050 else if (Clause->getClauseKind() == OMPC_simdlen)
6051 Simdlen = cast<OMPSimdlenClause>(Clause);
6052 if (Safelen && Simdlen)
6053 break;
6054 }
6055
6056 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006057 const Expr *SimdlenLength = Simdlen->getSimdlen();
6058 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006059 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6060 SimdlenLength->isInstantiationDependent() ||
6061 SimdlenLength->containsUnexpandedParameterPack())
6062 return false;
6063 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6064 SafelenLength->isInstantiationDependent() ||
6065 SafelenLength->containsUnexpandedParameterPack())
6066 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006067 Expr::EvalResult SimdlenResult, SafelenResult;
6068 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6069 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6070 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6071 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006072 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6073 // If both simdlen and safelen clauses are specified, the value of the
6074 // simdlen parameter must be less than or equal to the value of the safelen
6075 // parameter.
6076 if (SimdlenRes > SafelenRes) {
6077 S.Diag(SimdlenLength->getExprLoc(),
6078 diag::err_omp_wrong_simdlen_safelen_values)
6079 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6080 return true;
6081 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006082 }
6083 return false;
6084}
6085
Alexey Bataeve3727102018-04-18 15:57:46 +00006086StmtResult
6087Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6088 SourceLocation StartLoc, SourceLocation EndLoc,
6089 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006090 if (!AStmt)
6091 return StmtError();
6092
6093 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006094 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006095 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6096 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006097 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006098 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6099 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006100 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006101 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006102
Alexander Musmana5f070a2014-10-01 06:03:56 +00006103 assert((CurContext->isDependentContext() || B.builtAll()) &&
6104 "omp simd loop exprs were not built");
6105
Alexander Musman3276a272015-03-21 10:12:56 +00006106 if (!CurContext->isDependentContext()) {
6107 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006108 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006109 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006110 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006111 B.NumIterations, *this, CurScope,
6112 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006113 return StmtError();
6114 }
6115 }
6116
Kelvin Lic5609492016-07-15 04:39:07 +00006117 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006118 return StmtError();
6119
Reid Kleckner87a31802018-03-12 21:43:02 +00006120 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006121 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6122 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006123}
6124
Alexey Bataeve3727102018-04-18 15:57:46 +00006125StmtResult
6126Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6127 SourceLocation StartLoc, SourceLocation EndLoc,
6128 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006129 if (!AStmt)
6130 return StmtError();
6131
6132 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006133 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006134 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6135 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006136 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006137 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6138 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006139 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006140 return StmtError();
6141
Alexander Musmana5f070a2014-10-01 06:03:56 +00006142 assert((CurContext->isDependentContext() || B.builtAll()) &&
6143 "omp for loop exprs were not built");
6144
Alexey Bataev54acd402015-08-04 11:18:19 +00006145 if (!CurContext->isDependentContext()) {
6146 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006147 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006148 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006149 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006150 B.NumIterations, *this, CurScope,
6151 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006152 return StmtError();
6153 }
6154 }
6155
Reid Kleckner87a31802018-03-12 21:43:02 +00006156 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006157 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006158 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006159}
6160
Alexander Musmanf82886e2014-09-18 05:12:34 +00006161StmtResult Sema::ActOnOpenMPForSimdDirective(
6162 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006163 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006164 if (!AStmt)
6165 return StmtError();
6166
6167 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006168 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006169 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6170 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006171 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006172 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006173 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6174 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006175 if (NestedLoopCount == 0)
6176 return StmtError();
6177
Alexander Musmanc6388682014-12-15 07:07:06 +00006178 assert((CurContext->isDependentContext() || B.builtAll()) &&
6179 "omp for simd loop exprs were not built");
6180
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006181 if (!CurContext->isDependentContext()) {
6182 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006183 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006184 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006185 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006186 B.NumIterations, *this, CurScope,
6187 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006188 return StmtError();
6189 }
6190 }
6191
Kelvin Lic5609492016-07-15 04:39:07 +00006192 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006193 return StmtError();
6194
Reid Kleckner87a31802018-03-12 21:43:02 +00006195 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006196 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6197 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006198}
6199
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006200StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6201 Stmt *AStmt,
6202 SourceLocation StartLoc,
6203 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006204 if (!AStmt)
6205 return StmtError();
6206
6207 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006208 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006209 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006210 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006211 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006212 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006213 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006214 return StmtError();
6215 // All associated statements must be '#pragma omp section' except for
6216 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006217 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006218 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6219 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006220 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006221 diag::err_omp_sections_substmt_not_section);
6222 return StmtError();
6223 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006224 cast<OMPSectionDirective>(SectionStmt)
6225 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006226 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006227 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006228 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006229 return StmtError();
6230 }
6231
Reid Kleckner87a31802018-03-12 21:43:02 +00006232 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006233
Alexey Bataev25e5b442015-09-15 12:52:43 +00006234 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6235 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006236}
6237
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006238StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6239 SourceLocation StartLoc,
6240 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006241 if (!AStmt)
6242 return StmtError();
6243
6244 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006245
Reid Kleckner87a31802018-03-12 21:43:02 +00006246 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006247 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006248
Alexey Bataev25e5b442015-09-15 12:52:43 +00006249 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6250 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006251}
6252
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006253StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6254 Stmt *AStmt,
6255 SourceLocation StartLoc,
6256 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006257 if (!AStmt)
6258 return StmtError();
6259
6260 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006261
Reid Kleckner87a31802018-03-12 21:43:02 +00006262 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006263
Alexey Bataev3255bf32015-01-19 05:20:46 +00006264 // OpenMP [2.7.3, single Construct, Restrictions]
6265 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006266 const OMPClause *Nowait = nullptr;
6267 const OMPClause *Copyprivate = nullptr;
6268 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006269 if (Clause->getClauseKind() == OMPC_nowait)
6270 Nowait = Clause;
6271 else if (Clause->getClauseKind() == OMPC_copyprivate)
6272 Copyprivate = Clause;
6273 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006274 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006275 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006276 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006277 return StmtError();
6278 }
6279 }
6280
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006281 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6282}
6283
Alexander Musman80c22892014-07-17 08:54:58 +00006284StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6285 SourceLocation StartLoc,
6286 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006287 if (!AStmt)
6288 return StmtError();
6289
6290 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006291
Reid Kleckner87a31802018-03-12 21:43:02 +00006292 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006293
6294 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6295}
6296
Alexey Bataev28c75412015-12-15 08:19:24 +00006297StmtResult Sema::ActOnOpenMPCriticalDirective(
6298 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6299 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006300 if (!AStmt)
6301 return StmtError();
6302
6303 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006304
Alexey Bataev28c75412015-12-15 08:19:24 +00006305 bool ErrorFound = false;
6306 llvm::APSInt Hint;
6307 SourceLocation HintLoc;
6308 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006309 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006310 if (C->getClauseKind() == OMPC_hint) {
6311 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006312 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006313 ErrorFound = true;
6314 }
6315 Expr *E = cast<OMPHintClause>(C)->getHint();
6316 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006317 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006318 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006319 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006320 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006321 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006322 }
6323 }
6324 }
6325 if (ErrorFound)
6326 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006327 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006328 if (Pair.first && DirName.getName() && !DependentHint) {
6329 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6330 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006331 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006332 Diag(HintLoc, diag::note_omp_critical_hint_here)
6333 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006334 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006335 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006336 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006337 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006338 << 1
6339 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6340 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006341 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006342 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006343 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006344 }
6345 }
6346
Reid Kleckner87a31802018-03-12 21:43:02 +00006347 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006348
Alexey Bataev28c75412015-12-15 08:19:24 +00006349 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6350 Clauses, AStmt);
6351 if (!Pair.first && DirName.getName() && !DependentHint)
6352 DSAStack->addCriticalWithHint(Dir, Hint);
6353 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006354}
6355
Alexey Bataev4acb8592014-07-07 13:01:15 +00006356StmtResult Sema::ActOnOpenMPParallelForDirective(
6357 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006358 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006359 if (!AStmt)
6360 return StmtError();
6361
Alexey Bataeve3727102018-04-18 15:57:46 +00006362 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006363 // 1.2.2 OpenMP Language Terminology
6364 // Structured block - An executable statement with a single entry at the
6365 // top and a single exit at the bottom.
6366 // The point of exit cannot be a branch out of the structured block.
6367 // longjmp() and throw() must not violate the entry/exit criteria.
6368 CS->getCapturedDecl()->setNothrow();
6369
Alexander Musmanc6388682014-12-15 07:07:06 +00006370 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006371 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6372 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006373 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006374 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006375 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6376 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006377 if (NestedLoopCount == 0)
6378 return StmtError();
6379
Alexander Musmana5f070a2014-10-01 06:03:56 +00006380 assert((CurContext->isDependentContext() || B.builtAll()) &&
6381 "omp parallel for loop exprs were not built");
6382
Alexey Bataev54acd402015-08-04 11:18:19 +00006383 if (!CurContext->isDependentContext()) {
6384 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006385 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006386 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006387 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006388 B.NumIterations, *this, CurScope,
6389 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006390 return StmtError();
6391 }
6392 }
6393
Reid Kleckner87a31802018-03-12 21:43:02 +00006394 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006395 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006396 NestedLoopCount, Clauses, AStmt, B,
6397 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006398}
6399
Alexander Musmane4e893b2014-09-23 09:33:00 +00006400StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6401 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006402 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006403 if (!AStmt)
6404 return StmtError();
6405
Alexey Bataeve3727102018-04-18 15:57:46 +00006406 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006407 // 1.2.2 OpenMP Language Terminology
6408 // Structured block - An executable statement with a single entry at the
6409 // top and a single exit at the bottom.
6410 // The point of exit cannot be a branch out of the structured block.
6411 // longjmp() and throw() must not violate the entry/exit criteria.
6412 CS->getCapturedDecl()->setNothrow();
6413
Alexander Musmanc6388682014-12-15 07:07:06 +00006414 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006415 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6416 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006417 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006418 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006419 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6420 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006421 if (NestedLoopCount == 0)
6422 return StmtError();
6423
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006424 if (!CurContext->isDependentContext()) {
6425 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006426 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006427 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006428 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006429 B.NumIterations, *this, CurScope,
6430 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006431 return StmtError();
6432 }
6433 }
6434
Kelvin Lic5609492016-07-15 04:39:07 +00006435 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006436 return StmtError();
6437
Reid Kleckner87a31802018-03-12 21:43:02 +00006438 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006439 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006440 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006441}
6442
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006443StmtResult
6444Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6445 Stmt *AStmt, SourceLocation StartLoc,
6446 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006447 if (!AStmt)
6448 return StmtError();
6449
6450 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006451 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006452 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006453 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006454 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006455 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006456 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006457 return StmtError();
6458 // All associated statements must be '#pragma omp section' except for
6459 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006460 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006461 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6462 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006463 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006464 diag::err_omp_parallel_sections_substmt_not_section);
6465 return StmtError();
6466 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006467 cast<OMPSectionDirective>(SectionStmt)
6468 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006469 }
6470 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006471 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006472 diag::err_omp_parallel_sections_not_compound_stmt);
6473 return StmtError();
6474 }
6475
Reid Kleckner87a31802018-03-12 21:43:02 +00006476 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006477
Alexey Bataev25e5b442015-09-15 12:52:43 +00006478 return OMPParallelSectionsDirective::Create(
6479 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006480}
6481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006482StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6483 Stmt *AStmt, SourceLocation StartLoc,
6484 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006485 if (!AStmt)
6486 return StmtError();
6487
David Majnemer9d168222016-08-05 17:44:54 +00006488 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006489 // 1.2.2 OpenMP Language Terminology
6490 // Structured block - An executable statement with a single entry at the
6491 // top and a single exit at the bottom.
6492 // The point of exit cannot be a branch out of the structured block.
6493 // longjmp() and throw() must not violate the entry/exit criteria.
6494 CS->getCapturedDecl()->setNothrow();
6495
Reid Kleckner87a31802018-03-12 21:43:02 +00006496 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006497
Alexey Bataev25e5b442015-09-15 12:52:43 +00006498 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6499 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006500}
6501
Alexey Bataev68446b72014-07-18 07:47:19 +00006502StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6503 SourceLocation EndLoc) {
6504 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6505}
6506
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006507StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6508 SourceLocation EndLoc) {
6509 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6510}
6511
Alexey Bataev2df347a2014-07-18 10:17:07 +00006512StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6513 SourceLocation EndLoc) {
6514 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6515}
6516
Alexey Bataev169d96a2017-07-18 20:17:46 +00006517StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6518 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006519 SourceLocation StartLoc,
6520 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006521 if (!AStmt)
6522 return StmtError();
6523
6524 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006525
Reid Kleckner87a31802018-03-12 21:43:02 +00006526 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006527
Alexey Bataev169d96a2017-07-18 20:17:46 +00006528 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006529 AStmt,
6530 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006531}
6532
Alexey Bataev6125da92014-07-21 11:26:11 +00006533StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6534 SourceLocation StartLoc,
6535 SourceLocation EndLoc) {
6536 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6537 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6538}
6539
Alexey Bataev346265e2015-09-25 10:37:12 +00006540StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6541 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006542 SourceLocation StartLoc,
6543 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006544 const OMPClause *DependFound = nullptr;
6545 const OMPClause *DependSourceClause = nullptr;
6546 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006547 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006548 const OMPThreadsClause *TC = nullptr;
6549 const OMPSIMDClause *SC = nullptr;
6550 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006551 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6552 DependFound = C;
6553 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6554 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006555 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006556 << getOpenMPDirectiveName(OMPD_ordered)
6557 << getOpenMPClauseName(OMPC_depend) << 2;
6558 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006559 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006560 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006561 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006562 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006563 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006564 << 0;
6565 ErrorFound = true;
6566 }
6567 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6568 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006569 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006570 << 1;
6571 ErrorFound = true;
6572 }
6573 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006574 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006575 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006576 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006577 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006578 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006579 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006580 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006581 if (!ErrorFound && !SC &&
6582 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006583 // OpenMP [2.8.1,simd Construct, Restrictions]
6584 // An ordered construct with the simd clause is the only OpenMP construct
6585 // that can appear in the simd region.
6586 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006587 ErrorFound = true;
6588 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006589 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006590 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6591 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006592 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006593 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006594 diag::err_omp_ordered_directive_without_param);
6595 ErrorFound = true;
6596 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006597 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006598 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006599 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6600 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006601 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006602 ErrorFound = true;
6603 }
6604 }
6605 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006606 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006607
6608 if (AStmt) {
6609 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6610
Reid Kleckner87a31802018-03-12 21:43:02 +00006611 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006612 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006613
6614 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006615}
6616
Alexey Bataev1d160b12015-03-13 12:27:31 +00006617namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006618/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006619/// construct.
6620class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006621 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006622 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006623 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006624 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006625 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006626 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006627 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006628 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006629 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006630 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006631 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006632 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006633 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006634 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006635 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006636 /// expression.
6637 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006638 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006639 /// part.
6640 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006641 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006642 NoError
6643 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006644 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006645 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006646 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006647 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006648 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006649 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006650 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006651 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006652 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006653 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6654 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6655 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006656 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006657 /// important for non-associative operations.
6658 bool IsXLHSInRHSPart;
6659 BinaryOperatorKind Op;
6660 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006661 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006662 /// if it is a prefix unary operation.
6663 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006664
6665public:
6666 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006667 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006668 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006669 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006670 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006671 /// expression. If DiagId and NoteId == 0, then only check is performed
6672 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006673 /// \param DiagId Diagnostic which should be emitted if error is found.
6674 /// \param NoteId Diagnostic note for the main error message.
6675 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006676 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006677 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006678 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006679 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006680 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006681 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006682 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6683 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6684 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006685 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006686 /// false otherwise.
6687 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6688
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006689 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006690 /// if it is a prefix unary operation.
6691 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6692
Alexey Bataev1d160b12015-03-13 12:27:31 +00006693private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006694 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6695 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006696};
6697} // namespace
6698
6699bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6700 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6701 ExprAnalysisErrorCode ErrorFound = NoError;
6702 SourceLocation ErrorLoc, NoteLoc;
6703 SourceRange ErrorRange, NoteRange;
6704 // Allowed constructs are:
6705 // x = x binop expr;
6706 // x = expr binop x;
6707 if (AtomicBinOp->getOpcode() == BO_Assign) {
6708 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006709 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006710 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6711 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6712 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6713 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006714 Op = AtomicInnerBinOp->getOpcode();
6715 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006716 Expr *LHS = AtomicInnerBinOp->getLHS();
6717 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006718 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6719 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6720 /*Canonical=*/true);
6721 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6722 /*Canonical=*/true);
6723 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6724 /*Canonical=*/true);
6725 if (XId == LHSId) {
6726 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006727 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006728 } else if (XId == RHSId) {
6729 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006730 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006731 } else {
6732 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6733 ErrorRange = AtomicInnerBinOp->getSourceRange();
6734 NoteLoc = X->getExprLoc();
6735 NoteRange = X->getSourceRange();
6736 ErrorFound = NotAnUpdateExpression;
6737 }
6738 } else {
6739 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6740 ErrorRange = AtomicInnerBinOp->getSourceRange();
6741 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6742 NoteRange = SourceRange(NoteLoc, NoteLoc);
6743 ErrorFound = NotABinaryOperator;
6744 }
6745 } else {
6746 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6747 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6748 ErrorFound = NotABinaryExpression;
6749 }
6750 } else {
6751 ErrorLoc = AtomicBinOp->getExprLoc();
6752 ErrorRange = AtomicBinOp->getSourceRange();
6753 NoteLoc = AtomicBinOp->getOperatorLoc();
6754 NoteRange = SourceRange(NoteLoc, NoteLoc);
6755 ErrorFound = NotAnAssignmentOp;
6756 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006757 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006758 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6759 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6760 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006761 }
6762 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006763 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006764 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006765}
6766
6767bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6768 unsigned NoteId) {
6769 ExprAnalysisErrorCode ErrorFound = NoError;
6770 SourceLocation ErrorLoc, NoteLoc;
6771 SourceRange ErrorRange, NoteRange;
6772 // Allowed constructs are:
6773 // x++;
6774 // x--;
6775 // ++x;
6776 // --x;
6777 // x binop= expr;
6778 // x = x binop expr;
6779 // x = expr binop x;
6780 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6781 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6782 if (AtomicBody->getType()->isScalarType() ||
6783 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006784 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006785 AtomicBody->IgnoreParenImpCasts())) {
6786 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006787 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006788 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006789 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006790 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006791 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006792 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006793 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6794 AtomicBody->IgnoreParenImpCasts())) {
6795 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006796 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006797 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006798 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006799 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006800 // Check for Unary Operation
6801 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006802 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006803 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6804 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006805 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006806 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6807 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006808 } else {
6809 ErrorFound = NotAnUnaryIncDecExpression;
6810 ErrorLoc = AtomicUnaryOp->getExprLoc();
6811 ErrorRange = AtomicUnaryOp->getSourceRange();
6812 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6813 NoteRange = SourceRange(NoteLoc, NoteLoc);
6814 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006815 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006816 ErrorFound = NotABinaryOrUnaryExpression;
6817 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6818 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6819 }
6820 } else {
6821 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006822 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006823 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6824 }
6825 } else {
6826 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006827 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006828 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6829 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006830 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006831 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6832 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6833 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006834 }
6835 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006836 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006837 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006838 // Build an update expression of form 'OpaqueValueExpr(x) binop
6839 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6840 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6841 auto *OVEX = new (SemaRef.getASTContext())
6842 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6843 auto *OVEExpr = new (SemaRef.getASTContext())
6844 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006845 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006846 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6847 IsXLHSInRHSPart ? OVEExpr : OVEX);
6848 if (Update.isInvalid())
6849 return true;
6850 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6851 Sema::AA_Casting);
6852 if (Update.isInvalid())
6853 return true;
6854 UpdateExpr = Update.get();
6855 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006856 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006857}
6858
Alexey Bataev0162e452014-07-22 10:10:35 +00006859StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6860 Stmt *AStmt,
6861 SourceLocation StartLoc,
6862 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006863 if (!AStmt)
6864 return StmtError();
6865
David Majnemer9d168222016-08-05 17:44:54 +00006866 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006867 // 1.2.2 OpenMP Language Terminology
6868 // Structured block - An executable statement with a single entry at the
6869 // top and a single exit at the bottom.
6870 // The point of exit cannot be a branch out of the structured block.
6871 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006872 OpenMPClauseKind AtomicKind = OMPC_unknown;
6873 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006874 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006875 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006876 C->getClauseKind() == OMPC_update ||
6877 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006878 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006879 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006880 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006881 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6882 << getOpenMPClauseName(AtomicKind);
6883 } else {
6884 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006885 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006886 }
6887 }
6888 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006889
Alexey Bataeve3727102018-04-18 15:57:46 +00006890 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006891 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6892 Body = EWC->getSubExpr();
6893
Alexey Bataev62cec442014-11-18 10:14:22 +00006894 Expr *X = nullptr;
6895 Expr *V = nullptr;
6896 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006897 Expr *UE = nullptr;
6898 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006899 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006900 // OpenMP [2.12.6, atomic Construct]
6901 // In the next expressions:
6902 // * x and v (as applicable) are both l-value expressions with scalar type.
6903 // * During the execution of an atomic region, multiple syntactic
6904 // occurrences of x must designate the same storage location.
6905 // * Neither of v and expr (as applicable) may access the storage location
6906 // designated by x.
6907 // * Neither of x and expr (as applicable) may access the storage location
6908 // designated by v.
6909 // * expr is an expression with scalar type.
6910 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6911 // * binop, binop=, ++, and -- are not overloaded operators.
6912 // * The expression x binop expr must be numerically equivalent to x binop
6913 // (expr). This requirement is satisfied if the operators in expr have
6914 // precedence greater than binop, or by using parentheses around expr or
6915 // subexpressions of expr.
6916 // * The expression expr binop x must be numerically equivalent to (expr)
6917 // binop x. This requirement is satisfied if the operators in expr have
6918 // precedence equal to or greater than binop, or by using parentheses around
6919 // expr or subexpressions of expr.
6920 // * For forms that allow multiple occurrences of x, the number of times
6921 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006922 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006923 enum {
6924 NotAnExpression,
6925 NotAnAssignmentOp,
6926 NotAScalarType,
6927 NotAnLValue,
6928 NoError
6929 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006930 SourceLocation ErrorLoc, NoteLoc;
6931 SourceRange ErrorRange, NoteRange;
6932 // If clause is read:
6933 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006934 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6935 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006936 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6937 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6938 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6939 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6940 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6941 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6942 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006943 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006944 ErrorFound = NotAnLValue;
6945 ErrorLoc = AtomicBinOp->getExprLoc();
6946 ErrorRange = AtomicBinOp->getSourceRange();
6947 NoteLoc = NotLValueExpr->getExprLoc();
6948 NoteRange = NotLValueExpr->getSourceRange();
6949 }
6950 } else if (!X->isInstantiationDependent() ||
6951 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006952 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006953 (X->isInstantiationDependent() || X->getType()->isScalarType())
6954 ? V
6955 : X;
6956 ErrorFound = NotAScalarType;
6957 ErrorLoc = AtomicBinOp->getExprLoc();
6958 ErrorRange = AtomicBinOp->getSourceRange();
6959 NoteLoc = NotScalarExpr->getExprLoc();
6960 NoteRange = NotScalarExpr->getSourceRange();
6961 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006962 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006963 ErrorFound = NotAnAssignmentOp;
6964 ErrorLoc = AtomicBody->getExprLoc();
6965 ErrorRange = AtomicBody->getSourceRange();
6966 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6967 : AtomicBody->getExprLoc();
6968 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6969 : AtomicBody->getSourceRange();
6970 }
6971 } else {
6972 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006973 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006974 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006975 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006976 if (ErrorFound != NoError) {
6977 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6978 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006979 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6980 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006981 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006982 }
6983 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00006984 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006985 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006986 enum {
6987 NotAnExpression,
6988 NotAnAssignmentOp,
6989 NotAScalarType,
6990 NotAnLValue,
6991 NoError
6992 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006993 SourceLocation ErrorLoc, NoteLoc;
6994 SourceRange ErrorRange, NoteRange;
6995 // If clause is write:
6996 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00006997 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6998 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006999 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7000 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007001 X = AtomicBinOp->getLHS();
7002 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007003 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7004 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7005 if (!X->isLValue()) {
7006 ErrorFound = NotAnLValue;
7007 ErrorLoc = AtomicBinOp->getExprLoc();
7008 ErrorRange = AtomicBinOp->getSourceRange();
7009 NoteLoc = X->getExprLoc();
7010 NoteRange = X->getSourceRange();
7011 }
7012 } else if (!X->isInstantiationDependent() ||
7013 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007014 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007015 (X->isInstantiationDependent() || X->getType()->isScalarType())
7016 ? E
7017 : X;
7018 ErrorFound = NotAScalarType;
7019 ErrorLoc = AtomicBinOp->getExprLoc();
7020 ErrorRange = AtomicBinOp->getSourceRange();
7021 NoteLoc = NotScalarExpr->getExprLoc();
7022 NoteRange = NotScalarExpr->getSourceRange();
7023 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007024 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007025 ErrorFound = NotAnAssignmentOp;
7026 ErrorLoc = AtomicBody->getExprLoc();
7027 ErrorRange = AtomicBody->getSourceRange();
7028 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7029 : AtomicBody->getExprLoc();
7030 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7031 : AtomicBody->getSourceRange();
7032 }
7033 } else {
7034 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007035 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007036 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007037 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007038 if (ErrorFound != NoError) {
7039 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7040 << ErrorRange;
7041 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7042 << NoteRange;
7043 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007044 }
7045 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007046 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007047 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007048 // If clause is update:
7049 // x++;
7050 // x--;
7051 // ++x;
7052 // --x;
7053 // x binop= expr;
7054 // x = x binop expr;
7055 // x = expr binop x;
7056 OpenMPAtomicUpdateChecker Checker(*this);
7057 if (Checker.checkStatement(
7058 Body, (AtomicKind == OMPC_update)
7059 ? diag::err_omp_atomic_update_not_expression_statement
7060 : diag::err_omp_atomic_not_expression_statement,
7061 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007062 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007063 if (!CurContext->isDependentContext()) {
7064 E = Checker.getExpr();
7065 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007066 UE = Checker.getUpdateExpr();
7067 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007068 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007069 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007070 enum {
7071 NotAnAssignmentOp,
7072 NotACompoundStatement,
7073 NotTwoSubstatements,
7074 NotASpecificExpression,
7075 NoError
7076 } ErrorFound = NoError;
7077 SourceLocation ErrorLoc, NoteLoc;
7078 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007079 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007080 // If clause is a capture:
7081 // v = x++;
7082 // v = x--;
7083 // v = ++x;
7084 // v = --x;
7085 // v = x binop= expr;
7086 // v = x = x binop expr;
7087 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007088 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007089 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7090 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7091 V = AtomicBinOp->getLHS();
7092 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7093 OpenMPAtomicUpdateChecker Checker(*this);
7094 if (Checker.checkStatement(
7095 Body, diag::err_omp_atomic_capture_not_expression_statement,
7096 diag::note_omp_atomic_update))
7097 return StmtError();
7098 E = Checker.getExpr();
7099 X = Checker.getX();
7100 UE = Checker.getUpdateExpr();
7101 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7102 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007103 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007104 ErrorLoc = AtomicBody->getExprLoc();
7105 ErrorRange = AtomicBody->getSourceRange();
7106 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7107 : AtomicBody->getExprLoc();
7108 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7109 : AtomicBody->getSourceRange();
7110 ErrorFound = NotAnAssignmentOp;
7111 }
7112 if (ErrorFound != NoError) {
7113 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7114 << ErrorRange;
7115 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7116 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007117 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007118 if (CurContext->isDependentContext())
7119 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007120 } else {
7121 // If clause is a capture:
7122 // { v = x; x = expr; }
7123 // { v = x; x++; }
7124 // { v = x; x--; }
7125 // { v = x; ++x; }
7126 // { v = x; --x; }
7127 // { v = x; x binop= expr; }
7128 // { v = x; x = x binop expr; }
7129 // { v = x; x = expr binop x; }
7130 // { x++; v = x; }
7131 // { x--; v = x; }
7132 // { ++x; v = x; }
7133 // { --x; v = x; }
7134 // { x binop= expr; v = x; }
7135 // { x = x binop expr; v = x; }
7136 // { x = expr binop x; v = x; }
7137 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7138 // Check that this is { expr1; expr2; }
7139 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007140 Stmt *First = CS->body_front();
7141 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007142 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7143 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7144 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7145 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7146 // Need to find what subexpression is 'v' and what is 'x'.
7147 OpenMPAtomicUpdateChecker Checker(*this);
7148 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7149 BinaryOperator *BinOp = nullptr;
7150 if (IsUpdateExprFound) {
7151 BinOp = dyn_cast<BinaryOperator>(First);
7152 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7153 }
7154 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7155 // { v = x; x++; }
7156 // { v = x; x--; }
7157 // { v = x; ++x; }
7158 // { v = x; --x; }
7159 // { v = x; x binop= expr; }
7160 // { v = x; x = x binop expr; }
7161 // { v = x; x = expr binop x; }
7162 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007163 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007164 llvm::FoldingSetNodeID XId, PossibleXId;
7165 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7166 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7167 IsUpdateExprFound = XId == PossibleXId;
7168 if (IsUpdateExprFound) {
7169 V = BinOp->getLHS();
7170 X = Checker.getX();
7171 E = Checker.getExpr();
7172 UE = Checker.getUpdateExpr();
7173 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007174 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007175 }
7176 }
7177 if (!IsUpdateExprFound) {
7178 IsUpdateExprFound = !Checker.checkStatement(First);
7179 BinOp = nullptr;
7180 if (IsUpdateExprFound) {
7181 BinOp = dyn_cast<BinaryOperator>(Second);
7182 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7183 }
7184 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7185 // { x++; v = x; }
7186 // { x--; v = x; }
7187 // { ++x; v = x; }
7188 // { --x; v = x; }
7189 // { x binop= expr; v = x; }
7190 // { x = x binop expr; v = x; }
7191 // { x = expr binop x; v = x; }
7192 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007193 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007194 llvm::FoldingSetNodeID XId, PossibleXId;
7195 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7196 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7197 IsUpdateExprFound = XId == PossibleXId;
7198 if (IsUpdateExprFound) {
7199 V = BinOp->getLHS();
7200 X = Checker.getX();
7201 E = Checker.getExpr();
7202 UE = Checker.getUpdateExpr();
7203 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007204 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007205 }
7206 }
7207 }
7208 if (!IsUpdateExprFound) {
7209 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007210 auto *FirstExpr = dyn_cast<Expr>(First);
7211 auto *SecondExpr = dyn_cast<Expr>(Second);
7212 if (!FirstExpr || !SecondExpr ||
7213 !(FirstExpr->isInstantiationDependent() ||
7214 SecondExpr->isInstantiationDependent())) {
7215 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7216 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007217 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007218 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007219 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007220 NoteRange = ErrorRange = FirstBinOp
7221 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007222 : SourceRange(ErrorLoc, ErrorLoc);
7223 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007224 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7225 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7226 ErrorFound = NotAnAssignmentOp;
7227 NoteLoc = ErrorLoc = SecondBinOp
7228 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007229 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007230 NoteRange = ErrorRange =
7231 SecondBinOp ? SecondBinOp->getSourceRange()
7232 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007233 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007234 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007235 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007236 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007237 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7238 llvm::FoldingSetNodeID X1Id, X2Id;
7239 PossibleXRHSInFirst->Profile(X1Id, Context,
7240 /*Canonical=*/true);
7241 PossibleXLHSInSecond->Profile(X2Id, Context,
7242 /*Canonical=*/true);
7243 IsUpdateExprFound = X1Id == X2Id;
7244 if (IsUpdateExprFound) {
7245 V = FirstBinOp->getLHS();
7246 X = SecondBinOp->getLHS();
7247 E = SecondBinOp->getRHS();
7248 UE = nullptr;
7249 IsXLHSInRHSPart = false;
7250 IsPostfixUpdate = true;
7251 } else {
7252 ErrorFound = NotASpecificExpression;
7253 ErrorLoc = FirstBinOp->getExprLoc();
7254 ErrorRange = FirstBinOp->getSourceRange();
7255 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7256 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7257 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007258 }
7259 }
7260 }
7261 }
7262 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007263 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007264 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007265 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007266 ErrorFound = NotTwoSubstatements;
7267 }
7268 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007269 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007270 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007271 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007272 ErrorFound = NotACompoundStatement;
7273 }
7274 if (ErrorFound != NoError) {
7275 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7276 << ErrorRange;
7277 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7278 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007279 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007280 if (CurContext->isDependentContext())
7281 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007282 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007283 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007284
Reid Kleckner87a31802018-03-12 21:43:02 +00007285 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007286
Alexey Bataev62cec442014-11-18 10:14:22 +00007287 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007288 X, V, E, UE, IsXLHSInRHSPart,
7289 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007290}
7291
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007292StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7293 Stmt *AStmt,
7294 SourceLocation StartLoc,
7295 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007296 if (!AStmt)
7297 return StmtError();
7298
Alexey Bataeve3727102018-04-18 15:57:46 +00007299 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007300 // 1.2.2 OpenMP Language Terminology
7301 // Structured block - An executable statement with a single entry at the
7302 // top and a single exit at the bottom.
7303 // The point of exit cannot be a branch out of the structured block.
7304 // longjmp() and throw() must not violate the entry/exit criteria.
7305 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007306 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7307 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7308 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7309 // 1.2.2 OpenMP Language Terminology
7310 // Structured block - An executable statement with a single entry at the
7311 // top and a single exit at the bottom.
7312 // The point of exit cannot be a branch out of the structured block.
7313 // longjmp() and throw() must not violate the entry/exit criteria.
7314 CS->getCapturedDecl()->setNothrow();
7315 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007316
Alexey Bataev13314bf2014-10-09 04:18:56 +00007317 // OpenMP [2.16, Nesting of Regions]
7318 // If specified, a teams construct must be contained within a target
7319 // construct. That target construct must contain no statements or directives
7320 // outside of the teams construct.
7321 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007322 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007323 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007324 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007325 auto I = CS->body_begin();
7326 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007327 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007328 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7329 OMPTeamsFound) {
7330
Alexey Bataev13314bf2014-10-09 04:18:56 +00007331 OMPTeamsFound = false;
7332 break;
7333 }
7334 ++I;
7335 }
7336 assert(I != CS->body_end() && "Not found statement");
7337 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007338 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007339 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007340 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007341 }
7342 if (!OMPTeamsFound) {
7343 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7344 Diag(DSAStack->getInnerTeamsRegionLoc(),
7345 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007346 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007347 << isa<OMPExecutableDirective>(S);
7348 return StmtError();
7349 }
7350 }
7351
Reid Kleckner87a31802018-03-12 21:43:02 +00007352 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007353
7354 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7355}
7356
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007357StmtResult
7358Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7359 Stmt *AStmt, SourceLocation StartLoc,
7360 SourceLocation EndLoc) {
7361 if (!AStmt)
7362 return StmtError();
7363
Alexey Bataeve3727102018-04-18 15:57:46 +00007364 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007365 // 1.2.2 OpenMP Language Terminology
7366 // Structured block - An executable statement with a single entry at the
7367 // top and a single exit at the bottom.
7368 // The point of exit cannot be a branch out of the structured block.
7369 // longjmp() and throw() must not violate the entry/exit criteria.
7370 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007371 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7372 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7373 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7374 // 1.2.2 OpenMP Language Terminology
7375 // Structured block - An executable statement with a single entry at the
7376 // top and a single exit at the bottom.
7377 // The point of exit cannot be a branch out of the structured block.
7378 // longjmp() and throw() must not violate the entry/exit criteria.
7379 CS->getCapturedDecl()->setNothrow();
7380 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007381
Reid Kleckner87a31802018-03-12 21:43:02 +00007382 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007383
7384 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7385 AStmt);
7386}
7387
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007388StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7389 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007390 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007391 if (!AStmt)
7392 return StmtError();
7393
Alexey Bataeve3727102018-04-18 15:57:46 +00007394 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007395 // 1.2.2 OpenMP Language Terminology
7396 // Structured block - An executable statement with a single entry at the
7397 // top and a single exit at the bottom.
7398 // The point of exit cannot be a branch out of the structured block.
7399 // longjmp() and throw() must not violate the entry/exit criteria.
7400 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007401 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7402 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7403 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7404 // 1.2.2 OpenMP Language Terminology
7405 // Structured block - An executable statement with a single entry at the
7406 // top and a single exit at the bottom.
7407 // The point of exit cannot be a branch out of the structured block.
7408 // longjmp() and throw() must not violate the entry/exit criteria.
7409 CS->getCapturedDecl()->setNothrow();
7410 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007411
7412 OMPLoopDirective::HelperExprs B;
7413 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7414 // define the nested loops number.
7415 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007416 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007417 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007418 VarsWithImplicitDSA, B);
7419 if (NestedLoopCount == 0)
7420 return StmtError();
7421
7422 assert((CurContext->isDependentContext() || B.builtAll()) &&
7423 "omp target parallel for loop exprs were not built");
7424
7425 if (!CurContext->isDependentContext()) {
7426 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007427 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007428 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007429 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007430 B.NumIterations, *this, CurScope,
7431 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007432 return StmtError();
7433 }
7434 }
7435
Reid Kleckner87a31802018-03-12 21:43:02 +00007436 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007437 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7438 NestedLoopCount, Clauses, AStmt,
7439 B, DSAStack->isCancelRegion());
7440}
7441
Alexey Bataev95b64a92017-05-30 16:00:04 +00007442/// Check for existence of a map clause in the list of clauses.
7443static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7444 const OpenMPClauseKind K) {
7445 return llvm::any_of(
7446 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7447}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007448
Alexey Bataev95b64a92017-05-30 16:00:04 +00007449template <typename... Params>
7450static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7451 const Params... ClauseTypes) {
7452 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007453}
7454
Michael Wong65f367f2015-07-21 13:44:28 +00007455StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7456 Stmt *AStmt,
7457 SourceLocation StartLoc,
7458 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007459 if (!AStmt)
7460 return StmtError();
7461
7462 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7463
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007464 // OpenMP [2.10.1, Restrictions, p. 97]
7465 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007466 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7467 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7468 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007469 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007470 return StmtError();
7471 }
7472
Reid Kleckner87a31802018-03-12 21:43:02 +00007473 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007474
7475 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7476 AStmt);
7477}
7478
Samuel Antaodf67fc42016-01-19 19:15:56 +00007479StmtResult
7480Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7481 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007482 SourceLocation EndLoc, Stmt *AStmt) {
7483 if (!AStmt)
7484 return StmtError();
7485
Alexey Bataeve3727102018-04-18 15:57:46 +00007486 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007487 // 1.2.2 OpenMP Language Terminology
7488 // Structured block - An executable statement with a single entry at the
7489 // top and a single exit at the bottom.
7490 // The point of exit cannot be a branch out of the structured block.
7491 // longjmp() and throw() must not violate the entry/exit criteria.
7492 CS->getCapturedDecl()->setNothrow();
7493 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7494 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7495 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7496 // 1.2.2 OpenMP Language Terminology
7497 // Structured block - An executable statement with a single entry at the
7498 // top and a single exit at the bottom.
7499 // The point of exit cannot be a branch out of the structured block.
7500 // longjmp() and throw() must not violate the entry/exit criteria.
7501 CS->getCapturedDecl()->setNothrow();
7502 }
7503
Samuel Antaodf67fc42016-01-19 19:15:56 +00007504 // OpenMP [2.10.2, Restrictions, p. 99]
7505 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007506 if (!hasClauses(Clauses, OMPC_map)) {
7507 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7508 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007509 return StmtError();
7510 }
7511
Alexey Bataev7828b252017-11-21 17:08:48 +00007512 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7513 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007514}
7515
Samuel Antao72590762016-01-19 20:04:50 +00007516StmtResult
7517Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7518 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007519 SourceLocation EndLoc, Stmt *AStmt) {
7520 if (!AStmt)
7521 return StmtError();
7522
Alexey Bataeve3727102018-04-18 15:57:46 +00007523 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007524 // 1.2.2 OpenMP Language Terminology
7525 // Structured block - An executable statement with a single entry at the
7526 // top and a single exit at the bottom.
7527 // The point of exit cannot be a branch out of the structured block.
7528 // longjmp() and throw() must not violate the entry/exit criteria.
7529 CS->getCapturedDecl()->setNothrow();
7530 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7531 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7532 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7533 // 1.2.2 OpenMP Language Terminology
7534 // Structured block - An executable statement with a single entry at the
7535 // top and a single exit at the bottom.
7536 // The point of exit cannot be a branch out of the structured block.
7537 // longjmp() and throw() must not violate the entry/exit criteria.
7538 CS->getCapturedDecl()->setNothrow();
7539 }
7540
Samuel Antao72590762016-01-19 20:04:50 +00007541 // OpenMP [2.10.3, Restrictions, p. 102]
7542 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007543 if (!hasClauses(Clauses, OMPC_map)) {
7544 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7545 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007546 return StmtError();
7547 }
7548
Alexey Bataev7828b252017-11-21 17:08:48 +00007549 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7550 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007551}
7552
Samuel Antao686c70c2016-05-26 17:30:50 +00007553StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7554 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007555 SourceLocation EndLoc,
7556 Stmt *AStmt) {
7557 if (!AStmt)
7558 return StmtError();
7559
Alexey Bataeve3727102018-04-18 15:57:46 +00007560 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007561 // 1.2.2 OpenMP Language Terminology
7562 // Structured block - An executable statement with a single entry at the
7563 // top and a single exit at the bottom.
7564 // The point of exit cannot be a branch out of the structured block.
7565 // longjmp() and throw() must not violate the entry/exit criteria.
7566 CS->getCapturedDecl()->setNothrow();
7567 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7568 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7569 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7570 // 1.2.2 OpenMP Language Terminology
7571 // Structured block - An executable statement with a single entry at the
7572 // top and a single exit at the bottom.
7573 // The point of exit cannot be a branch out of the structured block.
7574 // longjmp() and throw() must not violate the entry/exit criteria.
7575 CS->getCapturedDecl()->setNothrow();
7576 }
7577
Alexey Bataev95b64a92017-05-30 16:00:04 +00007578 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007579 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7580 return StmtError();
7581 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007582 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7583 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007584}
7585
Alexey Bataev13314bf2014-10-09 04:18:56 +00007586StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7587 Stmt *AStmt, SourceLocation StartLoc,
7588 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007589 if (!AStmt)
7590 return StmtError();
7591
Alexey Bataeve3727102018-04-18 15:57:46 +00007592 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007593 // 1.2.2 OpenMP Language Terminology
7594 // Structured block - An executable statement with a single entry at the
7595 // top and a single exit at the bottom.
7596 // The point of exit cannot be a branch out of the structured block.
7597 // longjmp() and throw() must not violate the entry/exit criteria.
7598 CS->getCapturedDecl()->setNothrow();
7599
Reid Kleckner87a31802018-03-12 21:43:02 +00007600 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007601
Alexey Bataevceabd412017-11-30 18:01:54 +00007602 DSAStack->setParentTeamsRegionLoc(StartLoc);
7603
Alexey Bataev13314bf2014-10-09 04:18:56 +00007604 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7605}
7606
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007607StmtResult
7608Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7609 SourceLocation EndLoc,
7610 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007611 if (DSAStack->isParentNowaitRegion()) {
7612 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7613 return StmtError();
7614 }
7615 if (DSAStack->isParentOrderedRegion()) {
7616 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7617 return StmtError();
7618 }
7619 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7620 CancelRegion);
7621}
7622
Alexey Bataev87933c72015-09-18 08:07:34 +00007623StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7624 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007625 SourceLocation EndLoc,
7626 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007627 if (DSAStack->isParentNowaitRegion()) {
7628 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7629 return StmtError();
7630 }
7631 if (DSAStack->isParentOrderedRegion()) {
7632 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7633 return StmtError();
7634 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007635 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007636 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7637 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007638}
7639
Alexey Bataev382967a2015-12-08 12:06:20 +00007640static bool checkGrainsizeNumTasksClauses(Sema &S,
7641 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007642 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007643 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007644 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007645 if (C->getClauseKind() == OMPC_grainsize ||
7646 C->getClauseKind() == OMPC_num_tasks) {
7647 if (!PrevClause)
7648 PrevClause = C;
7649 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007650 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007651 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7652 << getOpenMPClauseName(C->getClauseKind())
7653 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007654 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007655 diag::note_omp_previous_grainsize_num_tasks)
7656 << getOpenMPClauseName(PrevClause->getClauseKind());
7657 ErrorFound = true;
7658 }
7659 }
7660 }
7661 return ErrorFound;
7662}
7663
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007664static bool checkReductionClauseWithNogroup(Sema &S,
7665 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007666 const OMPClause *ReductionClause = nullptr;
7667 const OMPClause *NogroupClause = nullptr;
7668 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007669 if (C->getClauseKind() == OMPC_reduction) {
7670 ReductionClause = C;
7671 if (NogroupClause)
7672 break;
7673 continue;
7674 }
7675 if (C->getClauseKind() == OMPC_nogroup) {
7676 NogroupClause = C;
7677 if (ReductionClause)
7678 break;
7679 continue;
7680 }
7681 }
7682 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007683 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7684 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007685 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007686 return true;
7687 }
7688 return false;
7689}
7690
Alexey Bataev49f6e782015-12-01 04:18:41 +00007691StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7692 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007693 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007694 if (!AStmt)
7695 return StmtError();
7696
7697 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7698 OMPLoopDirective::HelperExprs B;
7699 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7700 // define the nested loops number.
7701 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007702 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007703 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007704 VarsWithImplicitDSA, B);
7705 if (NestedLoopCount == 0)
7706 return StmtError();
7707
7708 assert((CurContext->isDependentContext() || B.builtAll()) &&
7709 "omp for loop exprs were not built");
7710
Alexey Bataev382967a2015-12-08 12:06:20 +00007711 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7712 // The grainsize clause and num_tasks clause are mutually exclusive and may
7713 // not appear on the same taskloop directive.
7714 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7715 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007716 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7717 // If a reduction clause is present on the taskloop directive, the nogroup
7718 // clause must not be specified.
7719 if (checkReductionClauseWithNogroup(*this, Clauses))
7720 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007721
Reid Kleckner87a31802018-03-12 21:43:02 +00007722 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007723 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7724 NestedLoopCount, Clauses, AStmt, B);
7725}
7726
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007727StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7728 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007729 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007730 if (!AStmt)
7731 return StmtError();
7732
7733 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7734 OMPLoopDirective::HelperExprs B;
7735 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7736 // define the nested loops number.
7737 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007738 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007739 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7740 VarsWithImplicitDSA, B);
7741 if (NestedLoopCount == 0)
7742 return StmtError();
7743
7744 assert((CurContext->isDependentContext() || B.builtAll()) &&
7745 "omp for loop exprs were not built");
7746
Alexey Bataev5a3af132016-03-29 08:58:54 +00007747 if (!CurContext->isDependentContext()) {
7748 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007749 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007750 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007751 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007752 B.NumIterations, *this, CurScope,
7753 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007754 return StmtError();
7755 }
7756 }
7757
Alexey Bataev382967a2015-12-08 12:06:20 +00007758 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7759 // The grainsize clause and num_tasks clause are mutually exclusive and may
7760 // not appear on the same taskloop directive.
7761 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7762 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007763 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7764 // If a reduction clause is present on the taskloop directive, the nogroup
7765 // clause must not be specified.
7766 if (checkReductionClauseWithNogroup(*this, Clauses))
7767 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007768 if (checkSimdlenSafelenSpecified(*this, Clauses))
7769 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007770
Reid Kleckner87a31802018-03-12 21:43:02 +00007771 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007772 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7773 NestedLoopCount, Clauses, AStmt, B);
7774}
7775
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007776StmtResult Sema::ActOnOpenMPDistributeDirective(
7777 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007778 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007779 if (!AStmt)
7780 return StmtError();
7781
7782 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7783 OMPLoopDirective::HelperExprs B;
7784 // In presence of clause 'collapse' with number of loops, it will
7785 // define the nested loops number.
7786 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007787 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007788 nullptr /*ordered not a clause on distribute*/, AStmt,
7789 *this, *DSAStack, VarsWithImplicitDSA, B);
7790 if (NestedLoopCount == 0)
7791 return StmtError();
7792
7793 assert((CurContext->isDependentContext() || B.builtAll()) &&
7794 "omp for loop exprs were not built");
7795
Reid Kleckner87a31802018-03-12 21:43:02 +00007796 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007797 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7798 NestedLoopCount, Clauses, AStmt, B);
7799}
7800
Carlo Bertolli9925f152016-06-27 14:55:37 +00007801StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7802 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007803 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007804 if (!AStmt)
7805 return StmtError();
7806
Alexey Bataeve3727102018-04-18 15:57:46 +00007807 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007808 // 1.2.2 OpenMP Language Terminology
7809 // Structured block - An executable statement with a single entry at the
7810 // top and a single exit at the bottom.
7811 // The point of exit cannot be a branch out of the structured block.
7812 // longjmp() and throw() must not violate the entry/exit criteria.
7813 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007814 for (int ThisCaptureLevel =
7815 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7816 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7817 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7818 // 1.2.2 OpenMP Language Terminology
7819 // Structured block - An executable statement with a single entry at the
7820 // top and a single exit at the bottom.
7821 // The point of exit cannot be a branch out of the structured block.
7822 // longjmp() and throw() must not violate the entry/exit criteria.
7823 CS->getCapturedDecl()->setNothrow();
7824 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007825
7826 OMPLoopDirective::HelperExprs B;
7827 // In presence of clause 'collapse' with number of loops, it will
7828 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007829 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007830 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007831 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007832 VarsWithImplicitDSA, B);
7833 if (NestedLoopCount == 0)
7834 return StmtError();
7835
7836 assert((CurContext->isDependentContext() || B.builtAll()) &&
7837 "omp for loop exprs were not built");
7838
Reid Kleckner87a31802018-03-12 21:43:02 +00007839 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007840 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007841 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7842 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007843}
7844
Kelvin Li4a39add2016-07-05 05:00:15 +00007845StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7846 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007847 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007848 if (!AStmt)
7849 return StmtError();
7850
Alexey Bataeve3727102018-04-18 15:57:46 +00007851 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007852 // 1.2.2 OpenMP Language Terminology
7853 // Structured block - An executable statement with a single entry at the
7854 // top and a single exit at the bottom.
7855 // The point of exit cannot be a branch out of the structured block.
7856 // longjmp() and throw() must not violate the entry/exit criteria.
7857 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007858 for (int ThisCaptureLevel =
7859 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7860 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7861 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7862 // 1.2.2 OpenMP Language Terminology
7863 // Structured block - An executable statement with a single entry at the
7864 // top and a single exit at the bottom.
7865 // The point of exit cannot be a branch out of the structured block.
7866 // longjmp() and throw() must not violate the entry/exit criteria.
7867 CS->getCapturedDecl()->setNothrow();
7868 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007869
7870 OMPLoopDirective::HelperExprs B;
7871 // In presence of clause 'collapse' with number of loops, it will
7872 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007873 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007874 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007875 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007876 VarsWithImplicitDSA, B);
7877 if (NestedLoopCount == 0)
7878 return StmtError();
7879
7880 assert((CurContext->isDependentContext() || B.builtAll()) &&
7881 "omp for loop exprs were not built");
7882
Alexey Bataev438388c2017-11-22 18:34:02 +00007883 if (!CurContext->isDependentContext()) {
7884 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007885 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007886 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7887 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7888 B.NumIterations, *this, CurScope,
7889 DSAStack))
7890 return StmtError();
7891 }
7892 }
7893
Kelvin Lic5609492016-07-15 04:39:07 +00007894 if (checkSimdlenSafelenSpecified(*this, Clauses))
7895 return StmtError();
7896
Reid Kleckner87a31802018-03-12 21:43:02 +00007897 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007898 return OMPDistributeParallelForSimdDirective::Create(
7899 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7900}
7901
Kelvin Li787f3fc2016-07-06 04:45:38 +00007902StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7903 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007904 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007905 if (!AStmt)
7906 return StmtError();
7907
Alexey Bataeve3727102018-04-18 15:57:46 +00007908 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +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 Bataev617db5f2017-12-04 15:38:33 +00007915 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_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 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007925
7926 OMPLoopDirective::HelperExprs B;
7927 // In presence of clause 'collapse' with number of loops, it will
7928 // define the nested loops number.
7929 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007930 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007931 nullptr /*ordered not a clause on distribute*/, CS, *this,
7932 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007933 if (NestedLoopCount == 0)
7934 return StmtError();
7935
7936 assert((CurContext->isDependentContext() || B.builtAll()) &&
7937 "omp for loop exprs were not built");
7938
Alexey Bataev438388c2017-11-22 18:34:02 +00007939 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) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007942 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7943 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7944 B.NumIterations, *this, CurScope,
7945 DSAStack))
7946 return StmtError();
7947 }
7948 }
7949
Kelvin Lic5609492016-07-15 04:39:07 +00007950 if (checkSimdlenSafelenSpecified(*this, Clauses))
7951 return StmtError();
7952
Reid Kleckner87a31802018-03-12 21:43:02 +00007953 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007954 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7955 NestedLoopCount, Clauses, AStmt, B);
7956}
7957
Kelvin Lia579b912016-07-14 02:54:56 +00007958StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7959 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007960 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007961 if (!AStmt)
7962 return StmtError();
7963
Alexey Bataeve3727102018-04-18 15:57:46 +00007964 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +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 Bataev5d7edca2017-11-09 17:32:15 +00007971 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
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 Lia579b912016-07-14 02:54:56 +00007981
7982 OMPLoopDirective::HelperExprs B;
7983 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7984 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007985 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00007986 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007987 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007988 VarsWithImplicitDSA, B);
7989 if (NestedLoopCount == 0)
7990 return StmtError();
7991
7992 assert((CurContext->isDependentContext() || B.builtAll()) &&
7993 "omp target parallel for simd loop exprs were not built");
7994
7995 if (!CurContext->isDependentContext()) {
7996 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007997 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007998 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007999 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8000 B.NumIterations, *this, CurScope,
8001 DSAStack))
8002 return StmtError();
8003 }
8004 }
Kelvin Lic5609492016-07-15 04:39:07 +00008005 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008006 return StmtError();
8007
Reid Kleckner87a31802018-03-12 21:43:02 +00008008 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008009 return OMPTargetParallelForSimdDirective::Create(
8010 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8011}
8012
Kelvin Li986330c2016-07-20 22:57:10 +00008013StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8014 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008015 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008016 if (!AStmt)
8017 return StmtError();
8018
Alexey Bataeve3727102018-04-18 15:57:46 +00008019 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008020 // 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();
Alexey Bataevf8365372017-11-17 17:57:25 +00008026 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8027 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8028 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8029 // 1.2.2 OpenMP Language Terminology
8030 // Structured block - An executable statement with a single entry at the
8031 // top and a single exit at the bottom.
8032 // The point of exit cannot be a branch out of the structured block.
8033 // longjmp() and throw() must not violate the entry/exit criteria.
8034 CS->getCapturedDecl()->setNothrow();
8035 }
8036
Kelvin Li986330c2016-07-20 22:57:10 +00008037 OMPLoopDirective::HelperExprs B;
8038 // In presence of clause 'collapse' with number of loops, it will define the
8039 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008040 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008041 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008042 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008043 VarsWithImplicitDSA, B);
8044 if (NestedLoopCount == 0)
8045 return StmtError();
8046
8047 assert((CurContext->isDependentContext() || B.builtAll()) &&
8048 "omp target simd loop exprs were not built");
8049
8050 if (!CurContext->isDependentContext()) {
8051 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008052 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008053 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008054 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8055 B.NumIterations, *this, CurScope,
8056 DSAStack))
8057 return StmtError();
8058 }
8059 }
8060
8061 if (checkSimdlenSafelenSpecified(*this, Clauses))
8062 return StmtError();
8063
Reid Kleckner87a31802018-03-12 21:43:02 +00008064 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008065 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8066 NestedLoopCount, Clauses, AStmt, B);
8067}
8068
Kelvin Li02532872016-08-05 14:37:37 +00008069StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008071 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008072 if (!AStmt)
8073 return StmtError();
8074
Alexey Bataeve3727102018-04-18 15:57:46 +00008075 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008076 // 1.2.2 OpenMP Language Terminology
8077 // Structured block - An executable statement with a single entry at the
8078 // top and a single exit at the bottom.
8079 // The point of exit cannot be a branch out of the structured block.
8080 // longjmp() and throw() must not violate the entry/exit criteria.
8081 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008082 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8083 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8084 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8085 // 1.2.2 OpenMP Language Terminology
8086 // Structured block - An executable statement with a single entry at the
8087 // top and a single exit at the bottom.
8088 // The point of exit cannot be a branch out of the structured block.
8089 // longjmp() and throw() must not violate the entry/exit criteria.
8090 CS->getCapturedDecl()->setNothrow();
8091 }
Kelvin Li02532872016-08-05 14:37:37 +00008092
8093 OMPLoopDirective::HelperExprs B;
8094 // In presence of clause 'collapse' with number of loops, it will
8095 // define the nested loops number.
8096 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008097 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008098 nullptr /*ordered not a clause on distribute*/, CS, *this,
8099 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008100 if (NestedLoopCount == 0)
8101 return StmtError();
8102
8103 assert((CurContext->isDependentContext() || B.builtAll()) &&
8104 "omp teams distribute loop exprs were not built");
8105
Reid Kleckner87a31802018-03-12 21:43:02 +00008106 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008107
8108 DSAStack->setParentTeamsRegionLoc(StartLoc);
8109
David Majnemer9d168222016-08-05 17:44:54 +00008110 return OMPTeamsDistributeDirective::Create(
8111 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008112}
8113
Kelvin Li4e325f72016-10-25 12:50:55 +00008114StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8115 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008116 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008117 if (!AStmt)
8118 return StmtError();
8119
Alexey Bataeve3727102018-04-18 15:57:46 +00008120 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008121 // 1.2.2 OpenMP Language Terminology
8122 // Structured block - An executable statement with a single entry at the
8123 // top and a single exit at the bottom.
8124 // The point of exit cannot be a branch out of the structured block.
8125 // longjmp() and throw() must not violate the entry/exit criteria.
8126 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008127 for (int ThisCaptureLevel =
8128 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8129 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8130 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8131 // 1.2.2 OpenMP Language Terminology
8132 // Structured block - An executable statement with a single entry at the
8133 // top and a single exit at the bottom.
8134 // The point of exit cannot be a branch out of the structured block.
8135 // longjmp() and throw() must not violate the entry/exit criteria.
8136 CS->getCapturedDecl()->setNothrow();
8137 }
8138
Kelvin Li4e325f72016-10-25 12:50:55 +00008139
8140 OMPLoopDirective::HelperExprs B;
8141 // In presence of clause 'collapse' with number of loops, it will
8142 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008143 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008144 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008145 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008146 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008147
8148 if (NestedLoopCount == 0)
8149 return StmtError();
8150
8151 assert((CurContext->isDependentContext() || B.builtAll()) &&
8152 "omp teams distribute simd loop exprs were not built");
8153
8154 if (!CurContext->isDependentContext()) {
8155 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008156 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008157 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8158 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8159 B.NumIterations, *this, CurScope,
8160 DSAStack))
8161 return StmtError();
8162 }
8163 }
8164
8165 if (checkSimdlenSafelenSpecified(*this, Clauses))
8166 return StmtError();
8167
Reid Kleckner87a31802018-03-12 21:43:02 +00008168 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008169
8170 DSAStack->setParentTeamsRegionLoc(StartLoc);
8171
Kelvin Li4e325f72016-10-25 12:50:55 +00008172 return OMPTeamsDistributeSimdDirective::Create(
8173 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8174}
8175
Kelvin Li579e41c2016-11-30 23:51:03 +00008176StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8177 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008178 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008179 if (!AStmt)
8180 return StmtError();
8181
Alexey Bataeve3727102018-04-18 15:57:46 +00008182 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008183 // 1.2.2 OpenMP Language Terminology
8184 // Structured block - An executable statement with a single entry at the
8185 // top and a single exit at the bottom.
8186 // The point of exit cannot be a branch out of the structured block.
8187 // longjmp() and throw() must not violate the entry/exit criteria.
8188 CS->getCapturedDecl()->setNothrow();
8189
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008190 for (int ThisCaptureLevel =
8191 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
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 }
8201
Kelvin Li579e41c2016-11-30 23:51:03 +00008202 OMPLoopDirective::HelperExprs B;
8203 // In presence of clause 'collapse' with number of loops, it will
8204 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008205 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008206 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008207 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008208 VarsWithImplicitDSA, B);
8209
8210 if (NestedLoopCount == 0)
8211 return StmtError();
8212
8213 assert((CurContext->isDependentContext() || B.builtAll()) &&
8214 "omp for loop exprs were not built");
8215
8216 if (!CurContext->isDependentContext()) {
8217 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008218 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008219 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8220 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8221 B.NumIterations, *this, CurScope,
8222 DSAStack))
8223 return StmtError();
8224 }
8225 }
8226
8227 if (checkSimdlenSafelenSpecified(*this, Clauses))
8228 return StmtError();
8229
Reid Kleckner87a31802018-03-12 21:43:02 +00008230 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008231
8232 DSAStack->setParentTeamsRegionLoc(StartLoc);
8233
Kelvin Li579e41c2016-11-30 23:51:03 +00008234 return OMPTeamsDistributeParallelForSimdDirective::Create(
8235 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8236}
8237
Kelvin Li7ade93f2016-12-09 03:24:30 +00008238StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8239 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008240 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008241 if (!AStmt)
8242 return StmtError();
8243
Alexey Bataeve3727102018-04-18 15:57:46 +00008244 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008245 // 1.2.2 OpenMP Language Terminology
8246 // Structured block - An executable statement with a single entry at the
8247 // top and a single exit at the bottom.
8248 // The point of exit cannot be a branch out of the structured block.
8249 // longjmp() and throw() must not violate the entry/exit criteria.
8250 CS->getCapturedDecl()->setNothrow();
8251
Carlo Bertolli62fae152017-11-20 20:46:39 +00008252 for (int ThisCaptureLevel =
8253 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8254 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8255 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8256 // 1.2.2 OpenMP Language Terminology
8257 // Structured block - An executable statement with a single entry at the
8258 // top and a single exit at the bottom.
8259 // The point of exit cannot be a branch out of the structured block.
8260 // longjmp() and throw() must not violate the entry/exit criteria.
8261 CS->getCapturedDecl()->setNothrow();
8262 }
8263
Kelvin Li7ade93f2016-12-09 03:24:30 +00008264 OMPLoopDirective::HelperExprs B;
8265 // In presence of clause 'collapse' with number of loops, it will
8266 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008267 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008268 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008269 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008270 VarsWithImplicitDSA, B);
8271
8272 if (NestedLoopCount == 0)
8273 return StmtError();
8274
8275 assert((CurContext->isDependentContext() || B.builtAll()) &&
8276 "omp for loop exprs were not built");
8277
Reid Kleckner87a31802018-03-12 21:43:02 +00008278 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008279
8280 DSAStack->setParentTeamsRegionLoc(StartLoc);
8281
Kelvin Li7ade93f2016-12-09 03:24:30 +00008282 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008283 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8284 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008285}
8286
Kelvin Libf594a52016-12-17 05:48:59 +00008287StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8288 Stmt *AStmt,
8289 SourceLocation StartLoc,
8290 SourceLocation EndLoc) {
8291 if (!AStmt)
8292 return StmtError();
8293
Alexey Bataeve3727102018-04-18 15:57:46 +00008294 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008295 // 1.2.2 OpenMP Language Terminology
8296 // Structured block - An executable statement with a single entry at the
8297 // top and a single exit at the bottom.
8298 // The point of exit cannot be a branch out of the structured block.
8299 // longjmp() and throw() must not violate the entry/exit criteria.
8300 CS->getCapturedDecl()->setNothrow();
8301
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008302 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8303 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8304 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8305 // 1.2.2 OpenMP Language Terminology
8306 // Structured block - An executable statement with a single entry at the
8307 // top and a single exit at the bottom.
8308 // The point of exit cannot be a branch out of the structured block.
8309 // longjmp() and throw() must not violate the entry/exit criteria.
8310 CS->getCapturedDecl()->setNothrow();
8311 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008312 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008313
8314 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8315 AStmt);
8316}
8317
Kelvin Li83c451e2016-12-25 04:52:54 +00008318StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8319 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008320 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008321 if (!AStmt)
8322 return StmtError();
8323
Alexey Bataeve3727102018-04-18 15:57:46 +00008324 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008325 // 1.2.2 OpenMP Language Terminology
8326 // Structured block - An executable statement with a single entry at the
8327 // top and a single exit at the bottom.
8328 // The point of exit cannot be a branch out of the structured block.
8329 // longjmp() and throw() must not violate the entry/exit criteria.
8330 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008331 for (int ThisCaptureLevel =
8332 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8333 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8334 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8335 // 1.2.2 OpenMP Language Terminology
8336 // Structured block - An executable statement with a single entry at the
8337 // top and a single exit at the bottom.
8338 // The point of exit cannot be a branch out of the structured block.
8339 // longjmp() and throw() must not violate the entry/exit criteria.
8340 CS->getCapturedDecl()->setNothrow();
8341 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008342
8343 OMPLoopDirective::HelperExprs B;
8344 // In presence of clause 'collapse' with number of loops, it will
8345 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008346 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008347 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8348 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008349 VarsWithImplicitDSA, B);
8350 if (NestedLoopCount == 0)
8351 return StmtError();
8352
8353 assert((CurContext->isDependentContext() || B.builtAll()) &&
8354 "omp target teams distribute loop exprs were not built");
8355
Reid Kleckner87a31802018-03-12 21:43:02 +00008356 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008357 return OMPTargetTeamsDistributeDirective::Create(
8358 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8359}
8360
Kelvin Li80e8f562016-12-29 22:16:30 +00008361StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8362 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008363 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008364 if (!AStmt)
8365 return StmtError();
8366
Alexey Bataeve3727102018-04-18 15:57:46 +00008367 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008368 // 1.2.2 OpenMP Language Terminology
8369 // Structured block - An executable statement with a single entry at the
8370 // top and a single exit at the bottom.
8371 // The point of exit cannot be a branch out of the structured block.
8372 // longjmp() and throw() must not violate the entry/exit criteria.
8373 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008374 for (int ThisCaptureLevel =
8375 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8376 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8377 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8378 // 1.2.2 OpenMP Language Terminology
8379 // Structured block - An executable statement with a single entry at the
8380 // top and a single exit at the bottom.
8381 // The point of exit cannot be a branch out of the structured block.
8382 // longjmp() and throw() must not violate the entry/exit criteria.
8383 CS->getCapturedDecl()->setNothrow();
8384 }
8385
Kelvin Li80e8f562016-12-29 22:16:30 +00008386 OMPLoopDirective::HelperExprs B;
8387 // In presence of clause 'collapse' with number of loops, it will
8388 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008389 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008390 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8391 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008392 VarsWithImplicitDSA, B);
8393 if (NestedLoopCount == 0)
8394 return StmtError();
8395
8396 assert((CurContext->isDependentContext() || B.builtAll()) &&
8397 "omp target teams distribute parallel for loop exprs were not built");
8398
Alexey Bataev647dd842018-01-15 20:59:40 +00008399 if (!CurContext->isDependentContext()) {
8400 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008401 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008402 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8403 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8404 B.NumIterations, *this, CurScope,
8405 DSAStack))
8406 return StmtError();
8407 }
8408 }
8409
Reid Kleckner87a31802018-03-12 21:43:02 +00008410 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008411 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008412 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8413 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008414}
8415
Kelvin Li1851df52017-01-03 05:23:48 +00008416StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8417 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008418 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008419 if (!AStmt)
8420 return StmtError();
8421
Alexey Bataeve3727102018-04-18 15:57:46 +00008422 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008423 // 1.2.2 OpenMP Language Terminology
8424 // Structured block - An executable statement with a single entry at the
8425 // top and a single exit at the bottom.
8426 // The point of exit cannot be a branch out of the structured block.
8427 // longjmp() and throw() must not violate the entry/exit criteria.
8428 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008429 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8430 OMPD_target_teams_distribute_parallel_for_simd);
8431 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8432 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8433 // 1.2.2 OpenMP Language Terminology
8434 // Structured block - An executable statement with a single entry at the
8435 // top and a single exit at the bottom.
8436 // The point of exit cannot be a branch out of the structured block.
8437 // longjmp() and throw() must not violate the entry/exit criteria.
8438 CS->getCapturedDecl()->setNothrow();
8439 }
Kelvin Li1851df52017-01-03 05:23:48 +00008440
8441 OMPLoopDirective::HelperExprs B;
8442 // In presence of clause 'collapse' with number of loops, it will
8443 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008444 unsigned NestedLoopCount =
8445 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008446 getCollapseNumberExpr(Clauses),
8447 nullptr /*ordered not a clause on distribute*/, CS, *this,
8448 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008449 if (NestedLoopCount == 0)
8450 return StmtError();
8451
8452 assert((CurContext->isDependentContext() || B.builtAll()) &&
8453 "omp target teams distribute parallel for simd loop exprs were not "
8454 "built");
8455
8456 if (!CurContext->isDependentContext()) {
8457 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008458 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008459 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8460 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8461 B.NumIterations, *this, CurScope,
8462 DSAStack))
8463 return StmtError();
8464 }
8465 }
8466
Alexey Bataev438388c2017-11-22 18:34:02 +00008467 if (checkSimdlenSafelenSpecified(*this, Clauses))
8468 return StmtError();
8469
Reid Kleckner87a31802018-03-12 21:43:02 +00008470 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008471 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8472 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8473}
8474
Kelvin Lida681182017-01-10 18:08:18 +00008475StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8476 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008477 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008478 if (!AStmt)
8479 return StmtError();
8480
8481 auto *CS = cast<CapturedStmt>(AStmt);
8482 // 1.2.2 OpenMP Language Terminology
8483 // Structured block - An executable statement with a single entry at the
8484 // top and a single exit at the bottom.
8485 // The point of exit cannot be a branch out of the structured block.
8486 // longjmp() and throw() must not violate the entry/exit criteria.
8487 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008488 for (int ThisCaptureLevel =
8489 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8490 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8491 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8492 // 1.2.2 OpenMP Language Terminology
8493 // Structured block - An executable statement with a single entry at the
8494 // top and a single exit at the bottom.
8495 // The point of exit cannot be a branch out of the structured block.
8496 // longjmp() and throw() must not violate the entry/exit criteria.
8497 CS->getCapturedDecl()->setNothrow();
8498 }
Kelvin Lida681182017-01-10 18:08:18 +00008499
8500 OMPLoopDirective::HelperExprs B;
8501 // In presence of clause 'collapse' with number of loops, it will
8502 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008503 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008504 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008505 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008506 VarsWithImplicitDSA, B);
8507 if (NestedLoopCount == 0)
8508 return StmtError();
8509
8510 assert((CurContext->isDependentContext() || B.builtAll()) &&
8511 "omp target teams distribute simd loop exprs were not built");
8512
Alexey Bataev438388c2017-11-22 18:34:02 +00008513 if (!CurContext->isDependentContext()) {
8514 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008515 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008516 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8517 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8518 B.NumIterations, *this, CurScope,
8519 DSAStack))
8520 return StmtError();
8521 }
8522 }
8523
8524 if (checkSimdlenSafelenSpecified(*this, Clauses))
8525 return StmtError();
8526
Reid Kleckner87a31802018-03-12 21:43:02 +00008527 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008528 return OMPTargetTeamsDistributeSimdDirective::Create(
8529 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8530}
8531
Alexey Bataeved09d242014-05-28 05:53:51 +00008532OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008533 SourceLocation StartLoc,
8534 SourceLocation LParenLoc,
8535 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008536 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008537 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008538 case OMPC_final:
8539 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8540 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008541 case OMPC_num_threads:
8542 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8543 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008544 case OMPC_safelen:
8545 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8546 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008547 case OMPC_simdlen:
8548 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8549 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00008550 case OMPC_allocator:
8551 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8552 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008553 case OMPC_collapse:
8554 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8555 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008556 case OMPC_ordered:
8557 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8558 break;
Michael Wonge710d542015-08-07 16:16:36 +00008559 case OMPC_device:
8560 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8561 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008562 case OMPC_num_teams:
8563 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8564 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008565 case OMPC_thread_limit:
8566 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8567 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008568 case OMPC_priority:
8569 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8570 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008571 case OMPC_grainsize:
8572 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8573 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008574 case OMPC_num_tasks:
8575 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8576 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008577 case OMPC_hint:
8578 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8579 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008580 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008581 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008582 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008583 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008584 case OMPC_private:
8585 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008586 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008587 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008588 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008589 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008590 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008591 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008592 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008593 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008594 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008595 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008596 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008597 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008598 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008599 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008600 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008601 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008602 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008603 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008604 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008605 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008606 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008607 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008608 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008609 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008610 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008611 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008612 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008613 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008614 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008615 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008616 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008617 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008618 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008619 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008620 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008621 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008622 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008623 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008624 llvm_unreachable("Clause is not allowed.");
8625 }
8626 return Res;
8627}
8628
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008629// An OpenMP directive such as 'target parallel' has two captured regions:
8630// for the 'target' and 'parallel' respectively. This function returns
8631// the region in which to capture expressions associated with a clause.
8632// A return value of OMPD_unknown signifies that the expression should not
8633// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008634static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8635 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8636 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008637 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008638 switch (CKind) {
8639 case OMPC_if:
8640 switch (DKind) {
8641 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008642 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008643 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008644 // If this clause applies to the nested 'parallel' region, capture within
8645 // the 'target' region, otherwise do not capture.
8646 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8647 CaptureRegion = OMPD_target;
8648 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008649 case OMPD_target_teams_distribute_parallel_for:
8650 case OMPD_target_teams_distribute_parallel_for_simd:
8651 // If this clause applies to the nested 'parallel' region, capture within
8652 // the 'teams' region, otherwise do not capture.
8653 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8654 CaptureRegion = OMPD_teams;
8655 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008656 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008657 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008658 CaptureRegion = OMPD_teams;
8659 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008660 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008661 case OMPD_target_enter_data:
8662 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008663 CaptureRegion = OMPD_task;
8664 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008665 case OMPD_cancel:
8666 case OMPD_parallel:
8667 case OMPD_parallel_sections:
8668 case OMPD_parallel_for:
8669 case OMPD_parallel_for_simd:
8670 case OMPD_target:
8671 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008672 case OMPD_target_teams:
8673 case OMPD_target_teams_distribute:
8674 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008675 case OMPD_distribute_parallel_for:
8676 case OMPD_distribute_parallel_for_simd:
8677 case OMPD_task:
8678 case OMPD_taskloop:
8679 case OMPD_taskloop_simd:
8680 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008681 // Do not capture if-clause expressions.
8682 break;
8683 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008684 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008685 case OMPD_taskyield:
8686 case OMPD_barrier:
8687 case OMPD_taskwait:
8688 case OMPD_cancellation_point:
8689 case OMPD_flush:
8690 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008691 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008692 case OMPD_declare_simd:
8693 case OMPD_declare_target:
8694 case OMPD_end_declare_target:
8695 case OMPD_teams:
8696 case OMPD_simd:
8697 case OMPD_for:
8698 case OMPD_for_simd:
8699 case OMPD_sections:
8700 case OMPD_section:
8701 case OMPD_single:
8702 case OMPD_master:
8703 case OMPD_critical:
8704 case OMPD_taskgroup:
8705 case OMPD_distribute:
8706 case OMPD_ordered:
8707 case OMPD_atomic:
8708 case OMPD_distribute_simd:
8709 case OMPD_teams_distribute:
8710 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008711 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008712 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8713 case OMPD_unknown:
8714 llvm_unreachable("Unknown OpenMP directive");
8715 }
8716 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008717 case OMPC_num_threads:
8718 switch (DKind) {
8719 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008720 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008721 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008722 CaptureRegion = OMPD_target;
8723 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008724 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008725 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008726 case OMPD_target_teams_distribute_parallel_for:
8727 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008728 CaptureRegion = OMPD_teams;
8729 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008730 case OMPD_parallel:
8731 case OMPD_parallel_sections:
8732 case OMPD_parallel_for:
8733 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008734 case OMPD_distribute_parallel_for:
8735 case OMPD_distribute_parallel_for_simd:
8736 // Do not capture num_threads-clause expressions.
8737 break;
8738 case OMPD_target_data:
8739 case OMPD_target_enter_data:
8740 case OMPD_target_exit_data:
8741 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008742 case OMPD_target:
8743 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008744 case OMPD_target_teams:
8745 case OMPD_target_teams_distribute:
8746 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008747 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008748 case OMPD_task:
8749 case OMPD_taskloop:
8750 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008751 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008752 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008753 case OMPD_taskyield:
8754 case OMPD_barrier:
8755 case OMPD_taskwait:
8756 case OMPD_cancellation_point:
8757 case OMPD_flush:
8758 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008759 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008760 case OMPD_declare_simd:
8761 case OMPD_declare_target:
8762 case OMPD_end_declare_target:
8763 case OMPD_teams:
8764 case OMPD_simd:
8765 case OMPD_for:
8766 case OMPD_for_simd:
8767 case OMPD_sections:
8768 case OMPD_section:
8769 case OMPD_single:
8770 case OMPD_master:
8771 case OMPD_critical:
8772 case OMPD_taskgroup:
8773 case OMPD_distribute:
8774 case OMPD_ordered:
8775 case OMPD_atomic:
8776 case OMPD_distribute_simd:
8777 case OMPD_teams_distribute:
8778 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008779 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008780 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8781 case OMPD_unknown:
8782 llvm_unreachable("Unknown OpenMP directive");
8783 }
8784 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008785 case OMPC_num_teams:
8786 switch (DKind) {
8787 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008788 case OMPD_target_teams_distribute:
8789 case OMPD_target_teams_distribute_simd:
8790 case OMPD_target_teams_distribute_parallel_for:
8791 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008792 CaptureRegion = OMPD_target;
8793 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008794 case OMPD_teams_distribute_parallel_for:
8795 case OMPD_teams_distribute_parallel_for_simd:
8796 case OMPD_teams:
8797 case OMPD_teams_distribute:
8798 case OMPD_teams_distribute_simd:
8799 // Do not capture num_teams-clause expressions.
8800 break;
8801 case OMPD_distribute_parallel_for:
8802 case OMPD_distribute_parallel_for_simd:
8803 case OMPD_task:
8804 case OMPD_taskloop:
8805 case OMPD_taskloop_simd:
8806 case OMPD_target_data:
8807 case OMPD_target_enter_data:
8808 case OMPD_target_exit_data:
8809 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008810 case OMPD_cancel:
8811 case OMPD_parallel:
8812 case OMPD_parallel_sections:
8813 case OMPD_parallel_for:
8814 case OMPD_parallel_for_simd:
8815 case OMPD_target:
8816 case OMPD_target_simd:
8817 case OMPD_target_parallel:
8818 case OMPD_target_parallel_for:
8819 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008820 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008821 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008822 case OMPD_taskyield:
8823 case OMPD_barrier:
8824 case OMPD_taskwait:
8825 case OMPD_cancellation_point:
8826 case OMPD_flush:
8827 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008828 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008829 case OMPD_declare_simd:
8830 case OMPD_declare_target:
8831 case OMPD_end_declare_target:
8832 case OMPD_simd:
8833 case OMPD_for:
8834 case OMPD_for_simd:
8835 case OMPD_sections:
8836 case OMPD_section:
8837 case OMPD_single:
8838 case OMPD_master:
8839 case OMPD_critical:
8840 case OMPD_taskgroup:
8841 case OMPD_distribute:
8842 case OMPD_ordered:
8843 case OMPD_atomic:
8844 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008845 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008846 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8847 case OMPD_unknown:
8848 llvm_unreachable("Unknown OpenMP directive");
8849 }
8850 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008851 case OMPC_thread_limit:
8852 switch (DKind) {
8853 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008854 case OMPD_target_teams_distribute:
8855 case OMPD_target_teams_distribute_simd:
8856 case OMPD_target_teams_distribute_parallel_for:
8857 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008858 CaptureRegion = OMPD_target;
8859 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008860 case OMPD_teams_distribute_parallel_for:
8861 case OMPD_teams_distribute_parallel_for_simd:
8862 case OMPD_teams:
8863 case OMPD_teams_distribute:
8864 case OMPD_teams_distribute_simd:
8865 // Do not capture thread_limit-clause expressions.
8866 break;
8867 case OMPD_distribute_parallel_for:
8868 case OMPD_distribute_parallel_for_simd:
8869 case OMPD_task:
8870 case OMPD_taskloop:
8871 case OMPD_taskloop_simd:
8872 case OMPD_target_data:
8873 case OMPD_target_enter_data:
8874 case OMPD_target_exit_data:
8875 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008876 case OMPD_cancel:
8877 case OMPD_parallel:
8878 case OMPD_parallel_sections:
8879 case OMPD_parallel_for:
8880 case OMPD_parallel_for_simd:
8881 case OMPD_target:
8882 case OMPD_target_simd:
8883 case OMPD_target_parallel:
8884 case OMPD_target_parallel_for:
8885 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008886 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008887 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008888 case OMPD_taskyield:
8889 case OMPD_barrier:
8890 case OMPD_taskwait:
8891 case OMPD_cancellation_point:
8892 case OMPD_flush:
8893 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008894 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008895 case OMPD_declare_simd:
8896 case OMPD_declare_target:
8897 case OMPD_end_declare_target:
8898 case OMPD_simd:
8899 case OMPD_for:
8900 case OMPD_for_simd:
8901 case OMPD_sections:
8902 case OMPD_section:
8903 case OMPD_single:
8904 case OMPD_master:
8905 case OMPD_critical:
8906 case OMPD_taskgroup:
8907 case OMPD_distribute:
8908 case OMPD_ordered:
8909 case OMPD_atomic:
8910 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008911 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008912 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8913 case OMPD_unknown:
8914 llvm_unreachable("Unknown OpenMP directive");
8915 }
8916 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008917 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008918 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008919 case OMPD_parallel_for:
8920 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008921 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008922 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008923 case OMPD_teams_distribute_parallel_for:
8924 case OMPD_teams_distribute_parallel_for_simd:
8925 case OMPD_target_parallel_for:
8926 case OMPD_target_parallel_for_simd:
8927 case OMPD_target_teams_distribute_parallel_for:
8928 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008929 CaptureRegion = OMPD_parallel;
8930 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008931 case OMPD_for:
8932 case OMPD_for_simd:
8933 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008934 break;
8935 case OMPD_task:
8936 case OMPD_taskloop:
8937 case OMPD_taskloop_simd:
8938 case OMPD_target_data:
8939 case OMPD_target_enter_data:
8940 case OMPD_target_exit_data:
8941 case OMPD_target_update:
8942 case OMPD_teams:
8943 case OMPD_teams_distribute:
8944 case OMPD_teams_distribute_simd:
8945 case OMPD_target_teams_distribute:
8946 case OMPD_target_teams_distribute_simd:
8947 case OMPD_target:
8948 case OMPD_target_simd:
8949 case OMPD_target_parallel:
8950 case OMPD_cancel:
8951 case OMPD_parallel:
8952 case OMPD_parallel_sections:
8953 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008954 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008955 case OMPD_taskyield:
8956 case OMPD_barrier:
8957 case OMPD_taskwait:
8958 case OMPD_cancellation_point:
8959 case OMPD_flush:
8960 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008961 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008962 case OMPD_declare_simd:
8963 case OMPD_declare_target:
8964 case OMPD_end_declare_target:
8965 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008966 case OMPD_sections:
8967 case OMPD_section:
8968 case OMPD_single:
8969 case OMPD_master:
8970 case OMPD_critical:
8971 case OMPD_taskgroup:
8972 case OMPD_distribute:
8973 case OMPD_ordered:
8974 case OMPD_atomic:
8975 case OMPD_distribute_simd:
8976 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008977 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008978 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8979 case OMPD_unknown:
8980 llvm_unreachable("Unknown OpenMP directive");
8981 }
8982 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008983 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008984 switch (DKind) {
8985 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008986 case OMPD_teams_distribute_parallel_for_simd:
8987 case OMPD_teams_distribute:
8988 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008989 case OMPD_target_teams_distribute_parallel_for:
8990 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008991 case OMPD_target_teams_distribute:
8992 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008993 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008994 break;
8995 case OMPD_distribute_parallel_for:
8996 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008997 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008998 case OMPD_distribute_simd:
8999 // Do not capture thread_limit-clause expressions.
9000 break;
9001 case OMPD_parallel_for:
9002 case OMPD_parallel_for_simd:
9003 case OMPD_target_parallel_for_simd:
9004 case OMPD_target_parallel_for:
9005 case OMPD_task:
9006 case OMPD_taskloop:
9007 case OMPD_taskloop_simd:
9008 case OMPD_target_data:
9009 case OMPD_target_enter_data:
9010 case OMPD_target_exit_data:
9011 case OMPD_target_update:
9012 case OMPD_teams:
9013 case OMPD_target:
9014 case OMPD_target_simd:
9015 case OMPD_target_parallel:
9016 case OMPD_cancel:
9017 case OMPD_parallel:
9018 case OMPD_parallel_sections:
9019 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009020 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009021 case OMPD_taskyield:
9022 case OMPD_barrier:
9023 case OMPD_taskwait:
9024 case OMPD_cancellation_point:
9025 case OMPD_flush:
9026 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009027 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009028 case OMPD_declare_simd:
9029 case OMPD_declare_target:
9030 case OMPD_end_declare_target:
9031 case OMPD_simd:
9032 case OMPD_for:
9033 case OMPD_for_simd:
9034 case OMPD_sections:
9035 case OMPD_section:
9036 case OMPD_single:
9037 case OMPD_master:
9038 case OMPD_critical:
9039 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009040 case OMPD_ordered:
9041 case OMPD_atomic:
9042 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009043 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009044 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9045 case OMPD_unknown:
9046 llvm_unreachable("Unknown OpenMP directive");
9047 }
9048 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009049 case OMPC_device:
9050 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009051 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009052 case OMPD_target_enter_data:
9053 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009054 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009055 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009056 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009057 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009058 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009059 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009060 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009061 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009062 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009063 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009064 CaptureRegion = OMPD_task;
9065 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009066 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009067 // Do not capture device-clause expressions.
9068 break;
9069 case OMPD_teams_distribute_parallel_for:
9070 case OMPD_teams_distribute_parallel_for_simd:
9071 case OMPD_teams:
9072 case OMPD_teams_distribute:
9073 case OMPD_teams_distribute_simd:
9074 case OMPD_distribute_parallel_for:
9075 case OMPD_distribute_parallel_for_simd:
9076 case OMPD_task:
9077 case OMPD_taskloop:
9078 case OMPD_taskloop_simd:
9079 case OMPD_cancel:
9080 case OMPD_parallel:
9081 case OMPD_parallel_sections:
9082 case OMPD_parallel_for:
9083 case OMPD_parallel_for_simd:
9084 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009085 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009086 case OMPD_taskyield:
9087 case OMPD_barrier:
9088 case OMPD_taskwait:
9089 case OMPD_cancellation_point:
9090 case OMPD_flush:
9091 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009092 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009093 case OMPD_declare_simd:
9094 case OMPD_declare_target:
9095 case OMPD_end_declare_target:
9096 case OMPD_simd:
9097 case OMPD_for:
9098 case OMPD_for_simd:
9099 case OMPD_sections:
9100 case OMPD_section:
9101 case OMPD_single:
9102 case OMPD_master:
9103 case OMPD_critical:
9104 case OMPD_taskgroup:
9105 case OMPD_distribute:
9106 case OMPD_ordered:
9107 case OMPD_atomic:
9108 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009109 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009110 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9111 case OMPD_unknown:
9112 llvm_unreachable("Unknown OpenMP directive");
9113 }
9114 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009115 case OMPC_firstprivate:
9116 case OMPC_lastprivate:
9117 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009118 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009119 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009120 case OMPC_linear:
9121 case OMPC_default:
9122 case OMPC_proc_bind:
9123 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009124 case OMPC_safelen:
9125 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009126 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009127 case OMPC_collapse:
9128 case OMPC_private:
9129 case OMPC_shared:
9130 case OMPC_aligned:
9131 case OMPC_copyin:
9132 case OMPC_copyprivate:
9133 case OMPC_ordered:
9134 case OMPC_nowait:
9135 case OMPC_untied:
9136 case OMPC_mergeable:
9137 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009138 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009139 case OMPC_flush:
9140 case OMPC_read:
9141 case OMPC_write:
9142 case OMPC_update:
9143 case OMPC_capture:
9144 case OMPC_seq_cst:
9145 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009146 case OMPC_threads:
9147 case OMPC_simd:
9148 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009149 case OMPC_priority:
9150 case OMPC_grainsize:
9151 case OMPC_nogroup:
9152 case OMPC_num_tasks:
9153 case OMPC_hint:
9154 case OMPC_defaultmap:
9155 case OMPC_unknown:
9156 case OMPC_uniform:
9157 case OMPC_to:
9158 case OMPC_from:
9159 case OMPC_use_device_ptr:
9160 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009161 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009162 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009163 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009164 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009165 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009166 llvm_unreachable("Unexpected OpenMP clause.");
9167 }
9168 return CaptureRegion;
9169}
9170
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009171OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9172 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009173 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009174 SourceLocation NameModifierLoc,
9175 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009176 SourceLocation EndLoc) {
9177 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009178 Stmt *HelperValStmt = nullptr;
9179 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009180 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9181 !Condition->isInstantiationDependent() &&
9182 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009183 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009184 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009185 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009186
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009187 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009188
9189 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9190 CaptureRegion =
9191 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009192 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009193 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009194 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009195 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9196 HelperValStmt = buildPreInits(Context, Captures);
9197 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009198 }
9199
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009200 return new (Context)
9201 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9202 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009203}
9204
Alexey Bataev3778b602014-07-17 07:32:53 +00009205OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9206 SourceLocation StartLoc,
9207 SourceLocation LParenLoc,
9208 SourceLocation EndLoc) {
9209 Expr *ValExpr = Condition;
9210 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9211 !Condition->isInstantiationDependent() &&
9212 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009213 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009214 if (Val.isInvalid())
9215 return nullptr;
9216
Richard Smith03a4aa32016-06-23 19:02:52 +00009217 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009218 }
9219
9220 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9221}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009222ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9223 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009224 if (!Op)
9225 return ExprError();
9226
9227 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9228 public:
9229 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009230 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009231 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9232 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009233 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9234 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009235 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9236 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009237 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9238 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009239 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9240 QualType T,
9241 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009242 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9243 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009244 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9245 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009246 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009247 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009248 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009249 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9250 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009251 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9252 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009253 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9254 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009255 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009256 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009257 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009258 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9259 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009260 llvm_unreachable("conversion functions are permitted");
9261 }
9262 } ConvertDiagnoser;
9263 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9264}
9265
Alexey Bataeve3727102018-04-18 15:57:46 +00009266static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009267 OpenMPClauseKind CKind,
9268 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009269 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9270 !ValExpr->isInstantiationDependent()) {
9271 SourceLocation Loc = ValExpr->getExprLoc();
9272 ExprResult Value =
9273 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9274 if (Value.isInvalid())
9275 return false;
9276
9277 ValExpr = Value.get();
9278 // The expression must evaluate to a non-negative integer value.
9279 llvm::APSInt Result;
9280 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009281 Result.isSigned() &&
9282 !((!StrictlyPositive && Result.isNonNegative()) ||
9283 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009284 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009285 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9286 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009287 return false;
9288 }
9289 }
9290 return true;
9291}
9292
Alexey Bataev568a8332014-03-06 06:15:19 +00009293OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9294 SourceLocation StartLoc,
9295 SourceLocation LParenLoc,
9296 SourceLocation EndLoc) {
9297 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009298 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009299
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009300 // OpenMP [2.5, Restrictions]
9301 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009302 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009303 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009304 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009305
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009306 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009307 OpenMPDirectiveKind CaptureRegion =
9308 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9309 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009310 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009311 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009312 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9313 HelperValStmt = buildPreInits(Context, Captures);
9314 }
9315
9316 return new (Context) OMPNumThreadsClause(
9317 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009318}
9319
Alexey Bataev62c87d22014-03-21 04:51:18 +00009320ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009321 OpenMPClauseKind CKind,
9322 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009323 if (!E)
9324 return ExprError();
9325 if (E->isValueDependent() || E->isTypeDependent() ||
9326 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009327 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009328 llvm::APSInt Result;
9329 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9330 if (ICE.isInvalid())
9331 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009332 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9333 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009334 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009335 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9336 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009337 return ExprError();
9338 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009339 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9340 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9341 << E->getSourceRange();
9342 return ExprError();
9343 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009344 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9345 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009346 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009347 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009348 return ICE;
9349}
9350
9351OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9352 SourceLocation LParenLoc,
9353 SourceLocation EndLoc) {
9354 // OpenMP [2.8.1, simd construct, Description]
9355 // The parameter of the safelen clause must be a constant
9356 // positive integer expression.
9357 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9358 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009359 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009360 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009361 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009362}
9363
Alexey Bataev66b15b52015-08-21 11:14:16 +00009364OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9365 SourceLocation LParenLoc,
9366 SourceLocation EndLoc) {
9367 // OpenMP [2.8.1, simd construct, Description]
9368 // The parameter of the simdlen clause must be a constant
9369 // positive integer expression.
9370 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9371 if (Simdlen.isInvalid())
9372 return nullptr;
9373 return new (Context)
9374 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9375}
9376
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009377/// Tries to find omp_allocator_handle_t type.
9378static bool FindOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9379 QualType &OMPAllocatorHandleT) {
9380 if (!OMPAllocatorHandleT.isNull())
9381 return true;
9382 DeclarationName OMPAllocatorHandleTName =
9383 &S.getASTContext().Idents.get("omp_allocator_handle_t");
9384 auto *TD = dyn_cast_or_null<TypeDecl>(S.LookupSingleName(
9385 S.TUScope, OMPAllocatorHandleTName, Loc, Sema::LookupAnyName));
9386 if (!TD) {
9387 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9388 return false;
9389 }
9390 OMPAllocatorHandleT = S.getASTContext().getTypeDeclType(TD);
9391 return true;
9392}
9393
9394OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9395 SourceLocation LParenLoc,
9396 SourceLocation EndLoc) {
9397 // OpenMP [2.11.3, allocate Directive, Description]
9398 // allocator is an expression of omp_allocator_handle_t type.
9399 if (!FindOMPAllocatorHandleT(*this, A->getExprLoc(), OMPAllocatorHandleT))
9400 return nullptr;
9401
9402 ExprResult Allocator = DefaultLvalueConversion(A);
9403 if (Allocator.isInvalid())
9404 return nullptr;
9405 Allocator = PerformImplicitConversion(Allocator.get(), OMPAllocatorHandleT,
9406 Sema::AA_Initializing,
9407 /*AllowExplicit=*/true);
9408 if (Allocator.isInvalid())
9409 return nullptr;
9410 return new (Context)
9411 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9412}
9413
Alexander Musman64d33f12014-06-04 07:53:32 +00009414OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9415 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009416 SourceLocation LParenLoc,
9417 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009418 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009419 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009420 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009421 // The parameter of the collapse clause must be a constant
9422 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009423 ExprResult NumForLoopsResult =
9424 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9425 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009426 return nullptr;
9427 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009428 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009429}
9430
Alexey Bataev10e775f2015-07-30 11:36:16 +00009431OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9432 SourceLocation EndLoc,
9433 SourceLocation LParenLoc,
9434 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009435 // OpenMP [2.7.1, loop construct, Description]
9436 // OpenMP [2.8.1, simd construct, Description]
9437 // OpenMP [2.9.6, distribute construct, Description]
9438 // The parameter of the ordered clause must be a constant
9439 // positive integer expression if any.
9440 if (NumForLoops && LParenLoc.isValid()) {
9441 ExprResult NumForLoopsResult =
9442 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9443 if (NumForLoopsResult.isInvalid())
9444 return nullptr;
9445 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009446 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009447 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009448 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009449 auto *Clause = OMPOrderedClause::Create(
9450 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9451 StartLoc, LParenLoc, EndLoc);
9452 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9453 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009454}
9455
Alexey Bataeved09d242014-05-28 05:53:51 +00009456OMPClause *Sema::ActOnOpenMPSimpleClause(
9457 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9458 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009459 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009460 switch (Kind) {
9461 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009462 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009463 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9464 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009465 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009466 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009467 Res = ActOnOpenMPProcBindClause(
9468 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9469 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009470 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009471 case OMPC_atomic_default_mem_order:
9472 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9473 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9474 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9475 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009476 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009477 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009478 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009479 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009480 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009481 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009482 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009483 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009484 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009485 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009486 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009487 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009488 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009489 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009490 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009491 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009492 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009493 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009494 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009495 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009496 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009497 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009498 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009499 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009500 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009501 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009502 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009503 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009504 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009505 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009506 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009507 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009508 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009509 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009510 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009511 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009512 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009513 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009514 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009515 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009516 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009517 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009518 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009519 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009520 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009521 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009522 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009523 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009524 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009525 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009526 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009527 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009528 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009529 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009530 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009531 llvm_unreachable("Clause is not allowed.");
9532 }
9533 return Res;
9534}
9535
Alexey Bataev6402bca2015-12-28 07:25:51 +00009536static std::string
9537getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9538 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009539 SmallString<256> Buffer;
9540 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009541 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9542 unsigned Skipped = Exclude.size();
9543 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009544 for (unsigned I = First; I < Last; ++I) {
9545 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009546 --Skipped;
9547 continue;
9548 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009549 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9550 if (I == Bound - Skipped)
9551 Out << " or ";
9552 else if (I != Bound + 1 - Skipped)
9553 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009554 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009555 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009556}
9557
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009558OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9559 SourceLocation KindKwLoc,
9560 SourceLocation StartLoc,
9561 SourceLocation LParenLoc,
9562 SourceLocation EndLoc) {
9563 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009564 static_assert(OMPC_DEFAULT_unknown > 0,
9565 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009566 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009567 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9568 /*Last=*/OMPC_DEFAULT_unknown)
9569 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009570 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009572 switch (Kind) {
9573 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009574 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009575 break;
9576 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009577 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009578 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009579 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009580 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009581 break;
9582 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009583 return new (Context)
9584 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009585}
9586
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009587OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9588 SourceLocation KindKwLoc,
9589 SourceLocation StartLoc,
9590 SourceLocation LParenLoc,
9591 SourceLocation EndLoc) {
9592 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009593 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009594 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9595 /*Last=*/OMPC_PROC_BIND_unknown)
9596 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009597 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009598 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009599 return new (Context)
9600 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009601}
9602
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009603OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9604 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9605 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9606 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9607 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9608 << getListOfPossibleValues(
9609 OMPC_atomic_default_mem_order, /*First=*/0,
9610 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9611 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9612 return nullptr;
9613 }
9614 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9615 LParenLoc, EndLoc);
9616}
9617
Alexey Bataev56dafe82014-06-20 07:16:17 +00009618OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009619 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009620 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009621 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009622 SourceLocation EndLoc) {
9623 OMPClause *Res = nullptr;
9624 switch (Kind) {
9625 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009626 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9627 assert(Argument.size() == NumberOfElements &&
9628 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009629 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009630 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9631 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9632 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9633 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9634 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009635 break;
9636 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009637 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9638 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9639 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9640 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009641 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009642 case OMPC_dist_schedule:
9643 Res = ActOnOpenMPDistScheduleClause(
9644 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9645 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9646 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009647 case OMPC_defaultmap:
9648 enum { Modifier, DefaultmapKind };
9649 Res = ActOnOpenMPDefaultmapClause(
9650 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9651 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009652 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9653 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009654 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009655 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009656 case OMPC_num_threads:
9657 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009658 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009659 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009660 case OMPC_collapse:
9661 case OMPC_default:
9662 case OMPC_proc_bind:
9663 case OMPC_private:
9664 case OMPC_firstprivate:
9665 case OMPC_lastprivate:
9666 case OMPC_shared:
9667 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009668 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009669 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009670 case OMPC_linear:
9671 case OMPC_aligned:
9672 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009673 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009674 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009675 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009676 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009677 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009678 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009679 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009680 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009681 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009682 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009683 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009684 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009685 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009686 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009687 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009688 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009689 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009690 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009691 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009692 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009693 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009694 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009695 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009696 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009697 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009698 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009699 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009700 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009701 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009702 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009703 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009704 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009705 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009706 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009707 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009708 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009709 llvm_unreachable("Clause is not allowed.");
9710 }
9711 return Res;
9712}
9713
Alexey Bataev6402bca2015-12-28 07:25:51 +00009714static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9715 OpenMPScheduleClauseModifier M2,
9716 SourceLocation M1Loc, SourceLocation M2Loc) {
9717 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9718 SmallVector<unsigned, 2> Excluded;
9719 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9720 Excluded.push_back(M2);
9721 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9722 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9723 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9724 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9725 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9726 << getListOfPossibleValues(OMPC_schedule,
9727 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9728 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9729 Excluded)
9730 << getOpenMPClauseName(OMPC_schedule);
9731 return true;
9732 }
9733 return false;
9734}
9735
Alexey Bataev56dafe82014-06-20 07:16:17 +00009736OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009737 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009738 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009739 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9740 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9741 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9742 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9743 return nullptr;
9744 // OpenMP, 2.7.1, Loop Construct, Restrictions
9745 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9746 // but not both.
9747 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9748 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9749 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9750 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9751 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9752 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9753 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9754 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9755 return nullptr;
9756 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009757 if (Kind == OMPC_SCHEDULE_unknown) {
9758 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009759 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9760 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9761 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9762 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9763 Exclude);
9764 } else {
9765 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9766 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009767 }
9768 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9769 << Values << getOpenMPClauseName(OMPC_schedule);
9770 return nullptr;
9771 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009772 // OpenMP, 2.7.1, Loop Construct, Restrictions
9773 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9774 // schedule(guided).
9775 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9776 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9777 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9778 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9779 diag::err_omp_schedule_nonmonotonic_static);
9780 return nullptr;
9781 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009782 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009783 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009784 if (ChunkSize) {
9785 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9786 !ChunkSize->isInstantiationDependent() &&
9787 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009788 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009789 ExprResult Val =
9790 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9791 if (Val.isInvalid())
9792 return nullptr;
9793
9794 ValExpr = Val.get();
9795
9796 // OpenMP [2.7.1, Restrictions]
9797 // chunk_size must be a loop invariant integer expression with a positive
9798 // value.
9799 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009800 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9801 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9802 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009803 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009804 return nullptr;
9805 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009806 } else if (getOpenMPCaptureRegionForClause(
9807 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9808 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009809 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009810 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009811 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009812 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9813 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009814 }
9815 }
9816 }
9817
Alexey Bataev6402bca2015-12-28 07:25:51 +00009818 return new (Context)
9819 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009820 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009821}
9822
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009823OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9824 SourceLocation StartLoc,
9825 SourceLocation EndLoc) {
9826 OMPClause *Res = nullptr;
9827 switch (Kind) {
9828 case OMPC_ordered:
9829 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9830 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009831 case OMPC_nowait:
9832 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9833 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009834 case OMPC_untied:
9835 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9836 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009837 case OMPC_mergeable:
9838 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9839 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009840 case OMPC_read:
9841 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9842 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009843 case OMPC_write:
9844 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9845 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009846 case OMPC_update:
9847 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9848 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009849 case OMPC_capture:
9850 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9851 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009852 case OMPC_seq_cst:
9853 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9854 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009855 case OMPC_threads:
9856 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9857 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009858 case OMPC_simd:
9859 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9860 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009861 case OMPC_nogroup:
9862 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9863 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009864 case OMPC_unified_address:
9865 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9866 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009867 case OMPC_unified_shared_memory:
9868 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9869 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009870 case OMPC_reverse_offload:
9871 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9872 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009873 case OMPC_dynamic_allocators:
9874 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9875 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009876 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009877 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009878 case OMPC_num_threads:
9879 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009880 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009881 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009882 case OMPC_collapse:
9883 case OMPC_schedule:
9884 case OMPC_private:
9885 case OMPC_firstprivate:
9886 case OMPC_lastprivate:
9887 case OMPC_shared:
9888 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009889 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009890 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009891 case OMPC_linear:
9892 case OMPC_aligned:
9893 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009894 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009895 case OMPC_default:
9896 case OMPC_proc_bind:
9897 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009898 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009899 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009900 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009901 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009902 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009903 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009904 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009905 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009906 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009907 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009908 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009909 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009910 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009911 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009912 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009913 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009914 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009915 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009916 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009917 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009918 llvm_unreachable("Clause is not allowed.");
9919 }
9920 return Res;
9921}
9922
Alexey Bataev236070f2014-06-20 11:19:47 +00009923OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9924 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009925 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009926 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9927}
9928
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009929OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9930 SourceLocation EndLoc) {
9931 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9932}
9933
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009934OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9935 SourceLocation EndLoc) {
9936 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9937}
9938
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009939OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9940 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009941 return new (Context) OMPReadClause(StartLoc, EndLoc);
9942}
9943
Alexey Bataevdea47612014-07-23 07:46:59 +00009944OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9945 SourceLocation EndLoc) {
9946 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9947}
9948
Alexey Bataev67a4f222014-07-23 10:25:33 +00009949OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9950 SourceLocation EndLoc) {
9951 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9952}
9953
Alexey Bataev459dec02014-07-24 06:46:57 +00009954OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9955 SourceLocation EndLoc) {
9956 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9957}
9958
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009959OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9960 SourceLocation EndLoc) {
9961 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9962}
9963
Alexey Bataev346265e2015-09-25 10:37:12 +00009964OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9965 SourceLocation EndLoc) {
9966 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9967}
9968
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009969OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9970 SourceLocation EndLoc) {
9971 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9972}
9973
Alexey Bataevb825de12015-12-07 10:51:44 +00009974OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9975 SourceLocation EndLoc) {
9976 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9977}
9978
Kelvin Li1408f912018-09-26 04:28:39 +00009979OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9980 SourceLocation EndLoc) {
9981 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9982}
9983
Patrick Lyster4a370b92018-10-01 13:47:43 +00009984OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9985 SourceLocation EndLoc) {
9986 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9987}
9988
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009989OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9990 SourceLocation EndLoc) {
9991 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9992}
9993
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009994OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9995 SourceLocation EndLoc) {
9996 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9997}
9998
Alexey Bataevc5e02582014-06-16 07:08:35 +00009999OMPClause *Sema::ActOnOpenMPVarListClause(
10000 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010001 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10002 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10003 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010004 OpenMPLinearClauseKind LinKind,
10005 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010006 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10007 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10008 SourceLocation StartLoc = Locs.StartLoc;
10009 SourceLocation LParenLoc = Locs.LParenLoc;
10010 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010011 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010012 switch (Kind) {
10013 case OMPC_private:
10014 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10015 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010016 case OMPC_firstprivate:
10017 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10018 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010019 case OMPC_lastprivate:
10020 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10021 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010022 case OMPC_shared:
10023 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10024 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010025 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010026 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010027 EndLoc, ReductionOrMapperIdScopeSpec,
10028 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010029 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010030 case OMPC_task_reduction:
10031 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010032 EndLoc, ReductionOrMapperIdScopeSpec,
10033 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010034 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010035 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010036 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10037 EndLoc, ReductionOrMapperIdScopeSpec,
10038 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010039 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010040 case OMPC_linear:
10041 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010042 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010043 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010044 case OMPC_aligned:
10045 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10046 ColonLoc, EndLoc);
10047 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010048 case OMPC_copyin:
10049 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10050 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010051 case OMPC_copyprivate:
10052 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10053 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010054 case OMPC_flush:
10055 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10056 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010057 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010058 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010059 StartLoc, LParenLoc, EndLoc);
10060 break;
10061 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010062 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10063 ReductionOrMapperIdScopeSpec,
10064 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10065 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010066 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010067 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010068 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10069 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010070 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010071 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010072 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10073 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010074 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010075 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010076 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010077 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010078 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010079 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010080 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010081 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010082 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010083 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010084 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010085 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010086 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010087 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010088 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010089 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010090 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010091 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010092 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010093 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010094 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010095 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010096 case OMPC_allocate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010097 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010098 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010099 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010100 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010101 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010102 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010103 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010104 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010105 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010106 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010107 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010108 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010109 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010110 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010111 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010112 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010113 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010114 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010115 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010116 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010117 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010118 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010119 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010120 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010121 llvm_unreachable("Clause is not allowed.");
10122 }
10123 return Res;
10124}
10125
Alexey Bataev90c228f2016-02-08 09:29:13 +000010126ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010127 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010128 ExprResult Res = BuildDeclRefExpr(
10129 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10130 if (!Res.isUsable())
10131 return ExprError();
10132 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10133 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10134 if (!Res.isUsable())
10135 return ExprError();
10136 }
10137 if (VK != VK_LValue && Res.get()->isGLValue()) {
10138 Res = DefaultLvalueConversion(Res.get());
10139 if (!Res.isUsable())
10140 return ExprError();
10141 }
10142 return Res;
10143}
10144
Alexey Bataev60da77e2016-02-29 05:54:20 +000010145static std::pair<ValueDecl *, bool>
10146getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
10147 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010148 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
10149 RefExpr->containsUnexpandedParameterPack())
10150 return std::make_pair(nullptr, true);
10151
Alexey Bataevd985eda2016-02-10 11:29:16 +000010152 // OpenMP [3.1, C/C++]
10153 // A list item is a variable name.
10154 // OpenMP [2.9.3.3, Restrictions, p.1]
10155 // A variable that is part of another variable (as an array or
10156 // structure element) cannot appear in a private clause.
10157 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010158 enum {
10159 NoArrayExpr = -1,
10160 ArraySubscript = 0,
10161 OMPArraySection = 1
10162 } IsArrayExpr = NoArrayExpr;
10163 if (AllowArraySection) {
10164 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010165 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010166 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10167 Base = TempASE->getBase()->IgnoreParenImpCasts();
10168 RefExpr = Base;
10169 IsArrayExpr = ArraySubscript;
10170 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010171 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010172 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10173 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10174 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10175 Base = TempASE->getBase()->IgnoreParenImpCasts();
10176 RefExpr = Base;
10177 IsArrayExpr = OMPArraySection;
10178 }
10179 }
10180 ELoc = RefExpr->getExprLoc();
10181 ERange = RefExpr->getSourceRange();
10182 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +000010183 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10184 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10185 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10186 (S.getCurrentThisType().isNull() || !ME ||
10187 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10188 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010189 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010190 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10191 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000010192 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010193 S.Diag(ELoc,
10194 AllowArraySection
10195 ? diag::err_omp_expected_var_name_member_expr_or_array_item
10196 : diag::err_omp_expected_var_name_member_expr)
10197 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10198 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010199 return std::make_pair(nullptr, false);
10200 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010201 return std::make_pair(
10202 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010203}
10204
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010205OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10206 SourceLocation StartLoc,
10207 SourceLocation LParenLoc,
10208 SourceLocation EndLoc) {
10209 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010210 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010211 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010212 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010213 SourceLocation ELoc;
10214 SourceRange ERange;
10215 Expr *SimpleRefExpr = RefExpr;
10216 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010217 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010218 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010219 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010220 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010221 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010222 ValueDecl *D = Res.first;
10223 if (!D)
10224 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010225
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010226 QualType Type = D->getType();
10227 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010228
10229 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10230 // A variable that appears in a private clause must not have an incomplete
10231 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010232 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010233 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010234 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010235
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010236 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10237 // A variable that is privatized must not have a const-qualified type
10238 // unless it is of class type with a mutable member. This restriction does
10239 // not apply to the firstprivate clause.
10240 //
10241 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10242 // A variable that appears in a private clause must not have a
10243 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010244 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010245 continue;
10246
Alexey Bataev758e55e2013-09-06 18:03:48 +000010247 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10248 // in a Construct]
10249 // Variables with the predetermined data-sharing attributes may not be
10250 // listed in data-sharing attributes clauses, except for the cases
10251 // listed below. For these exceptions only, listing a predetermined
10252 // variable in a data-sharing attribute clause is allowed and overrides
10253 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010254 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010255 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010256 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10257 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010258 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010259 continue;
10260 }
10261
Alexey Bataeve3727102018-04-18 15:57:46 +000010262 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010263 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010264 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010265 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010266 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10267 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010268 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010269 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010270 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010271 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010272 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010273 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010274 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010275 continue;
10276 }
10277
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010278 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10279 // A list item cannot appear in both a map clause and a data-sharing
10280 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010281 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010282 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010283 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010284 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010285 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10286 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10287 ConflictKind = WhereFoundClauseKind;
10288 return true;
10289 })) {
10290 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010291 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010292 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010293 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010294 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010295 continue;
10296 }
10297 }
10298
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010299 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10300 // A variable of class type (or array thereof) that appears in a private
10301 // clause requires an accessible, unambiguous default constructor for the
10302 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010303 // Generate helper private variable and initialize it with the default
10304 // value. The address of the original variable is replaced by the address of
10305 // the new private variable in CodeGen. This new variable is not added to
10306 // IdResolver, so the code in the OpenMP region uses original variable for
10307 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010308 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010309 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010310 buildVarDecl(*this, ELoc, Type, D->getName(),
10311 D->hasAttrs() ? &D->getAttrs() : nullptr,
10312 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010313 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010314 if (VDPrivate->isInvalidDecl())
10315 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010316 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010317 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010318
Alexey Bataev90c228f2016-02-08 09:29:13 +000010319 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010320 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010321 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010322 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010323 Vars.push_back((VD || CurContext->isDependentContext())
10324 ? RefExpr->IgnoreParens()
10325 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010326 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010327 }
10328
Alexey Bataeved09d242014-05-28 05:53:51 +000010329 if (Vars.empty())
10330 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010331
Alexey Bataev03b340a2014-10-21 03:16:40 +000010332 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10333 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010334}
10335
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010336namespace {
10337class DiagsUninitializedSeveretyRAII {
10338private:
10339 DiagnosticsEngine &Diags;
10340 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010341 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010342
10343public:
10344 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10345 bool IsIgnored)
10346 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10347 if (!IsIgnored) {
10348 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10349 /*Map*/ diag::Severity::Ignored, Loc);
10350 }
10351 }
10352 ~DiagsUninitializedSeveretyRAII() {
10353 if (!IsIgnored)
10354 Diags.popMappings(SavedLoc);
10355 }
10356};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010357}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010358
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010359OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10360 SourceLocation StartLoc,
10361 SourceLocation LParenLoc,
10362 SourceLocation EndLoc) {
10363 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010364 SmallVector<Expr *, 8> PrivateCopies;
10365 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010366 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010367 bool IsImplicitClause =
10368 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010369 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010370
Alexey Bataeve3727102018-04-18 15:57:46 +000010371 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010372 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010373 SourceLocation ELoc;
10374 SourceRange ERange;
10375 Expr *SimpleRefExpr = RefExpr;
10376 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010377 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010378 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010379 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010380 PrivateCopies.push_back(nullptr);
10381 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010382 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010383 ValueDecl *D = Res.first;
10384 if (!D)
10385 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010386
Alexey Bataev60da77e2016-02-29 05:54:20 +000010387 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010388 QualType Type = D->getType();
10389 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010390
10391 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10392 // A variable that appears in a private clause must not have an incomplete
10393 // type or a reference type.
10394 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010395 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010396 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010397 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010398
10399 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10400 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010401 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010402 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010403 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010404
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010405 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010406 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010407 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010408 DSAStackTy::DSAVarData DVar =
10409 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010410 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010411 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010412 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010413 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10414 // A list item that specifies a given variable may not appear in more
10415 // than one clause on the same directive, except that a variable may be
10416 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010417 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10418 // A list item may appear in a firstprivate or lastprivate clause but not
10419 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010420 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010421 (isOpenMPDistributeDirective(CurrDir) ||
10422 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010423 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010424 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010425 << getOpenMPClauseName(DVar.CKind)
10426 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010427 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010428 continue;
10429 }
10430
10431 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10432 // in a Construct]
10433 // Variables with the predetermined data-sharing attributes may not be
10434 // listed in data-sharing attributes clauses, except for the cases
10435 // listed below. For these exceptions only, listing a predetermined
10436 // variable in a data-sharing attribute clause is allowed and overrides
10437 // the variable's predetermined data-sharing attributes.
10438 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10439 // in a Construct, C/C++, p.2]
10440 // Variables with const-qualified type having no mutable member may be
10441 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010442 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010443 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10444 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010445 << getOpenMPClauseName(DVar.CKind)
10446 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010447 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010448 continue;
10449 }
10450
10451 // OpenMP [2.9.3.4, Restrictions, p.2]
10452 // A list item that is private within a parallel region must not appear
10453 // in a firstprivate clause on a worksharing construct if any of the
10454 // worksharing regions arising from the worksharing construct ever bind
10455 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010456 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10457 // A list item that is private within a teams region must not appear in a
10458 // firstprivate clause on a distribute construct if any of the distribute
10459 // regions arising from the distribute construct ever bind to any of the
10460 // teams regions arising from the teams construct.
10461 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10462 // A list item that appears in a reduction clause of a teams construct
10463 // must not appear in a firstprivate clause on a distribute construct if
10464 // any of the distribute regions arising from the distribute construct
10465 // ever bind to any of the teams regions arising from the teams construct.
10466 if ((isOpenMPWorksharingDirective(CurrDir) ||
10467 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010468 !isOpenMPParallelDirective(CurrDir) &&
10469 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010470 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010471 if (DVar.CKind != OMPC_shared &&
10472 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010473 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010474 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010475 Diag(ELoc, diag::err_omp_required_access)
10476 << getOpenMPClauseName(OMPC_firstprivate)
10477 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010478 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010479 continue;
10480 }
10481 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010482 // OpenMP [2.9.3.4, Restrictions, p.3]
10483 // A list item that appears in a reduction clause of a parallel construct
10484 // must not appear in a firstprivate clause on a worksharing or task
10485 // construct if any of the worksharing or task regions arising from the
10486 // worksharing or task construct ever bind to any of the parallel regions
10487 // arising from the parallel construct.
10488 // OpenMP [2.9.3.4, Restrictions, p.4]
10489 // A list item that appears in a reduction clause in worksharing
10490 // construct must not appear in a firstprivate clause in a task construct
10491 // encountered during execution of any of the worksharing regions arising
10492 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010493 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010494 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010495 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10496 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010497 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010498 isOpenMPWorksharingDirective(K) ||
10499 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010500 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010501 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010502 if (DVar.CKind == OMPC_reduction &&
10503 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010504 isOpenMPWorksharingDirective(DVar.DKind) ||
10505 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010506 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10507 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010508 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010509 continue;
10510 }
10511 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010512
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010513 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10514 // A list item cannot appear in both a map clause and a data-sharing
10515 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010516 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010517 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010518 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010519 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010520 [&ConflictKind](
10521 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10522 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010523 ConflictKind = WhereFoundClauseKind;
10524 return true;
10525 })) {
10526 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010527 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010528 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010529 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010530 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010531 continue;
10532 }
10533 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010534 }
10535
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010536 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010537 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010538 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010539 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10540 << getOpenMPClauseName(OMPC_firstprivate) << Type
10541 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10542 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010543 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010544 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010545 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010546 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010547 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010548 continue;
10549 }
10550
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010551 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010552 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010553 buildVarDecl(*this, ELoc, Type, D->getName(),
10554 D->hasAttrs() ? &D->getAttrs() : nullptr,
10555 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010556 // Generate helper private variable and initialize it with the value of the
10557 // original variable. The address of the original variable is replaced by
10558 // the address of the new private variable in the CodeGen. This new variable
10559 // is not added to IdResolver, so the code in the OpenMP region uses
10560 // original variable for proper diagnostics and variable capturing.
10561 Expr *VDInitRefExpr = nullptr;
10562 // For arrays generate initializer for single element and replace it by the
10563 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010564 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010565 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010566 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010567 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010568 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010569 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010570 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10571 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010572 InitializedEntity Entity =
10573 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010574 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10575
10576 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10577 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10578 if (Result.isInvalid())
10579 VDPrivate->setInvalidDecl();
10580 else
10581 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010582 // Remove temp variable declaration.
10583 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010584 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010585 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10586 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010587 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10588 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010589 AddInitializerToDecl(VDPrivate,
10590 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010591 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010592 }
10593 if (VDPrivate->isInvalidDecl()) {
10594 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010595 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010596 diag::note_omp_task_predetermined_firstprivate_here);
10597 }
10598 continue;
10599 }
10600 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010601 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010602 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10603 RefExpr->getExprLoc());
10604 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010605 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010606 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010607 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010608 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010609 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010610 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010611 ExprCaptures.push_back(Ref->getDecl());
10612 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010613 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010614 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010615 Vars.push_back((VD || CurContext->isDependentContext())
10616 ? RefExpr->IgnoreParens()
10617 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010618 PrivateCopies.push_back(VDPrivateRefExpr);
10619 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010620 }
10621
Alexey Bataeved09d242014-05-28 05:53:51 +000010622 if (Vars.empty())
10623 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010624
10625 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010626 Vars, PrivateCopies, Inits,
10627 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010628}
10629
Alexander Musman1bb328c2014-06-04 13:06:39 +000010630OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10631 SourceLocation StartLoc,
10632 SourceLocation LParenLoc,
10633 SourceLocation EndLoc) {
10634 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010635 SmallVector<Expr *, 8> SrcExprs;
10636 SmallVector<Expr *, 8> DstExprs;
10637 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010638 SmallVector<Decl *, 4> ExprCaptures;
10639 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010640 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +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 Bataev74caaf22016-02-20 04:09:36 +000010646 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010647 // It will be analyzed later.
10648 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010649 SrcExprs.push_back(nullptr);
10650 DstExprs.push_back(nullptr);
10651 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010652 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010653 ValueDecl *D = Res.first;
10654 if (!D)
10655 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010656
Alexey Bataev74caaf22016-02-20 04:09:36 +000010657 QualType Type = D->getType();
10658 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010659
10660 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10661 // A variable that appears in a lastprivate clause must not have an
10662 // incomplete type or a reference type.
10663 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010664 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010665 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010666 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010667
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010668 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10669 // A variable that is privatized must not have a const-qualified type
10670 // unless it is of class type with a mutable member. This restriction does
10671 // not apply to the firstprivate clause.
10672 //
10673 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10674 // A variable that appears in a lastprivate clause must not have a
10675 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010676 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010677 continue;
10678
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010679 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010680 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10681 // in a Construct]
10682 // Variables with the predetermined data-sharing attributes may not be
10683 // listed in data-sharing attributes clauses, except for the cases
10684 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010685 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10686 // A list item may appear in a firstprivate or lastprivate clause but not
10687 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010688 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010689 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010690 (isOpenMPDistributeDirective(CurrDir) ||
10691 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010692 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10693 Diag(ELoc, diag::err_omp_wrong_dsa)
10694 << getOpenMPClauseName(DVar.CKind)
10695 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010696 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010697 continue;
10698 }
10699
Alexey Bataevf29276e2014-06-18 04:14:57 +000010700 // OpenMP [2.14.3.5, Restrictions, p.2]
10701 // A list item that is private within a parallel region, or that appears in
10702 // the reduction clause of a parallel construct, must not appear in a
10703 // lastprivate clause on a worksharing construct if any of the corresponding
10704 // worksharing regions ever binds to any of the corresponding parallel
10705 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010706 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010707 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010708 !isOpenMPParallelDirective(CurrDir) &&
10709 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010710 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010711 if (DVar.CKind != OMPC_shared) {
10712 Diag(ELoc, diag::err_omp_required_access)
10713 << getOpenMPClauseName(OMPC_lastprivate)
10714 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010715 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010716 continue;
10717 }
10718 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010719
Alexander Musman1bb328c2014-06-04 13:06:39 +000010720 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010721 // A variable of class type (or array thereof) that appears in a
10722 // lastprivate clause requires an accessible, unambiguous default
10723 // constructor for the class type, unless the list item is also specified
10724 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010725 // A variable of class type (or array thereof) that appears in a
10726 // lastprivate clause requires an accessible, unambiguous copy assignment
10727 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010728 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010729 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10730 Type.getUnqualifiedType(), ".lastprivate.src",
10731 D->hasAttrs() ? &D->getAttrs() : nullptr);
10732 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010733 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010734 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010735 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010736 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010737 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010738 // For arrays generate assignment operation for single element and replace
10739 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010740 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10741 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010742 if (AssignmentOp.isInvalid())
10743 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010744 AssignmentOp =
10745 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010746 if (AssignmentOp.isInvalid())
10747 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010748
Alexey Bataev74caaf22016-02-20 04:09:36 +000010749 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010750 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010751 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010752 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010753 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010754 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010755 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010756 ExprCaptures.push_back(Ref->getDecl());
10757 }
10758 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010759 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010760 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010761 ExprResult RefRes = DefaultLvalueConversion(Ref);
10762 if (!RefRes.isUsable())
10763 continue;
10764 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010765 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10766 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010767 if (!PostUpdateRes.isUsable())
10768 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010769 ExprPostUpdates.push_back(
10770 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010771 }
10772 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010773 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010774 Vars.push_back((VD || CurContext->isDependentContext())
10775 ? RefExpr->IgnoreParens()
10776 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010777 SrcExprs.push_back(PseudoSrcExpr);
10778 DstExprs.push_back(PseudoDstExpr);
10779 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010780 }
10781
10782 if (Vars.empty())
10783 return nullptr;
10784
10785 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010786 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010787 buildPreInits(Context, ExprCaptures),
10788 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010789}
10790
Alexey Bataev758e55e2013-09-06 18:03:48 +000010791OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10792 SourceLocation StartLoc,
10793 SourceLocation LParenLoc,
10794 SourceLocation EndLoc) {
10795 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010796 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010797 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010798 SourceLocation ELoc;
10799 SourceRange ERange;
10800 Expr *SimpleRefExpr = RefExpr;
10801 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010802 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010803 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010804 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010805 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010806 ValueDecl *D = Res.first;
10807 if (!D)
10808 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010809
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010810 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010811 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10812 // in a Construct]
10813 // Variables with the predetermined data-sharing attributes may not be
10814 // listed in data-sharing attributes clauses, except for the cases
10815 // listed below. For these exceptions only, listing a predetermined
10816 // variable in a data-sharing attribute clause is allowed and overrides
10817 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010818 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010819 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10820 DVar.RefExpr) {
10821 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10822 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010823 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010824 continue;
10825 }
10826
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010827 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010828 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010829 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010830 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010831 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10832 ? RefExpr->IgnoreParens()
10833 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010834 }
10835
Alexey Bataeved09d242014-05-28 05:53:51 +000010836 if (Vars.empty())
10837 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010838
10839 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10840}
10841
Alexey Bataevc5e02582014-06-16 07:08:35 +000010842namespace {
10843class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10844 DSAStackTy *Stack;
10845
10846public:
10847 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010848 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10849 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010850 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10851 return false;
10852 if (DVar.CKind != OMPC_unknown)
10853 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010854 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010855 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010856 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010857 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010858 }
10859 return false;
10860 }
10861 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010862 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010863 if (Child && Visit(Child))
10864 return true;
10865 }
10866 return false;
10867 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010868 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010869};
Alexey Bataev23b69422014-06-18 07:08:49 +000010870} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010871
Alexey Bataev60da77e2016-02-29 05:54:20 +000010872namespace {
10873// Transform MemberExpression for specified FieldDecl of current class to
10874// DeclRefExpr to specified OMPCapturedExprDecl.
10875class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10876 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010877 ValueDecl *Field = nullptr;
10878 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010879
10880public:
10881 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10882 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10883
10884 ExprResult TransformMemberExpr(MemberExpr *E) {
10885 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10886 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010887 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010888 return CapturedExpr;
10889 }
10890 return BaseTransform::TransformMemberExpr(E);
10891 }
10892 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10893};
10894} // namespace
10895
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010896template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010897static T filterLookupForUDReductionAndMapper(
10898 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010899 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010900 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010901 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010902 return Res;
10903 }
10904 }
10905 return T();
10906}
10907
Alexey Bataev43b90b72018-09-12 16:31:59 +000010908static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10909 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10910
10911 for (auto RD : D->redecls()) {
10912 // Don't bother with extra checks if we already know this one isn't visible.
10913 if (RD == D)
10914 continue;
10915
10916 auto ND = cast<NamedDecl>(RD);
10917 if (LookupResult::isVisible(SemaRef, ND))
10918 return ND;
10919 }
10920
10921 return nullptr;
10922}
10923
10924static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010925argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010926 SourceLocation Loc, QualType Ty,
10927 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10928 // Find all of the associated namespaces and classes based on the
10929 // arguments we have.
10930 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10931 Sema::AssociatedClassSet AssociatedClasses;
10932 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10933 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10934 AssociatedClasses);
10935
10936 // C++ [basic.lookup.argdep]p3:
10937 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10938 // and let Y be the lookup set produced by argument dependent
10939 // lookup (defined as follows). If X contains [...] then Y is
10940 // empty. Otherwise Y is the set of declarations found in the
10941 // namespaces associated with the argument types as described
10942 // below. The set of declarations found by the lookup of the name
10943 // is the union of X and Y.
10944 //
10945 // Here, we compute Y and add its members to the overloaded
10946 // candidate set.
10947 for (auto *NS : AssociatedNamespaces) {
10948 // When considering an associated namespace, the lookup is the
10949 // same as the lookup performed when the associated namespace is
10950 // used as a qualifier (3.4.3.2) except that:
10951 //
10952 // -- Any using-directives in the associated namespace are
10953 // ignored.
10954 //
10955 // -- Any namespace-scope friend functions declared in
10956 // associated classes are visible within their respective
10957 // namespaces even if they are not visible during an ordinary
10958 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000010959 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000010960 for (auto *D : R) {
10961 auto *Underlying = D;
10962 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10963 Underlying = USD->getTargetDecl();
10964
Michael Kruse4304e9d2019-02-19 16:38:20 +000010965 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
10966 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000010967 continue;
10968
10969 if (!SemaRef.isVisible(D)) {
10970 D = findAcceptableDecl(SemaRef, D);
10971 if (!D)
10972 continue;
10973 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10974 Underlying = USD->getTargetDecl();
10975 }
10976 Lookups.emplace_back();
10977 Lookups.back().addDecl(Underlying);
10978 }
10979 }
10980}
10981
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010982static ExprResult
10983buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10984 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10985 const DeclarationNameInfo &ReductionId, QualType Ty,
10986 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10987 if (ReductionIdScopeSpec.isInvalid())
10988 return ExprError();
10989 SmallVector<UnresolvedSet<8>, 4> Lookups;
10990 if (S) {
10991 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10992 Lookup.suppressDiagnostics();
10993 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010994 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010995 do {
10996 S = S->getParent();
10997 } while (S && !S->isDeclScope(D));
10998 if (S)
10999 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011000 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011001 Lookups.back().append(Lookup.begin(), Lookup.end());
11002 Lookup.clear();
11003 }
11004 } else if (auto *ULE =
11005 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11006 Lookups.push_back(UnresolvedSet<8>());
11007 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011008 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011009 if (D == PrevD)
11010 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011011 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011012 Lookups.back().addDecl(DRD);
11013 PrevD = D;
11014 }
11015 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011016 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11017 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011018 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011019 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011020 return !D->isInvalidDecl() &&
11021 (D->getType()->isDependentType() ||
11022 D->getType()->isInstantiationDependentType() ||
11023 D->getType()->containsUnexpandedParameterPack());
11024 })) {
11025 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011026 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011027 if (Set.empty())
11028 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011029 ResSet.append(Set.begin(), Set.end());
11030 // The last item marks the end of all declarations at the specified scope.
11031 ResSet.addDecl(Set[Set.size() - 1]);
11032 }
11033 return UnresolvedLookupExpr::Create(
11034 SemaRef.Context, /*NamingClass=*/nullptr,
11035 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11036 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11037 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011038 // Lookup inside the classes.
11039 // C++ [over.match.oper]p3:
11040 // For a unary operator @ with an operand of a type whose
11041 // cv-unqualified version is T1, and for a binary operator @ with
11042 // a left operand of a type whose cv-unqualified version is T1 and
11043 // a right operand of a type whose cv-unqualified version is T2,
11044 // three sets of candidate functions, designated member
11045 // candidates, non-member candidates and built-in candidates, are
11046 // constructed as follows:
11047 // -- If T1 is a complete class type or a class currently being
11048 // defined, the set of member candidates is the result of the
11049 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11050 // the set of member candidates is empty.
11051 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11052 Lookup.suppressDiagnostics();
11053 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11054 // Complete the type if it can be completed.
11055 // If the type is neither complete nor being defined, bail out now.
11056 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11057 TyRec->getDecl()->getDefinition()) {
11058 Lookup.clear();
11059 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11060 if (Lookup.empty()) {
11061 Lookups.emplace_back();
11062 Lookups.back().append(Lookup.begin(), Lookup.end());
11063 }
11064 }
11065 }
11066 // Perform ADL.
Alexey Bataev74a04e82019-03-13 19:31:34 +000011067 if (SemaRef.getLangOpts().CPlusPlus) {
11068 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11069 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11070 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11071 if (!D->isInvalidDecl() &&
11072 SemaRef.Context.hasSameType(D->getType(), Ty))
11073 return D;
11074 return nullptr;
11075 }))
11076 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11077 VK_LValue, Loc);
11078 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11079 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11080 if (!D->isInvalidDecl() &&
11081 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11082 !Ty.isMoreQualifiedThan(D->getType()))
11083 return D;
11084 return nullptr;
11085 })) {
11086 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11087 /*DetectVirtual=*/false);
11088 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11089 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11090 VD->getType().getUnqualifiedType()))) {
11091 if (SemaRef.CheckBaseClassAccess(
11092 Loc, VD->getType(), Ty, Paths.front(),
11093 /*DiagID=*/0) != Sema::AR_inaccessible) {
11094 SemaRef.BuildBasePathArray(Paths, BasePath);
11095 return SemaRef.BuildDeclRefExpr(
11096 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11097 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011098 }
11099 }
11100 }
11101 }
11102 if (ReductionIdScopeSpec.isSet()) {
11103 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11104 return ExprError();
11105 }
11106 return ExprEmpty();
11107}
11108
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011109namespace {
11110/// Data for the reduction-based clauses.
11111struct ReductionData {
11112 /// List of original reduction items.
11113 SmallVector<Expr *, 8> Vars;
11114 /// List of private copies of the reduction items.
11115 SmallVector<Expr *, 8> Privates;
11116 /// LHS expressions for the reduction_op expressions.
11117 SmallVector<Expr *, 8> LHSs;
11118 /// RHS expressions for the reduction_op expressions.
11119 SmallVector<Expr *, 8> RHSs;
11120 /// Reduction operation expression.
11121 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011122 /// Taskgroup descriptors for the corresponding reduction items in
11123 /// in_reduction clauses.
11124 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011125 /// List of captures for clause.
11126 SmallVector<Decl *, 4> ExprCaptures;
11127 /// List of postupdate expressions.
11128 SmallVector<Expr *, 4> ExprPostUpdates;
11129 ReductionData() = delete;
11130 /// Reserves required memory for the reduction data.
11131 ReductionData(unsigned Size) {
11132 Vars.reserve(Size);
11133 Privates.reserve(Size);
11134 LHSs.reserve(Size);
11135 RHSs.reserve(Size);
11136 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011137 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011138 ExprCaptures.reserve(Size);
11139 ExprPostUpdates.reserve(Size);
11140 }
11141 /// Stores reduction item and reduction operation only (required for dependent
11142 /// reduction item).
11143 void push(Expr *Item, Expr *ReductionOp) {
11144 Vars.emplace_back(Item);
11145 Privates.emplace_back(nullptr);
11146 LHSs.emplace_back(nullptr);
11147 RHSs.emplace_back(nullptr);
11148 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011149 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011150 }
11151 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011152 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11153 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011154 Vars.emplace_back(Item);
11155 Privates.emplace_back(Private);
11156 LHSs.emplace_back(LHS);
11157 RHSs.emplace_back(RHS);
11158 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011159 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011160 }
11161};
11162} // namespace
11163
Alexey Bataeve3727102018-04-18 15:57:46 +000011164static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011165 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11166 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11167 const Expr *Length = OASE->getLength();
11168 if (Length == nullptr) {
11169 // For array sections of the form [1:] or [:], we would need to analyze
11170 // the lower bound...
11171 if (OASE->getColonLoc().isValid())
11172 return false;
11173
11174 // This is an array subscript which has implicit length 1!
11175 SingleElement = true;
11176 ArraySizes.push_back(llvm::APSInt::get(1));
11177 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011178 Expr::EvalResult Result;
11179 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011180 return false;
11181
Fangrui Song407659a2018-11-30 23:41:18 +000011182 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011183 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11184 ArraySizes.push_back(ConstantLengthValue);
11185 }
11186
11187 // Get the base of this array section and walk up from there.
11188 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11189
11190 // We require length = 1 for all array sections except the right-most to
11191 // guarantee that the memory region is contiguous and has no holes in it.
11192 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11193 Length = TempOASE->getLength();
11194 if (Length == nullptr) {
11195 // For array sections of the form [1:] or [:], we would need to analyze
11196 // the lower bound...
11197 if (OASE->getColonLoc().isValid())
11198 return false;
11199
11200 // This is an array subscript which has implicit length 1!
11201 ArraySizes.push_back(llvm::APSInt::get(1));
11202 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011203 Expr::EvalResult Result;
11204 if (!Length->EvaluateAsInt(Result, Context))
11205 return false;
11206
11207 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11208 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011209 return false;
11210
11211 ArraySizes.push_back(ConstantLengthValue);
11212 }
11213 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11214 }
11215
11216 // If we have a single element, we don't need to add the implicit lengths.
11217 if (!SingleElement) {
11218 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11219 // Has implicit length 1!
11220 ArraySizes.push_back(llvm::APSInt::get(1));
11221 Base = TempASE->getBase()->IgnoreParenImpCasts();
11222 }
11223 }
11224
11225 // This array section can be privatized as a single value or as a constant
11226 // sized array.
11227 return true;
11228}
11229
Alexey Bataeve3727102018-04-18 15:57:46 +000011230static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011231 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11232 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11233 SourceLocation ColonLoc, SourceLocation EndLoc,
11234 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011235 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011236 DeclarationName DN = ReductionId.getName();
11237 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011238 BinaryOperatorKind BOK = BO_Comma;
11239
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011240 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011241 // OpenMP [2.14.3.6, reduction clause]
11242 // C
11243 // reduction-identifier is either an identifier or one of the following
11244 // operators: +, -, *, &, |, ^, && and ||
11245 // C++
11246 // reduction-identifier is either an id-expression or one of the following
11247 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011248 switch (OOK) {
11249 case OO_Plus:
11250 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011251 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011252 break;
11253 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011254 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011255 break;
11256 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011257 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011258 break;
11259 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011260 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011261 break;
11262 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011263 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011264 break;
11265 case OO_AmpAmp:
11266 BOK = BO_LAnd;
11267 break;
11268 case OO_PipePipe:
11269 BOK = BO_LOr;
11270 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011271 case OO_New:
11272 case OO_Delete:
11273 case OO_Array_New:
11274 case OO_Array_Delete:
11275 case OO_Slash:
11276 case OO_Percent:
11277 case OO_Tilde:
11278 case OO_Exclaim:
11279 case OO_Equal:
11280 case OO_Less:
11281 case OO_Greater:
11282 case OO_LessEqual:
11283 case OO_GreaterEqual:
11284 case OO_PlusEqual:
11285 case OO_MinusEqual:
11286 case OO_StarEqual:
11287 case OO_SlashEqual:
11288 case OO_PercentEqual:
11289 case OO_CaretEqual:
11290 case OO_AmpEqual:
11291 case OO_PipeEqual:
11292 case OO_LessLess:
11293 case OO_GreaterGreater:
11294 case OO_LessLessEqual:
11295 case OO_GreaterGreaterEqual:
11296 case OO_EqualEqual:
11297 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011298 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011299 case OO_PlusPlus:
11300 case OO_MinusMinus:
11301 case OO_Comma:
11302 case OO_ArrowStar:
11303 case OO_Arrow:
11304 case OO_Call:
11305 case OO_Subscript:
11306 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011307 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011308 case NUM_OVERLOADED_OPERATORS:
11309 llvm_unreachable("Unexpected reduction identifier");
11310 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011311 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011312 if (II->isStr("max"))
11313 BOK = BO_GT;
11314 else if (II->isStr("min"))
11315 BOK = BO_LT;
11316 }
11317 break;
11318 }
11319 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011320 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011321 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011322 else
11323 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011324 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011325
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011326 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11327 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011328 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011329 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011330 // OpenMP [2.1, C/C++]
11331 // A list item is a variable or array section, subject to the restrictions
11332 // specified in Section 2.4 on page 42 and in each of the sections
11333 // describing clauses and directives for which a list appears.
11334 // OpenMP [2.14.3.3, Restrictions, p.1]
11335 // A variable that is part of another variable (as an array or
11336 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011337 if (!FirstIter && IR != ER)
11338 ++IR;
11339 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011340 SourceLocation ELoc;
11341 SourceRange ERange;
11342 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011343 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011344 /*AllowArraySection=*/true);
11345 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011346 // Try to find 'declare reduction' corresponding construct before using
11347 // builtin/overloaded operators.
11348 QualType Type = Context.DependentTy;
11349 CXXCastPath BasePath;
11350 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011351 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011352 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011353 Expr *ReductionOp = nullptr;
11354 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011355 (DeclareReductionRef.isUnset() ||
11356 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011357 ReductionOp = DeclareReductionRef.get();
11358 // It will be analyzed later.
11359 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011360 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011361 ValueDecl *D = Res.first;
11362 if (!D)
11363 continue;
11364
Alexey Bataev88202be2017-07-27 13:20:36 +000011365 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011366 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011367 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11368 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011369 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011370 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011371 } else if (OASE) {
11372 QualType BaseType =
11373 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11374 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011375 Type = ATy->getElementType();
11376 else
11377 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011378 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011379 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011380 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011381 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011382 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011383
Alexey Bataevc5e02582014-06-16 07:08:35 +000011384 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11385 // A variable that appears in a private clause must not have an incomplete
11386 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011387 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011388 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011389 continue;
11390 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011391 // A list item that appears in a reduction clause must not be
11392 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011393 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11394 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011395 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011396
11397 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011398 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11399 // If a list-item is a reference type then it must bind to the same object
11400 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011401 if (!ASE && !OASE) {
11402 if (VD) {
11403 VarDecl *VDDef = VD->getDefinition();
11404 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11405 DSARefChecker Check(Stack);
11406 if (Check.Visit(VDDef->getInit())) {
11407 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11408 << getOpenMPClauseName(ClauseKind) << ERange;
11409 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11410 continue;
11411 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011412 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011413 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011414
Alexey Bataevbc529672018-09-28 19:33:14 +000011415 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11416 // in a Construct]
11417 // Variables with the predetermined data-sharing attributes may not be
11418 // listed in data-sharing attributes clauses, except for the cases
11419 // listed below. For these exceptions only, listing a predetermined
11420 // variable in a data-sharing attribute clause is allowed and overrides
11421 // the variable's predetermined data-sharing attributes.
11422 // OpenMP [2.14.3.6, Restrictions, p.3]
11423 // Any number of reduction clauses can be specified on the directive,
11424 // but a list item can appear only once in the reduction clauses for that
11425 // directive.
11426 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11427 if (DVar.CKind == OMPC_reduction) {
11428 S.Diag(ELoc, diag::err_omp_once_referenced)
11429 << getOpenMPClauseName(ClauseKind);
11430 if (DVar.RefExpr)
11431 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11432 continue;
11433 }
11434 if (DVar.CKind != OMPC_unknown) {
11435 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11436 << getOpenMPClauseName(DVar.CKind)
11437 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011438 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011439 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011440 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011441
11442 // OpenMP [2.14.3.6, Restrictions, p.1]
11443 // A list item that appears in a reduction clause of a worksharing
11444 // construct must be shared in the parallel regions to which any of the
11445 // worksharing regions arising from the worksharing construct bind.
11446 if (isOpenMPWorksharingDirective(CurrDir) &&
11447 !isOpenMPParallelDirective(CurrDir) &&
11448 !isOpenMPTeamsDirective(CurrDir)) {
11449 DVar = Stack->getImplicitDSA(D, true);
11450 if (DVar.CKind != OMPC_shared) {
11451 S.Diag(ELoc, diag::err_omp_required_access)
11452 << getOpenMPClauseName(OMPC_reduction)
11453 << getOpenMPClauseName(OMPC_shared);
11454 reportOriginalDsa(S, Stack, D, DVar);
11455 continue;
11456 }
11457 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011458 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011459
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011460 // Try to find 'declare reduction' corresponding construct before using
11461 // builtin/overloaded operators.
11462 CXXCastPath BasePath;
11463 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011464 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011465 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11466 if (DeclareReductionRef.isInvalid())
11467 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011468 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011469 (DeclareReductionRef.isUnset() ||
11470 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011471 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011472 continue;
11473 }
11474 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11475 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011476 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011477 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011478 << Type << ReductionIdRange;
11479 continue;
11480 }
11481
11482 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11483 // The type of a list item that appears in a reduction clause must be valid
11484 // for the reduction-identifier. For a max or min reduction in C, the type
11485 // of the list item must be an allowed arithmetic data type: char, int,
11486 // float, double, or _Bool, possibly modified with long, short, signed, or
11487 // unsigned. For a max or min reduction in C++, the type of the list item
11488 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11489 // double, or bool, possibly modified with long, short, signed, or unsigned.
11490 if (DeclareReductionRef.isUnset()) {
11491 if ((BOK == BO_GT || BOK == BO_LT) &&
11492 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011493 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11494 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011495 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011496 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011497 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11498 VarDecl::DeclarationOnly;
11499 S.Diag(D->getLocation(),
11500 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011501 << D;
11502 }
11503 continue;
11504 }
11505 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011506 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011507 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11508 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011509 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011510 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11511 VarDecl::DeclarationOnly;
11512 S.Diag(D->getLocation(),
11513 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011514 << D;
11515 }
11516 continue;
11517 }
11518 }
11519
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011520 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011521 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11522 D->hasAttrs() ? &D->getAttrs() : nullptr);
11523 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11524 D->hasAttrs() ? &D->getAttrs() : nullptr);
11525 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011526
11527 // Try if we can determine constant lengths for all array sections and avoid
11528 // the VLA.
11529 bool ConstantLengthOASE = false;
11530 if (OASE) {
11531 bool SingleElement;
11532 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011533 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011534 Context, OASE, SingleElement, ArraySizes);
11535
11536 // If we don't have a single element, we must emit a constant array type.
11537 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011538 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011539 PrivateTy = Context.getConstantArrayType(
11540 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011541 }
11542 }
11543
11544 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011545 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011546 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011547 if (!Context.getTargetInfo().isVLASupported() &&
11548 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11549 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11550 S.Diag(ELoc, diag::note_vla_unsupported);
11551 continue;
11552 }
David Majnemer9d168222016-08-05 17:44:54 +000011553 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011554 // Create pseudo array type for private copy. The size for this array will
11555 // be generated during codegen.
11556 // For array subscripts or single variables Private Ty is the same as Type
11557 // (type of the variable or single array element).
11558 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011559 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011560 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011561 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011562 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011563 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011564 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011565 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011566 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011567 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011568 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11569 D->hasAttrs() ? &D->getAttrs() : nullptr,
11570 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011571 // Add initializer for private variable.
11572 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011573 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11574 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011575 if (DeclareReductionRef.isUsable()) {
11576 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11577 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11578 if (DRD->getInitializer()) {
11579 Init = DRDRef;
11580 RHSVD->setInit(DRDRef);
11581 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011582 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011583 } else {
11584 switch (BOK) {
11585 case BO_Add:
11586 case BO_Xor:
11587 case BO_Or:
11588 case BO_LOr:
11589 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11590 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011591 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011592 break;
11593 case BO_Mul:
11594 case BO_LAnd:
11595 if (Type->isScalarType() || Type->isAnyComplexType()) {
11596 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011597 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011598 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011599 break;
11600 case BO_And: {
11601 // '&' reduction op - initializer is '~0'.
11602 QualType OrigType = Type;
11603 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11604 Type = ComplexTy->getElementType();
11605 if (Type->isRealFloatingType()) {
11606 llvm::APFloat InitValue =
11607 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11608 /*isIEEE=*/true);
11609 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11610 Type, ELoc);
11611 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011612 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011613 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11614 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11615 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11616 }
11617 if (Init && OrigType->isAnyComplexType()) {
11618 // Init = 0xFFFF + 0xFFFFi;
11619 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011620 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011621 }
11622 Type = OrigType;
11623 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011624 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011625 case BO_LT:
11626 case BO_GT: {
11627 // 'min' reduction op - initializer is 'Largest representable number in
11628 // the reduction list item type'.
11629 // 'max' reduction op - initializer is 'Least representable number in
11630 // the reduction list item type'.
11631 if (Type->isIntegerType() || Type->isPointerType()) {
11632 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011633 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011634 QualType IntTy =
11635 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11636 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011637 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11638 : llvm::APInt::getMinValue(Size)
11639 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11640 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011641 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11642 if (Type->isPointerType()) {
11643 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011644 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011645 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011646 if (CastExpr.isInvalid())
11647 continue;
11648 Init = CastExpr.get();
11649 }
11650 } else if (Type->isRealFloatingType()) {
11651 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11652 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11653 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11654 Type, ELoc);
11655 }
11656 break;
11657 }
11658 case BO_PtrMemD:
11659 case BO_PtrMemI:
11660 case BO_MulAssign:
11661 case BO_Div:
11662 case BO_Rem:
11663 case BO_Sub:
11664 case BO_Shl:
11665 case BO_Shr:
11666 case BO_LE:
11667 case BO_GE:
11668 case BO_EQ:
11669 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011670 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011671 case BO_AndAssign:
11672 case BO_XorAssign:
11673 case BO_OrAssign:
11674 case BO_Assign:
11675 case BO_AddAssign:
11676 case BO_SubAssign:
11677 case BO_DivAssign:
11678 case BO_RemAssign:
11679 case BO_ShlAssign:
11680 case BO_ShrAssign:
11681 case BO_Comma:
11682 llvm_unreachable("Unexpected reduction operation");
11683 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011684 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011685 if (Init && DeclareReductionRef.isUnset())
11686 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11687 else if (!Init)
11688 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011689 if (RHSVD->isInvalidDecl())
11690 continue;
11691 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011692 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11693 << Type << ReductionIdRange;
11694 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11695 VarDecl::DeclarationOnly;
11696 S.Diag(D->getLocation(),
11697 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011698 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011699 continue;
11700 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011701 // Store initializer for single element in private copy. Will be used during
11702 // codegen.
11703 PrivateVD->setInit(RHSVD->getInit());
11704 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011705 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011706 ExprResult ReductionOp;
11707 if (DeclareReductionRef.isUsable()) {
11708 QualType RedTy = DeclareReductionRef.get()->getType();
11709 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011710 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11711 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011712 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011713 LHS = S.DefaultLvalueConversion(LHS.get());
11714 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011715 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11716 CK_UncheckedDerivedToBase, LHS.get(),
11717 &BasePath, LHS.get()->getValueKind());
11718 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11719 CK_UncheckedDerivedToBase, RHS.get(),
11720 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011721 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011722 FunctionProtoType::ExtProtoInfo EPI;
11723 QualType Params[] = {PtrRedTy, PtrRedTy};
11724 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11725 auto *OVE = new (Context) OpaqueValueExpr(
11726 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011727 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011728 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011729 ReductionOp =
11730 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011731 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011732 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011733 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011734 if (ReductionOp.isUsable()) {
11735 if (BOK != BO_LT && BOK != BO_GT) {
11736 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011737 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011738 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011739 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011740 auto *ConditionalOp = new (Context)
11741 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11742 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011743 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011744 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011745 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011746 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011747 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011748 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11749 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011750 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011751 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011752 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011753 }
11754
Alexey Bataevfa312f32017-07-21 18:48:21 +000011755 // OpenMP [2.15.4.6, Restrictions, p.2]
11756 // A list item that appears in an in_reduction clause of a task construct
11757 // must appear in a task_reduction clause of a construct associated with a
11758 // taskgroup region that includes the participating task in its taskgroup
11759 // set. The construct associated with the innermost region that meets this
11760 // condition must specify the same reduction-identifier as the in_reduction
11761 // clause.
11762 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011763 SourceRange ParentSR;
11764 BinaryOperatorKind ParentBOK;
11765 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011766 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011767 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011768 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11769 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011770 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011771 Stack->getTopMostTaskgroupReductionData(
11772 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011773 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11774 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11775 if (!IsParentBOK && !IsParentReductionOp) {
11776 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11777 continue;
11778 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011779 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11780 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11781 IsParentReductionOp) {
11782 bool EmitError = true;
11783 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11784 llvm::FoldingSetNodeID RedId, ParentRedId;
11785 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11786 DeclareReductionRef.get()->Profile(RedId, Context,
11787 /*Canonical=*/true);
11788 EmitError = RedId != ParentRedId;
11789 }
11790 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011791 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011792 diag::err_omp_reduction_identifier_mismatch)
11793 << ReductionIdRange << RefExpr->getSourceRange();
11794 S.Diag(ParentSR.getBegin(),
11795 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011796 << ParentSR
11797 << (IsParentBOK ? ParentBOKDSA.RefExpr
11798 : ParentReductionOpDSA.RefExpr)
11799 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011800 continue;
11801 }
11802 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011803 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11804 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011805 }
11806
Alexey Bataev60da77e2016-02-29 05:54:20 +000011807 DeclRefExpr *Ref = nullptr;
11808 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011809 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011810 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011811 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011812 VarsExpr =
11813 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11814 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011815 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011816 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011817 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011818 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011819 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011820 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011821 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011822 if (!RefRes.isUsable())
11823 continue;
11824 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011825 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11826 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011827 if (!PostUpdateRes.isUsable())
11828 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011829 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11830 Stack->getCurrentDirective() == OMPD_taskgroup) {
11831 S.Diag(RefExpr->getExprLoc(),
11832 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011833 << RefExpr->getSourceRange();
11834 continue;
11835 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011836 RD.ExprPostUpdates.emplace_back(
11837 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011838 }
11839 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011840 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011841 // All reduction items are still marked as reduction (to do not increase
11842 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011843 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011844 if (CurrDir == OMPD_taskgroup) {
11845 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011846 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11847 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011848 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011849 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011850 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011851 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11852 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011853 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011854 return RD.Vars.empty();
11855}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011856
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011857OMPClause *Sema::ActOnOpenMPReductionClause(
11858 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11859 SourceLocation ColonLoc, SourceLocation EndLoc,
11860 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11861 ArrayRef<Expr *> UnresolvedReductions) {
11862 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011863 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011864 StartLoc, LParenLoc, ColonLoc, EndLoc,
11865 ReductionIdScopeSpec, ReductionId,
11866 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011867 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011868
Alexey Bataevc5e02582014-06-16 07:08:35 +000011869 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011870 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11871 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11872 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11873 buildPreInits(Context, RD.ExprCaptures),
11874 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011875}
11876
Alexey Bataev169d96a2017-07-18 20:17:46 +000011877OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11878 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11879 SourceLocation ColonLoc, SourceLocation EndLoc,
11880 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11881 ArrayRef<Expr *> UnresolvedReductions) {
11882 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011883 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11884 StartLoc, LParenLoc, ColonLoc, EndLoc,
11885 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011886 UnresolvedReductions, RD))
11887 return nullptr;
11888
11889 return OMPTaskReductionClause::Create(
11890 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11891 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11892 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11893 buildPreInits(Context, RD.ExprCaptures),
11894 buildPostUpdate(*this, RD.ExprPostUpdates));
11895}
11896
Alexey Bataevfa312f32017-07-21 18:48:21 +000011897OMPClause *Sema::ActOnOpenMPInReductionClause(
11898 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11899 SourceLocation ColonLoc, SourceLocation EndLoc,
11900 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11901 ArrayRef<Expr *> UnresolvedReductions) {
11902 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011903 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011904 StartLoc, LParenLoc, ColonLoc, EndLoc,
11905 ReductionIdScopeSpec, ReductionId,
11906 UnresolvedReductions, RD))
11907 return nullptr;
11908
11909 return OMPInReductionClause::Create(
11910 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11911 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011912 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011913 buildPreInits(Context, RD.ExprCaptures),
11914 buildPostUpdate(*this, RD.ExprPostUpdates));
11915}
11916
Alexey Bataevecba70f2016-04-12 11:02:11 +000011917bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11918 SourceLocation LinLoc) {
11919 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11920 LinKind == OMPC_LINEAR_unknown) {
11921 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11922 return true;
11923 }
11924 return false;
11925}
11926
Alexey Bataeve3727102018-04-18 15:57:46 +000011927bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011928 OpenMPLinearClauseKind LinKind,
11929 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011930 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011931 // A variable must not have an incomplete type or a reference type.
11932 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11933 return true;
11934 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11935 !Type->isReferenceType()) {
11936 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11937 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11938 return true;
11939 }
11940 Type = Type.getNonReferenceType();
11941
Joel E. Dennybae586f2019-01-04 22:12:13 +000011942 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11943 // A variable that is privatized must not have a const-qualified type
11944 // unless it is of class type with a mutable member. This restriction does
11945 // not apply to the firstprivate clause.
11946 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011947 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011948
11949 // A list item must be of integral or pointer type.
11950 Type = Type.getUnqualifiedType().getCanonicalType();
11951 const auto *Ty = Type.getTypePtrOrNull();
11952 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11953 !Ty->isPointerType())) {
11954 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11955 if (D) {
11956 bool IsDecl =
11957 !VD ||
11958 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11959 Diag(D->getLocation(),
11960 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11961 << D;
11962 }
11963 return true;
11964 }
11965 return false;
11966}
11967
Alexey Bataev182227b2015-08-20 10:54:39 +000011968OMPClause *Sema::ActOnOpenMPLinearClause(
11969 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11970 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11971 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011972 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011973 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000011974 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011975 SmallVector<Decl *, 4> ExprCaptures;
11976 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011977 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000011978 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000011979 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011980 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011981 SourceLocation ELoc;
11982 SourceRange ERange;
11983 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011984 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011985 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011986 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011987 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011988 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000011989 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000011990 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011991 ValueDecl *D = Res.first;
11992 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000011993 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000011994
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011995 QualType Type = D->getType();
11996 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000011997
11998 // OpenMP [2.14.3.7, linear clause]
11999 // A list-item cannot appear in more than one linear clause.
12000 // A list-item that appears in a linear clause cannot appear in any
12001 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012002 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012003 if (DVar.RefExpr) {
12004 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12005 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012006 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012007 continue;
12008 }
12009
Alexey Bataevecba70f2016-04-12 11:02:11 +000012010 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012011 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012012 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012013
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012014 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012015 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012016 buildVarDecl(*this, ELoc, Type, D->getName(),
12017 D->hasAttrs() ? &D->getAttrs() : nullptr,
12018 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012019 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012020 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012021 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012022 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012023 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012024 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012025 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012026 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012027 ExprCaptures.push_back(Ref->getDecl());
12028 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12029 ExprResult RefRes = DefaultLvalueConversion(Ref);
12030 if (!RefRes.isUsable())
12031 continue;
12032 ExprResult PostUpdateRes =
12033 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12034 SimpleRefExpr, RefRes.get());
12035 if (!PostUpdateRes.isUsable())
12036 continue;
12037 ExprPostUpdates.push_back(
12038 IgnoredValueConversions(PostUpdateRes.get()).get());
12039 }
12040 }
12041 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012042 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012043 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012044 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012045 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012046 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012047 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012048 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012049
12050 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012051 Vars.push_back((VD || CurContext->isDependentContext())
12052 ? RefExpr->IgnoreParens()
12053 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012054 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012055 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012056 }
12057
12058 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012059 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012060
12061 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012062 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012063 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12064 !Step->isInstantiationDependent() &&
12065 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012066 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012067 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012068 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012069 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012070 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012071
Alexander Musman3276a272015-03-21 10:12:56 +000012072 // Build var to save the step value.
12073 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012074 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012075 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012076 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012077 ExprResult CalcStep =
12078 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012079 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012080
Alexander Musman8dba6642014-04-22 13:09:42 +000012081 // Warn about zero linear step (it would be probably better specified as
12082 // making corresponding variables 'const').
12083 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012084 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12085 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012086 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12087 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012088 if (!IsConstant && CalcStep.isUsable()) {
12089 // Calculate the step beforehand instead of doing this on each iteration.
12090 // (This is not used if the number of iterations may be kfold-ed).
12091 CalcStepExpr = CalcStep.get();
12092 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012093 }
12094
Alexey Bataev182227b2015-08-20 10:54:39 +000012095 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12096 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012097 StepExpr, CalcStepExpr,
12098 buildPreInits(Context, ExprCaptures),
12099 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012100}
12101
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012102static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12103 Expr *NumIterations, Sema &SemaRef,
12104 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012105 // Walk the vars and build update/final expressions for the CodeGen.
12106 SmallVector<Expr *, 8> Updates;
12107 SmallVector<Expr *, 8> Finals;
12108 Expr *Step = Clause.getStep();
12109 Expr *CalcStep = Clause.getCalcStep();
12110 // OpenMP [2.14.3.7, linear clause]
12111 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012112 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012113 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012114 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012115 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12116 bool HasErrors = false;
12117 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012118 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012119 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12120 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012121 SourceLocation ELoc;
12122 SourceRange ERange;
12123 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012124 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012125 ValueDecl *D = Res.first;
12126 if (Res.second || !D) {
12127 Updates.push_back(nullptr);
12128 Finals.push_back(nullptr);
12129 HasErrors = true;
12130 continue;
12131 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012132 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012133 // OpenMP [2.15.11, distribute simd Construct]
12134 // A list item may not appear in a linear clause, unless it is the loop
12135 // iteration variable.
12136 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12137 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12138 SemaRef.Diag(ELoc,
12139 diag::err_omp_linear_distribute_var_non_loop_iteration);
12140 Updates.push_back(nullptr);
12141 Finals.push_back(nullptr);
12142 HasErrors = true;
12143 continue;
12144 }
Alexander Musman3276a272015-03-21 10:12:56 +000012145 Expr *InitExpr = *CurInit;
12146
12147 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012148 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012149 Expr *CapturedRef;
12150 if (LinKind == OMPC_LINEAR_uval)
12151 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12152 else
12153 CapturedRef =
12154 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12155 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12156 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012157
12158 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012159 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012160 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012161 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012162 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012163 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012164 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012165 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012166 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012167 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012168
12169 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012170 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012171 if (!Info.first)
12172 Final =
12173 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12174 InitExpr, NumIterations, Step, /*Subtract=*/false);
12175 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012176 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012177 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012178 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012179
Alexander Musman3276a272015-03-21 10:12:56 +000012180 if (!Update.isUsable() || !Final.isUsable()) {
12181 Updates.push_back(nullptr);
12182 Finals.push_back(nullptr);
12183 HasErrors = true;
12184 } else {
12185 Updates.push_back(Update.get());
12186 Finals.push_back(Final.get());
12187 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012188 ++CurInit;
12189 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012190 }
12191 Clause.setUpdates(Updates);
12192 Clause.setFinals(Finals);
12193 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012194}
12195
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012196OMPClause *Sema::ActOnOpenMPAlignedClause(
12197 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12198 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012199 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012200 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012201 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12202 SourceLocation ELoc;
12203 SourceRange ERange;
12204 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012205 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012206 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012207 // It will be analyzed later.
12208 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012209 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012210 ValueDecl *D = Res.first;
12211 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012212 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012213
Alexey Bataev1efd1662016-03-29 10:59:56 +000012214 QualType QType = D->getType();
12215 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012216
12217 // OpenMP [2.8.1, simd construct, Restrictions]
12218 // The type of list items appearing in the aligned clause must be
12219 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012220 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012221 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012222 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012223 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012224 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012225 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012226 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012227 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012228 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012229 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012230 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012231 continue;
12232 }
12233
12234 // OpenMP [2.8.1, simd construct, Restrictions]
12235 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012236 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012237 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012238 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12239 << getOpenMPClauseName(OMPC_aligned);
12240 continue;
12241 }
12242
Alexey Bataev1efd1662016-03-29 10:59:56 +000012243 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012244 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012245 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12246 Vars.push_back(DefaultFunctionArrayConversion(
12247 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12248 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012249 }
12250
12251 // OpenMP [2.8.1, simd construct, Description]
12252 // The parameter of the aligned clause, alignment, must be a constant
12253 // positive integer expression.
12254 // If no optional parameter is specified, implementation-defined default
12255 // alignments for SIMD instructions on the target platforms are assumed.
12256 if (Alignment != nullptr) {
12257 ExprResult AlignResult =
12258 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12259 if (AlignResult.isInvalid())
12260 return nullptr;
12261 Alignment = AlignResult.get();
12262 }
12263 if (Vars.empty())
12264 return nullptr;
12265
12266 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12267 EndLoc, Vars, Alignment);
12268}
12269
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012270OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12271 SourceLocation StartLoc,
12272 SourceLocation LParenLoc,
12273 SourceLocation EndLoc) {
12274 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012275 SmallVector<Expr *, 8> SrcExprs;
12276 SmallVector<Expr *, 8> DstExprs;
12277 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012278 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012279 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12280 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012281 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012282 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012283 SrcExprs.push_back(nullptr);
12284 DstExprs.push_back(nullptr);
12285 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012286 continue;
12287 }
12288
Alexey Bataeved09d242014-05-28 05:53:51 +000012289 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012290 // OpenMP [2.1, C/C++]
12291 // A list item is a variable name.
12292 // OpenMP [2.14.4.1, Restrictions, p.1]
12293 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012294 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012295 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012296 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12297 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012298 continue;
12299 }
12300
12301 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012302 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012303
12304 QualType Type = VD->getType();
12305 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12306 // It will be analyzed later.
12307 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012308 SrcExprs.push_back(nullptr);
12309 DstExprs.push_back(nullptr);
12310 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012311 continue;
12312 }
12313
12314 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12315 // A list item that appears in a copyin clause must be threadprivate.
12316 if (!DSAStack->isThreadPrivate(VD)) {
12317 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012318 << getOpenMPClauseName(OMPC_copyin)
12319 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012320 continue;
12321 }
12322
12323 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12324 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012325 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012326 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012327 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12328 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012329 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012330 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012331 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012332 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012333 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012334 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012335 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012336 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012337 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012338 // For arrays generate assignment operation for single element and replace
12339 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012340 ExprResult AssignmentOp =
12341 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12342 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012343 if (AssignmentOp.isInvalid())
12344 continue;
12345 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012346 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012347 if (AssignmentOp.isInvalid())
12348 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012349
12350 DSAStack->addDSA(VD, DE, OMPC_copyin);
12351 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012352 SrcExprs.push_back(PseudoSrcExpr);
12353 DstExprs.push_back(PseudoDstExpr);
12354 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012355 }
12356
Alexey Bataeved09d242014-05-28 05:53:51 +000012357 if (Vars.empty())
12358 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012359
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012360 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12361 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012362}
12363
Alexey Bataevbae9a792014-06-27 10:37:06 +000012364OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12365 SourceLocation StartLoc,
12366 SourceLocation LParenLoc,
12367 SourceLocation EndLoc) {
12368 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012369 SmallVector<Expr *, 8> SrcExprs;
12370 SmallVector<Expr *, 8> DstExprs;
12371 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012372 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012373 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12374 SourceLocation ELoc;
12375 SourceRange ERange;
12376 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012377 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012378 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012379 // It will be analyzed later.
12380 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012381 SrcExprs.push_back(nullptr);
12382 DstExprs.push_back(nullptr);
12383 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012384 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012385 ValueDecl *D = Res.first;
12386 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012387 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012388
Alexey Bataeve122da12016-03-17 10:50:17 +000012389 QualType Type = D->getType();
12390 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012391
12392 // OpenMP [2.14.4.2, Restrictions, p.2]
12393 // A list item that appears in a copyprivate clause may not appear in a
12394 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012395 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012396 DSAStackTy::DSAVarData DVar =
12397 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012398 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12399 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012400 Diag(ELoc, diag::err_omp_wrong_dsa)
12401 << getOpenMPClauseName(DVar.CKind)
12402 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012403 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012404 continue;
12405 }
12406
12407 // OpenMP [2.11.4.2, Restrictions, p.1]
12408 // All list items that appear in a copyprivate clause must be either
12409 // threadprivate or private in the enclosing context.
12410 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012411 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012412 if (DVar.CKind == OMPC_shared) {
12413 Diag(ELoc, diag::err_omp_required_access)
12414 << getOpenMPClauseName(OMPC_copyprivate)
12415 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012416 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012417 continue;
12418 }
12419 }
12420 }
12421
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012422 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012423 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012424 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012425 << getOpenMPClauseName(OMPC_copyprivate) << Type
12426 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012427 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012428 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012429 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012430 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012431 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012432 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012433 continue;
12434 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012435
Alexey Bataevbae9a792014-06-27 10:37:06 +000012436 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12437 // A variable of class type (or array thereof) that appears in a
12438 // copyin clause requires an accessible, unambiguous copy assignment
12439 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012440 Type = Context.getBaseElementType(Type.getNonReferenceType())
12441 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012442 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012443 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012444 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012445 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12446 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012447 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012448 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012449 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12450 ExprResult AssignmentOp = BuildBinOp(
12451 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012452 if (AssignmentOp.isInvalid())
12453 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012454 AssignmentOp =
12455 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012456 if (AssignmentOp.isInvalid())
12457 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012458
12459 // No need to mark vars as copyprivate, they are already threadprivate or
12460 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012461 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012462 Vars.push_back(
12463 VD ? RefExpr->IgnoreParens()
12464 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012465 SrcExprs.push_back(PseudoSrcExpr);
12466 DstExprs.push_back(PseudoDstExpr);
12467 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012468 }
12469
12470 if (Vars.empty())
12471 return nullptr;
12472
Alexey Bataeva63048e2015-03-23 06:18:07 +000012473 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12474 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012475}
12476
Alexey Bataev6125da92014-07-21 11:26:11 +000012477OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12478 SourceLocation StartLoc,
12479 SourceLocation LParenLoc,
12480 SourceLocation EndLoc) {
12481 if (VarList.empty())
12482 return nullptr;
12483
12484 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12485}
Alexey Bataevdea47612014-07-23 07:46:59 +000012486
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012487OMPClause *
12488Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12489 SourceLocation DepLoc, SourceLocation ColonLoc,
12490 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12491 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012492 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012493 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012494 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012495 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012496 return nullptr;
12497 }
12498 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012499 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12500 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012501 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012502 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012503 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12504 /*Last=*/OMPC_DEPEND_unknown, Except)
12505 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012506 return nullptr;
12507 }
12508 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012509 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012510 llvm::APSInt DepCounter(/*BitWidth=*/32);
12511 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012512 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12513 if (const Expr *OrderedCountExpr =
12514 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012515 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12516 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012517 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012518 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012519 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012520 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12521 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12522 // It will be analyzed later.
12523 Vars.push_back(RefExpr);
12524 continue;
12525 }
12526
12527 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012528 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012529 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012530 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012531 DepCounter >= TotalDepCount) {
12532 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12533 continue;
12534 }
12535 ++DepCounter;
12536 // OpenMP [2.13.9, Summary]
12537 // depend(dependence-type : vec), where dependence-type is:
12538 // 'sink' and where vec is the iteration vector, which has the form:
12539 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12540 // where n is the value specified by the ordered clause in the loop
12541 // directive, xi denotes the loop iteration variable of the i-th nested
12542 // loop associated with the loop directive, and di is a constant
12543 // non-negative integer.
12544 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012545 // It will be analyzed later.
12546 Vars.push_back(RefExpr);
12547 continue;
12548 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012549 SimpleExpr = SimpleExpr->IgnoreImplicit();
12550 OverloadedOperatorKind OOK = OO_None;
12551 SourceLocation OOLoc;
12552 Expr *LHS = SimpleExpr;
12553 Expr *RHS = nullptr;
12554 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12555 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12556 OOLoc = BO->getOperatorLoc();
12557 LHS = BO->getLHS()->IgnoreParenImpCasts();
12558 RHS = BO->getRHS()->IgnoreParenImpCasts();
12559 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12560 OOK = OCE->getOperator();
12561 OOLoc = OCE->getOperatorLoc();
12562 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12563 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12564 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12565 OOK = MCE->getMethodDecl()
12566 ->getNameInfo()
12567 .getName()
12568 .getCXXOverloadedOperator();
12569 OOLoc = MCE->getCallee()->getExprLoc();
12570 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12571 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012572 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012573 SourceLocation ELoc;
12574 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012575 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012576 if (Res.second) {
12577 // It will be analyzed later.
12578 Vars.push_back(RefExpr);
12579 }
12580 ValueDecl *D = Res.first;
12581 if (!D)
12582 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012583
Alexey Bataev17daedf2018-02-15 22:42:57 +000012584 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12585 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12586 continue;
12587 }
12588 if (RHS) {
12589 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12590 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12591 if (RHSRes.isInvalid())
12592 continue;
12593 }
12594 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012595 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012596 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012597 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012598 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012599 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012600 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12601 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012602 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012603 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012604 continue;
12605 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012606 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012607 } else {
12608 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12609 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12610 (ASE &&
12611 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12612 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12613 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12614 << RefExpr->getSourceRange();
12615 continue;
12616 }
12617 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12618 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12619 ExprResult Res =
12620 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12621 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12622 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12623 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12624 << RefExpr->getSourceRange();
12625 continue;
12626 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012627 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012628 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012629 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012630
12631 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12632 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012633 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012634 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12635 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12636 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12637 }
12638 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12639 Vars.empty())
12640 return nullptr;
12641
Alexey Bataev8b427062016-05-25 12:36:08 +000012642 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012643 DepKind, DepLoc, ColonLoc, Vars,
12644 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012645 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12646 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012647 DSAStack->addDoacrossDependClause(C, OpsOffs);
12648 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012649}
Michael Wonge710d542015-08-07 16:16:36 +000012650
12651OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12652 SourceLocation LParenLoc,
12653 SourceLocation EndLoc) {
12654 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012655 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012656
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012657 // OpenMP [2.9.1, Restrictions]
12658 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012659 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012660 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012661 return nullptr;
12662
Alexey Bataev931e19b2017-10-02 16:32:39 +000012663 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012664 OpenMPDirectiveKind CaptureRegion =
12665 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12666 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012667 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012668 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012669 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12670 HelperValStmt = buildPreInits(Context, Captures);
12671 }
12672
Alexey Bataev8451efa2018-01-15 19:06:12 +000012673 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12674 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012675}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012676
Alexey Bataeve3727102018-04-18 15:57:46 +000012677static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012678 DSAStackTy *Stack, QualType QTy,
12679 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012680 NamedDecl *ND;
12681 if (QTy->isIncompleteType(&ND)) {
12682 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12683 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012684 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012685 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12686 !QTy.isTrivialType(SemaRef.Context))
12687 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012688 return true;
12689}
12690
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012691/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012692/// (array section or array subscript) does NOT specify the whole size of the
12693/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012694static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012695 const Expr *E,
12696 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012697 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012698
12699 // If this is an array subscript, it refers to the whole size if the size of
12700 // the dimension is constant and equals 1. Also, an array section assumes the
12701 // format of an array subscript if no colon is used.
12702 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012703 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012704 return ATy->getSize().getSExtValue() != 1;
12705 // Size can't be evaluated statically.
12706 return false;
12707 }
12708
12709 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012710 const Expr *LowerBound = OASE->getLowerBound();
12711 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012712
12713 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012714 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012715 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012716 Expr::EvalResult Result;
12717 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012718 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012719
12720 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012721 if (ConstLowerBound.getSExtValue())
12722 return true;
12723 }
12724
12725 // If we don't have a length we covering the whole dimension.
12726 if (!Length)
12727 return false;
12728
12729 // If the base is a pointer, we don't have a way to get the size of the
12730 // pointee.
12731 if (BaseQTy->isPointerType())
12732 return false;
12733
12734 // We can only check if the length is the same as the size of the dimension
12735 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012736 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012737 if (!CATy)
12738 return false;
12739
Fangrui Song407659a2018-11-30 23:41:18 +000012740 Expr::EvalResult Result;
12741 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012742 return false; // Can't get the integer value as a constant.
12743
Fangrui Song407659a2018-11-30 23:41:18 +000012744 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012745 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12746}
12747
12748// Return true if it can be proven that the provided array expression (array
12749// section or array subscript) does NOT specify a single element of the array
12750// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012751static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012752 const Expr *E,
12753 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012754 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012755
12756 // An array subscript always refer to a single element. Also, an array section
12757 // assumes the format of an array subscript if no colon is used.
12758 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12759 return false;
12760
12761 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012762 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012763
12764 // If we don't have a length we have to check if the array has unitary size
12765 // for this dimension. Also, we should always expect a length if the base type
12766 // is pointer.
12767 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012768 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012769 return ATy->getSize().getSExtValue() != 1;
12770 // We cannot assume anything.
12771 return false;
12772 }
12773
12774 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012775 Expr::EvalResult Result;
12776 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012777 return false; // Can't get the integer value as a constant.
12778
Fangrui Song407659a2018-11-30 23:41:18 +000012779 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012780 return ConstLength.getSExtValue() != 1;
12781}
12782
Samuel Antao661c0902016-05-26 17:39:58 +000012783// Return the expression of the base of the mappable expression or null if it
12784// cannot be determined and do all the necessary checks to see if the expression
12785// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012786// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012787static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012788 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012789 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012790 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012791 SourceLocation ELoc = E->getExprLoc();
12792 SourceRange ERange = E->getSourceRange();
12793
12794 // The base of elements of list in a map clause have to be either:
12795 // - a reference to variable or field.
12796 // - a member expression.
12797 // - an array expression.
12798 //
12799 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12800 // reference to 'r'.
12801 //
12802 // If we have:
12803 //
12804 // struct SS {
12805 // Bla S;
12806 // foo() {
12807 // #pragma omp target map (S.Arr[:12]);
12808 // }
12809 // }
12810 //
12811 // We want to retrieve the member expression 'this->S';
12812
Alexey Bataeve3727102018-04-18 15:57:46 +000012813 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012814
Samuel Antao5de996e2016-01-22 20:21:36 +000012815 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12816 // If a list item is an array section, it must specify contiguous storage.
12817 //
12818 // For this restriction it is sufficient that we make sure only references
12819 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012820 // exist except in the rightmost expression (unless they cover the whole
12821 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012822 //
12823 // r.ArrS[3:5].Arr[6:7]
12824 //
12825 // r.ArrS[3:5].x
12826 //
12827 // but these would be valid:
12828 // r.ArrS[3].Arr[6:7]
12829 //
12830 // r.ArrS[3].x
12831
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012832 bool AllowUnitySizeArraySection = true;
12833 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012834
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012835 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012836 E = E->IgnoreParenImpCasts();
12837
12838 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12839 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012840 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012841
12842 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012843
12844 // If we got a reference to a declaration, we should not expect any array
12845 // section before that.
12846 AllowUnitySizeArraySection = false;
12847 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012848
12849 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012850 CurComponents.emplace_back(CurE, CurE->getDecl());
12851 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012852 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012853
12854 if (isa<CXXThisExpr>(BaseE))
12855 // We found a base expression: this->Val.
12856 RelevantExpr = CurE;
12857 else
12858 E = BaseE;
12859
12860 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012861 if (!NoDiagnose) {
12862 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12863 << CurE->getSourceRange();
12864 return nullptr;
12865 }
12866 if (RelevantExpr)
12867 return nullptr;
12868 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012869 }
12870
12871 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12872
12873 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12874 // A bit-field cannot appear in a map clause.
12875 //
12876 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012877 if (!NoDiagnose) {
12878 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12879 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12880 return nullptr;
12881 }
12882 if (RelevantExpr)
12883 return nullptr;
12884 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012885 }
12886
12887 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12888 // If the type of a list item is a reference to a type T then the type
12889 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012890 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012891
12892 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12893 // A list item cannot be a variable that is a member of a structure with
12894 // a union type.
12895 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012896 if (CurType->isUnionType()) {
12897 if (!NoDiagnose) {
12898 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12899 << CurE->getSourceRange();
12900 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012901 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012902 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012903 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012904
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012905 // If we got a member expression, we should not expect any array section
12906 // before that:
12907 //
12908 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12909 // If a list item is an element of a structure, only the rightmost symbol
12910 // of the variable reference can be an array section.
12911 //
12912 AllowUnitySizeArraySection = false;
12913 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012914
12915 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012916 CurComponents.emplace_back(CurE, FD);
12917 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012918 E = CurE->getBase()->IgnoreParenImpCasts();
12919
12920 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012921 if (!NoDiagnose) {
12922 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12923 << 0 << CurE->getSourceRange();
12924 return nullptr;
12925 }
12926 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012927 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012928
12929 // If we got an array subscript that express the whole dimension we
12930 // can have any array expressions before. If it only expressing part of
12931 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012932 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012933 E->getType()))
12934 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012935
Patrick Lystere13b1e32019-01-02 19:28:48 +000012936 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12937 Expr::EvalResult Result;
12938 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12939 if (!Result.Val.getInt().isNullValue()) {
12940 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12941 diag::err_omp_invalid_map_this_expr);
12942 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12943 diag::note_omp_invalid_subscript_on_this_ptr_map);
12944 }
12945 }
12946 RelevantExpr = TE;
12947 }
12948
Samuel Antao90927002016-04-26 14:54:23 +000012949 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012950 CurComponents.emplace_back(CurE, nullptr);
12951 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012952 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000012953 E = CurE->getBase()->IgnoreParenImpCasts();
12954
Alexey Bataev27041fa2017-12-05 15:22:49 +000012955 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012956 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12957
Samuel Antao5de996e2016-01-22 20:21:36 +000012958 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12959 // If the type of a list item is a reference to a type T then the type
12960 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000012961 if (CurType->isReferenceType())
12962 CurType = CurType->getPointeeType();
12963
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012964 bool IsPointer = CurType->isAnyPointerType();
12965
12966 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012967 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12968 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012969 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012970 }
12971
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012972 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000012973 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012974 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000012975 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012976
Samuel Antaodab51bb2016-07-18 23:22:11 +000012977 if (AllowWholeSizeArraySection) {
12978 // Any array section is currently allowed. Allowing a whole size array
12979 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012980 //
12981 // If this array section refers to the whole dimension we can still
12982 // accept other array sections before this one, except if the base is a
12983 // pointer. Otherwise, only unitary sections are accepted.
12984 if (NotWhole || IsPointer)
12985 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000012986 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012987 // A unity or whole array section is not allowed and that is not
12988 // compatible with the properties of the current array section.
12989 SemaRef.Diag(
12990 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12991 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012992 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012993 }
Samuel Antao90927002016-04-26 14:54:23 +000012994
Patrick Lystere13b1e32019-01-02 19:28:48 +000012995 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12996 Expr::EvalResult ResultR;
12997 Expr::EvalResult ResultL;
12998 if (CurE->getLength()->EvaluateAsInt(ResultR,
12999 SemaRef.getASTContext())) {
13000 if (!ResultR.Val.getInt().isOneValue()) {
13001 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13002 diag::err_omp_invalid_map_this_expr);
13003 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13004 diag::note_omp_invalid_length_on_this_ptr_mapping);
13005 }
13006 }
13007 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13008 ResultL, SemaRef.getASTContext())) {
13009 if (!ResultL.Val.getInt().isNullValue()) {
13010 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13011 diag::err_omp_invalid_map_this_expr);
13012 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13013 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13014 }
13015 }
13016 RelevantExpr = TE;
13017 }
13018
Samuel Antao90927002016-04-26 14:54:23 +000013019 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013020 CurComponents.emplace_back(CurE, nullptr);
13021 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013022 if (!NoDiagnose) {
13023 // If nothing else worked, this is not a valid map clause expression.
13024 SemaRef.Diag(
13025 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13026 << ERange;
13027 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013028 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013029 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013030 }
13031
13032 return RelevantExpr;
13033}
13034
13035// Return true if expression E associated with value VD has conflicts with other
13036// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013037static bool checkMapConflicts(
13038 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013039 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013040 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13041 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013042 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013043 SourceLocation ELoc = E->getExprLoc();
13044 SourceRange ERange = E->getSourceRange();
13045
13046 // In order to easily check the conflicts we need to match each component of
13047 // the expression under test with the components of the expressions that are
13048 // already in the stack.
13049
Samuel Antao5de996e2016-01-22 20:21:36 +000013050 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013051 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013052 "Map clause expression with unexpected base!");
13053
13054 // Variables to help detecting enclosing problems in data environment nests.
13055 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013056 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013057
Samuel Antao90927002016-04-26 14:54:23 +000013058 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13059 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013060 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13061 ERange, CKind, &EnclosingExpr,
13062 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13063 StackComponents,
13064 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013065 assert(!StackComponents.empty() &&
13066 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013067 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013068 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013069 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013070
Samuel Antao90927002016-04-26 14:54:23 +000013071 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013072 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013073
Samuel Antao5de996e2016-01-22 20:21:36 +000013074 // Expressions must start from the same base. Here we detect at which
13075 // point both expressions diverge from each other and see if we can
13076 // detect if the memory referred to both expressions is contiguous and
13077 // do not overlap.
13078 auto CI = CurComponents.rbegin();
13079 auto CE = CurComponents.rend();
13080 auto SI = StackComponents.rbegin();
13081 auto SE = StackComponents.rend();
13082 for (; CI != CE && SI != SE; ++CI, ++SI) {
13083
13084 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13085 // At most one list item can be an array item derived from a given
13086 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013087 if (CurrentRegionOnly &&
13088 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13089 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13090 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13091 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13092 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013093 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013094 << CI->getAssociatedExpression()->getSourceRange();
13095 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13096 diag::note_used_here)
13097 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013098 return true;
13099 }
13100
13101 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013102 if (CI->getAssociatedExpression()->getStmtClass() !=
13103 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013104 break;
13105
13106 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013107 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013108 break;
13109 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013110 // Check if the extra components of the expressions in the enclosing
13111 // data environment are redundant for the current base declaration.
13112 // If they are, the maps completely overlap, which is legal.
13113 for (; SI != SE; ++SI) {
13114 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013115 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013116 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013117 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013118 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013119 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013120 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013121 Type =
13122 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13123 }
13124 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013125 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013126 SemaRef, SI->getAssociatedExpression(), Type))
13127 break;
13128 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013129
13130 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13131 // List items of map clauses in the same construct must not share
13132 // original storage.
13133 //
13134 // If the expressions are exactly the same or one is a subset of the
13135 // other, it means they are sharing storage.
13136 if (CI == CE && SI == SE) {
13137 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013138 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013139 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013140 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013141 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013142 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13143 << ERange;
13144 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013145 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13146 << RE->getSourceRange();
13147 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013148 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013149 // If we find the same expression in the enclosing data environment,
13150 // that is legal.
13151 IsEnclosedByDataEnvironmentExpr = true;
13152 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013153 }
13154
Samuel Antao90927002016-04-26 14:54:23 +000013155 QualType DerivedType =
13156 std::prev(CI)->getAssociatedDeclaration()->getType();
13157 SourceLocation DerivedLoc =
13158 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013159
13160 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13161 // If the type of a list item is a reference to a type T then the type
13162 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013163 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013164
13165 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13166 // A variable for which the type is pointer and an array section
13167 // derived from that variable must not appear as list items of map
13168 // clauses of the same construct.
13169 //
13170 // Also, cover one of the cases in:
13171 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13172 // If any part of the original storage of a list item has corresponding
13173 // storage in the device data environment, all of the original storage
13174 // must have corresponding storage in the device data environment.
13175 //
13176 if (DerivedType->isAnyPointerType()) {
13177 if (CI == CE || SI == SE) {
13178 SemaRef.Diag(
13179 DerivedLoc,
13180 diag::err_omp_pointer_mapped_along_with_derived_section)
13181 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013182 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13183 << RE->getSourceRange();
13184 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013185 }
13186 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013187 SI->getAssociatedExpression()->getStmtClass() ||
13188 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13189 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013190 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013191 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013192 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013193 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13194 << RE->getSourceRange();
13195 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013196 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013197 }
13198
13199 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13200 // List items of map clauses in the same construct must not share
13201 // original storage.
13202 //
13203 // An expression is a subset of the other.
13204 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013205 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013206 if (CI != CE || SI != SE) {
13207 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13208 // a pointer.
13209 auto Begin =
13210 CI != CE ? CurComponents.begin() : StackComponents.begin();
13211 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13212 auto It = Begin;
13213 while (It != End && !It->getAssociatedDeclaration())
13214 std::advance(It, 1);
13215 assert(It != End &&
13216 "Expected at least one component with the declaration.");
13217 if (It != Begin && It->getAssociatedDeclaration()
13218 ->getType()
13219 .getCanonicalType()
13220 ->isAnyPointerType()) {
13221 IsEnclosedByDataEnvironmentExpr = false;
13222 EnclosingExpr = nullptr;
13223 return false;
13224 }
13225 }
Samuel Antao661c0902016-05-26 17:39:58 +000013226 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013227 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013228 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013229 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13230 << ERange;
13231 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013232 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13233 << RE->getSourceRange();
13234 return true;
13235 }
13236
13237 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013238 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013239 if (!CurrentRegionOnly && SI != SE)
13240 EnclosingExpr = RE;
13241
13242 // The current expression is a subset of the expression in the data
13243 // environment.
13244 IsEnclosedByDataEnvironmentExpr |=
13245 (!CurrentRegionOnly && CI != CE && SI == SE);
13246
13247 return false;
13248 });
13249
13250 if (CurrentRegionOnly)
13251 return FoundError;
13252
13253 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13254 // If any part of the original storage of a list item has corresponding
13255 // storage in the device data environment, all of the original storage must
13256 // have corresponding storage in the device data environment.
13257 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13258 // If a list item is an element of a structure, and a different element of
13259 // the structure has a corresponding list item in the device data environment
13260 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013261 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013262 // data environment prior to the task encountering the construct.
13263 //
13264 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13265 SemaRef.Diag(ELoc,
13266 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13267 << ERange;
13268 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13269 << EnclosingExpr->getSourceRange();
13270 return true;
13271 }
13272
13273 return FoundError;
13274}
13275
Michael Kruse4304e9d2019-02-19 16:38:20 +000013276// Look up the user-defined mapper given the mapper name and mapped type, and
13277// build a reference to it.
13278ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13279 CXXScopeSpec &MapperIdScopeSpec,
13280 const DeclarationNameInfo &MapperId,
13281 QualType Type, Expr *UnresolvedMapper) {
13282 if (MapperIdScopeSpec.isInvalid())
13283 return ExprError();
13284 // Find all user-defined mappers with the given MapperId.
13285 SmallVector<UnresolvedSet<8>, 4> Lookups;
13286 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13287 Lookup.suppressDiagnostics();
13288 if (S) {
13289 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13290 NamedDecl *D = Lookup.getRepresentativeDecl();
13291 while (S && !S->isDeclScope(D))
13292 S = S->getParent();
13293 if (S)
13294 S = S->getParent();
13295 Lookups.emplace_back();
13296 Lookups.back().append(Lookup.begin(), Lookup.end());
13297 Lookup.clear();
13298 }
13299 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13300 // Extract the user-defined mappers with the given MapperId.
13301 Lookups.push_back(UnresolvedSet<8>());
13302 for (NamedDecl *D : ULE->decls()) {
13303 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13304 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13305 Lookups.back().addDecl(DMD);
13306 }
13307 }
13308 // Defer the lookup for dependent types. The results will be passed through
13309 // UnresolvedMapper on instantiation.
13310 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13311 Type->isInstantiationDependentType() ||
13312 Type->containsUnexpandedParameterPack() ||
13313 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13314 return !D->isInvalidDecl() &&
13315 (D->getType()->isDependentType() ||
13316 D->getType()->isInstantiationDependentType() ||
13317 D->getType()->containsUnexpandedParameterPack());
13318 })) {
13319 UnresolvedSet<8> URS;
13320 for (const UnresolvedSet<8> &Set : Lookups) {
13321 if (Set.empty())
13322 continue;
13323 URS.append(Set.begin(), Set.end());
13324 }
13325 return UnresolvedLookupExpr::Create(
13326 SemaRef.Context, /*NamingClass=*/nullptr,
13327 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13328 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13329 }
13330 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13331 // The type must be of struct, union or class type in C and C++
13332 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13333 return ExprEmpty();
13334 SourceLocation Loc = MapperId.getLoc();
13335 // Perform argument dependent lookup.
13336 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13337 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13338 // Return the first user-defined mapper with the desired type.
13339 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13340 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13341 if (!D->isInvalidDecl() &&
13342 SemaRef.Context.hasSameType(D->getType(), Type))
13343 return D;
13344 return nullptr;
13345 }))
13346 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13347 // Find the first user-defined mapper with a type derived from the desired
13348 // type.
13349 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13350 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13351 if (!D->isInvalidDecl() &&
13352 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13353 !Type.isMoreQualifiedThan(D->getType()))
13354 return D;
13355 return nullptr;
13356 })) {
13357 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13358 /*DetectVirtual=*/false);
13359 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13360 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13361 VD->getType().getUnqualifiedType()))) {
13362 if (SemaRef.CheckBaseClassAccess(
13363 Loc, VD->getType(), Type, Paths.front(),
13364 /*DiagID=*/0) != Sema::AR_inaccessible) {
13365 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13366 }
13367 }
13368 }
13369 }
13370 // Report error if a mapper is specified, but cannot be found.
13371 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13372 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13373 << Type << MapperId.getName();
13374 return ExprError();
13375 }
13376 return ExprEmpty();
13377}
13378
Samuel Antao661c0902016-05-26 17:39:58 +000013379namespace {
13380// Utility struct that gathers all the related lists associated with a mappable
13381// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013382struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013383 // The list of expressions.
13384 ArrayRef<Expr *> VarList;
13385 // The list of processed expressions.
13386 SmallVector<Expr *, 16> ProcessedVarList;
13387 // The mappble components for each expression.
13388 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13389 // The base declaration of the variable.
13390 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013391 // The reference to the user-defined mapper associated with every expression.
13392 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013393
13394 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13395 // We have a list of components and base declarations for each entry in the
13396 // variable list.
13397 VarComponents.reserve(VarList.size());
13398 VarBaseDeclarations.reserve(VarList.size());
13399 }
13400};
13401}
13402
13403// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013404// \a CKind. In the check process the valid expressions, mappable expression
13405// components, variables, and user-defined mappers are extracted and used to
13406// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13407// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13408// and \a MapperId are expected to be valid if the clause kind is 'map'.
13409static void checkMappableExpressionList(
13410 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13411 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013412 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13413 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013414 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013415 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013416 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13417 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013418 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013419
13420 // If the identifier of user-defined mapper is not specified, it is "default".
13421 // We do not change the actual name in this clause to distinguish whether a
13422 // mapper is specified explicitly, i.e., it is not explicitly specified when
13423 // MapperId.getName() is empty.
13424 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13425 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13426 MapperId.setName(DeclNames.getIdentifier(
13427 &SemaRef.getASTContext().Idents.get("default")));
13428 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013429
13430 // Iterators to find the current unresolved mapper expression.
13431 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13432 bool UpdateUMIt = false;
13433 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013434
Samuel Antao90927002016-04-26 14:54:23 +000013435 // Keep track of the mappable components and base declarations in this clause.
13436 // Each entry in the list is going to have a list of components associated. We
13437 // record each set of the components so that we can build the clause later on.
13438 // In the end we should have the same amount of declarations and component
13439 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013440
Alexey Bataeve3727102018-04-18 15:57:46 +000013441 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013442 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013443 SourceLocation ELoc = RE->getExprLoc();
13444
Michael Kruse4304e9d2019-02-19 16:38:20 +000013445 // Find the current unresolved mapper expression.
13446 if (UpdateUMIt && UMIt != UMEnd) {
13447 UMIt++;
13448 assert(
13449 UMIt != UMEnd &&
13450 "Expect the size of UnresolvedMappers to match with that of VarList");
13451 }
13452 UpdateUMIt = true;
13453 if (UMIt != UMEnd)
13454 UnresolvedMapper = *UMIt;
13455
Alexey Bataeve3727102018-04-18 15:57:46 +000013456 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013457
13458 if (VE->isValueDependent() || VE->isTypeDependent() ||
13459 VE->isInstantiationDependent() ||
13460 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013461 // Try to find the associated user-defined mapper.
13462 ExprResult ER = buildUserDefinedMapperRef(
13463 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13464 VE->getType().getCanonicalType(), UnresolvedMapper);
13465 if (ER.isInvalid())
13466 continue;
13467 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013468 // We can only analyze this information once the missing information is
13469 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013470 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013471 continue;
13472 }
13473
Alexey Bataeve3727102018-04-18 15:57:46 +000013474 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013475
Samuel Antao5de996e2016-01-22 20:21:36 +000013476 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013477 SemaRef.Diag(ELoc,
13478 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013479 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013480 continue;
13481 }
13482
Samuel Antao90927002016-04-26 14:54:23 +000013483 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13484 ValueDecl *CurDeclaration = nullptr;
13485
13486 // Obtain the array or member expression bases if required. Also, fill the
13487 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013488 const Expr *BE = checkMapClauseExpressionBase(
13489 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013490 if (!BE)
13491 continue;
13492
Samuel Antao90927002016-04-26 14:54:23 +000013493 assert(!CurComponents.empty() &&
13494 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013495
Patrick Lystere13b1e32019-01-02 19:28:48 +000013496 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13497 // Add store "this" pointer to class in DSAStackTy for future checking
13498 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013499 // Try to find the associated user-defined mapper.
13500 ExprResult ER = buildUserDefinedMapperRef(
13501 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13502 VE->getType().getCanonicalType(), UnresolvedMapper);
13503 if (ER.isInvalid())
13504 continue;
13505 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013506 // Skip restriction checking for variable or field declarations
13507 MVLI.ProcessedVarList.push_back(RE);
13508 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13509 MVLI.VarComponents.back().append(CurComponents.begin(),
13510 CurComponents.end());
13511 MVLI.VarBaseDeclarations.push_back(nullptr);
13512 continue;
13513 }
13514
Samuel Antao90927002016-04-26 14:54:23 +000013515 // For the following checks, we rely on the base declaration which is
13516 // expected to be associated with the last component. The declaration is
13517 // expected to be a variable or a field (if 'this' is being mapped).
13518 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13519 assert(CurDeclaration && "Null decl on map clause.");
13520 assert(
13521 CurDeclaration->isCanonicalDecl() &&
13522 "Expecting components to have associated only canonical declarations.");
13523
13524 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013525 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013526
13527 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013528 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013529
13530 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013531 // threadprivate variables cannot appear in a map clause.
13532 // OpenMP 4.5 [2.10.5, target update Construct]
13533 // threadprivate variables cannot appear in a from clause.
13534 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013535 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013536 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13537 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013538 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013539 continue;
13540 }
13541
Samuel Antao5de996e2016-01-22 20:21:36 +000013542 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13543 // A list item cannot appear in both a map clause and a data-sharing
13544 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013545
Samuel Antao5de996e2016-01-22 20:21:36 +000013546 // Check conflicts with other map clause expressions. We check the conflicts
13547 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013548 // environment, because the restrictions are different. We only have to
13549 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013550 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013551 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013552 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013553 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013554 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013555 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013556 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013557
Samuel Antao661c0902016-05-26 17:39:58 +000013558 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013559 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13560 // If the type of a list item is a reference to a type T then the type will
13561 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013562 auto I = llvm::find_if(
13563 CurComponents,
13564 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13565 return MC.getAssociatedDeclaration();
13566 });
13567 assert(I != CurComponents.end() && "Null decl on map clause.");
13568 QualType Type =
13569 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013570
Samuel Antao661c0902016-05-26 17:39:58 +000013571 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13572 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013573 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013574 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013575 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013576 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013577 continue;
13578
Samuel Antao661c0902016-05-26 17:39:58 +000013579 if (CKind == OMPC_map) {
13580 // target enter data
13581 // OpenMP [2.10.2, Restrictions, p. 99]
13582 // A map-type must be specified in all map clauses and must be either
13583 // to or alloc.
13584 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13585 if (DKind == OMPD_target_enter_data &&
13586 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13587 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13588 << (IsMapTypeImplicit ? 1 : 0)
13589 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13590 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013591 continue;
13592 }
Samuel Antao661c0902016-05-26 17:39:58 +000013593
13594 // target exit_data
13595 // OpenMP [2.10.3, Restrictions, p. 102]
13596 // A map-type must be specified in all map clauses and must be either
13597 // from, release, or delete.
13598 if (DKind == OMPD_target_exit_data &&
13599 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13600 MapType == OMPC_MAP_delete)) {
13601 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13602 << (IsMapTypeImplicit ? 1 : 0)
13603 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13604 << getOpenMPDirectiveName(DKind);
13605 continue;
13606 }
13607
13608 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13609 // A list item cannot appear in both a map clause and a data-sharing
13610 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013611 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13612 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013613 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013614 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013615 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013616 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013617 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013618 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013619 continue;
13620 }
13621 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013622 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013623
Michael Kruse01f670d2019-02-22 22:29:42 +000013624 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013625 ExprResult ER = buildUserDefinedMapperRef(
13626 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13627 Type.getCanonicalType(), UnresolvedMapper);
13628 if (ER.isInvalid())
13629 continue;
13630 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013631
Samuel Antao90927002016-04-26 14:54:23 +000013632 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013633 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013634
13635 // Store the components in the stack so that they can be used to check
13636 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013637 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13638 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013639
13640 // Save the components and declaration to create the clause. For purposes of
13641 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013642 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013643 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13644 MVLI.VarComponents.back().append(CurComponents.begin(),
13645 CurComponents.end());
13646 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13647 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013648 }
Samuel Antao661c0902016-05-26 17:39:58 +000013649}
13650
Michael Kruse4304e9d2019-02-19 16:38:20 +000013651OMPClause *Sema::ActOnOpenMPMapClause(
13652 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13653 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13654 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13655 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13656 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13657 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13658 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13659 OMPC_MAP_MODIFIER_unknown,
13660 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013661 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13662
13663 // Process map-type-modifiers, flag errors for duplicate modifiers.
13664 unsigned Count = 0;
13665 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13666 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13667 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13668 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13669 continue;
13670 }
13671 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013672 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013673 Modifiers[Count] = MapTypeModifiers[I];
13674 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13675 ++Count;
13676 }
13677
Michael Kruse4304e9d2019-02-19 16:38:20 +000013678 MappableVarListInfo MVLI(VarList);
13679 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013680 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13681 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013682
Samuel Antao5de996e2016-01-22 20:21:36 +000013683 // We need to produce a map clause even if we don't have variables so that
13684 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013685 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13686 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13687 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13688 MapperIdScopeSpec.getWithLocInContext(Context),
13689 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013690}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013691
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013692QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13693 TypeResult ParsedType) {
13694 assert(ParsedType.isUsable());
13695
13696 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13697 if (ReductionType.isNull())
13698 return QualType();
13699
13700 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13701 // A type name in a declare reduction directive cannot be a function type, an
13702 // array type, a reference type, or a type qualified with const, volatile or
13703 // restrict.
13704 if (ReductionType.hasQualifiers()) {
13705 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13706 return QualType();
13707 }
13708
13709 if (ReductionType->isFunctionType()) {
13710 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13711 return QualType();
13712 }
13713 if (ReductionType->isReferenceType()) {
13714 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13715 return QualType();
13716 }
13717 if (ReductionType->isArrayType()) {
13718 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13719 return QualType();
13720 }
13721 return ReductionType;
13722}
13723
13724Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13725 Scope *S, DeclContext *DC, DeclarationName Name,
13726 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13727 AccessSpecifier AS, Decl *PrevDeclInScope) {
13728 SmallVector<Decl *, 8> Decls;
13729 Decls.reserve(ReductionTypes.size());
13730
13731 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013732 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013733 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13734 // A reduction-identifier may not be re-declared in the current scope for the
13735 // same type or for a type that is compatible according to the base language
13736 // rules.
13737 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13738 OMPDeclareReductionDecl *PrevDRD = nullptr;
13739 bool InCompoundScope = true;
13740 if (S != nullptr) {
13741 // Find previous declaration with the same name not referenced in other
13742 // declarations.
13743 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13744 InCompoundScope =
13745 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13746 LookupName(Lookup, S);
13747 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13748 /*AllowInlineNamespace=*/false);
13749 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013750 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013751 while (Filter.hasNext()) {
13752 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13753 if (InCompoundScope) {
13754 auto I = UsedAsPrevious.find(PrevDecl);
13755 if (I == UsedAsPrevious.end())
13756 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013757 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013758 UsedAsPrevious[D] = true;
13759 }
13760 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13761 PrevDecl->getLocation();
13762 }
13763 Filter.done();
13764 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013765 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013766 if (!PrevData.second) {
13767 PrevDRD = PrevData.first;
13768 break;
13769 }
13770 }
13771 }
13772 } else if (PrevDeclInScope != nullptr) {
13773 auto *PrevDRDInScope = PrevDRD =
13774 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13775 do {
13776 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13777 PrevDRDInScope->getLocation();
13778 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13779 } while (PrevDRDInScope != nullptr);
13780 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013781 for (const auto &TyData : ReductionTypes) {
13782 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013783 bool Invalid = false;
13784 if (I != PreviousRedeclTypes.end()) {
13785 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13786 << TyData.first;
13787 Diag(I->second, diag::note_previous_definition);
13788 Invalid = true;
13789 }
13790 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13791 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13792 Name, TyData.first, PrevDRD);
13793 DC->addDecl(DRD);
13794 DRD->setAccess(AS);
13795 Decls.push_back(DRD);
13796 if (Invalid)
13797 DRD->setInvalidDecl();
13798 else
13799 PrevDRD = DRD;
13800 }
13801
13802 return DeclGroupPtrTy::make(
13803 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13804}
13805
13806void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13807 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13808
13809 // Enter new function scope.
13810 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013811 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013812 getCurFunction()->setHasOMPDeclareReductionCombiner();
13813
13814 if (S != nullptr)
13815 PushDeclContext(S, DRD);
13816 else
13817 CurContext = DRD;
13818
Faisal Valid143a0c2017-04-01 21:30:49 +000013819 PushExpressionEvaluationContext(
13820 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013821
13822 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013823 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13824 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13825 // uses semantics of argument handles by value, but it should be passed by
13826 // reference. C lang does not support references, so pass all parameters as
13827 // pointers.
13828 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013829 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013830 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013831 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13832 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13833 // uses semantics of argument handles by value, but it should be passed by
13834 // reference. C lang does not support references, so pass all parameters as
13835 // pointers.
13836 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013837 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013838 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13839 if (S != nullptr) {
13840 PushOnScopeChains(OmpInParm, S);
13841 PushOnScopeChains(OmpOutParm, S);
13842 } else {
13843 DRD->addDecl(OmpInParm);
13844 DRD->addDecl(OmpOutParm);
13845 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013846 Expr *InE =
13847 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13848 Expr *OutE =
13849 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13850 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013851}
13852
13853void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13854 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13855 DiscardCleanupsInEvaluationContext();
13856 PopExpressionEvaluationContext();
13857
13858 PopDeclContext();
13859 PopFunctionScopeInfo();
13860
13861 if (Combiner != nullptr)
13862 DRD->setCombiner(Combiner);
13863 else
13864 DRD->setInvalidDecl();
13865}
13866
Alexey Bataev070f43a2017-09-06 14:49:58 +000013867VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013868 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13869
13870 // Enter new function scope.
13871 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013872 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013873
13874 if (S != nullptr)
13875 PushDeclContext(S, DRD);
13876 else
13877 CurContext = DRD;
13878
Faisal Valid143a0c2017-04-01 21:30:49 +000013879 PushExpressionEvaluationContext(
13880 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013881
13882 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013883 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13884 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13885 // uses semantics of argument handles by value, but it should be passed by
13886 // reference. C lang does not support references, so pass all parameters as
13887 // pointers.
13888 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013889 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013890 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013891 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13892 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13893 // uses semantics of argument handles by value, but it should be passed by
13894 // reference. C lang does not support references, so pass all parameters as
13895 // pointers.
13896 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013897 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013898 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013899 if (S != nullptr) {
13900 PushOnScopeChains(OmpPrivParm, S);
13901 PushOnScopeChains(OmpOrigParm, S);
13902 } else {
13903 DRD->addDecl(OmpPrivParm);
13904 DRD->addDecl(OmpOrigParm);
13905 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013906 Expr *OrigE =
13907 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13908 Expr *PrivE =
13909 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13910 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013911 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013912}
13913
Alexey Bataev070f43a2017-09-06 14:49:58 +000013914void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13915 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013916 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13917 DiscardCleanupsInEvaluationContext();
13918 PopExpressionEvaluationContext();
13919
13920 PopDeclContext();
13921 PopFunctionScopeInfo();
13922
Alexey Bataev070f43a2017-09-06 14:49:58 +000013923 if (Initializer != nullptr) {
13924 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13925 } else if (OmpPrivParm->hasInit()) {
13926 DRD->setInitializer(OmpPrivParm->getInit(),
13927 OmpPrivParm->isDirectInit()
13928 ? OMPDeclareReductionDecl::DirectInit
13929 : OMPDeclareReductionDecl::CopyInit);
13930 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013931 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013932 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013933}
13934
13935Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13936 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013937 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013938 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013939 if (S)
13940 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13941 /*AddToContext=*/false);
13942 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013943 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013944 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013945 }
13946 return DeclReductions;
13947}
13948
Michael Kruse251e1482019-02-01 20:25:04 +000013949TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13950 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13951 QualType T = TInfo->getType();
13952 if (D.isInvalidType())
13953 return true;
13954
13955 if (getLangOpts().CPlusPlus) {
13956 // Check that there are no default arguments (C++ only).
13957 CheckExtraCXXDefaultArguments(D);
13958 }
13959
13960 return CreateParsedType(T, TInfo);
13961}
13962
13963QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
13964 TypeResult ParsedType) {
13965 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
13966
13967 QualType MapperType = GetTypeFromParser(ParsedType.get());
13968 assert(!MapperType.isNull() && "Expect valid mapper type");
13969
13970 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13971 // The type must be of struct, union or class type in C and C++
13972 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
13973 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
13974 return QualType();
13975 }
13976 return MapperType;
13977}
13978
13979OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
13980 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
13981 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
13982 Decl *PrevDeclInScope) {
13983 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
13984 forRedeclarationInCurContext());
13985 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13986 // A mapper-identifier may not be redeclared in the current scope for the
13987 // same type or for a type that is compatible according to the base language
13988 // rules.
13989 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13990 OMPDeclareMapperDecl *PrevDMD = nullptr;
13991 bool InCompoundScope = true;
13992 if (S != nullptr) {
13993 // Find previous declaration with the same name not referenced in other
13994 // declarations.
13995 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13996 InCompoundScope =
13997 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13998 LookupName(Lookup, S);
13999 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14000 /*AllowInlineNamespace=*/false);
14001 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14002 LookupResult::Filter Filter = Lookup.makeFilter();
14003 while (Filter.hasNext()) {
14004 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14005 if (InCompoundScope) {
14006 auto I = UsedAsPrevious.find(PrevDecl);
14007 if (I == UsedAsPrevious.end())
14008 UsedAsPrevious[PrevDecl] = false;
14009 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14010 UsedAsPrevious[D] = true;
14011 }
14012 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14013 PrevDecl->getLocation();
14014 }
14015 Filter.done();
14016 if (InCompoundScope) {
14017 for (const auto &PrevData : UsedAsPrevious) {
14018 if (!PrevData.second) {
14019 PrevDMD = PrevData.first;
14020 break;
14021 }
14022 }
14023 }
14024 } else if (PrevDeclInScope) {
14025 auto *PrevDMDInScope = PrevDMD =
14026 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14027 do {
14028 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14029 PrevDMDInScope->getLocation();
14030 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14031 } while (PrevDMDInScope != nullptr);
14032 }
14033 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14034 bool Invalid = false;
14035 if (I != PreviousRedeclTypes.end()) {
14036 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14037 << MapperType << Name;
14038 Diag(I->second, diag::note_previous_definition);
14039 Invalid = true;
14040 }
14041 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14042 MapperType, VN, PrevDMD);
14043 DC->addDecl(DMD);
14044 DMD->setAccess(AS);
14045 if (Invalid)
14046 DMD->setInvalidDecl();
14047
14048 // Enter new function scope.
14049 PushFunctionScope();
14050 setFunctionHasBranchProtectedScope();
14051
14052 CurContext = DMD;
14053
14054 return DMD;
14055}
14056
14057void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14058 Scope *S,
14059 QualType MapperType,
14060 SourceLocation StartLoc,
14061 DeclarationName VN) {
14062 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14063 if (S)
14064 PushOnScopeChains(VD, S);
14065 else
14066 DMD->addDecl(VD);
14067 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14068 DMD->setMapperVarRef(MapperVarRefExpr);
14069}
14070
14071Sema::DeclGroupPtrTy
14072Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14073 ArrayRef<OMPClause *> ClauseList) {
14074 PopDeclContext();
14075 PopFunctionScopeInfo();
14076
14077 if (D) {
14078 if (S)
14079 PushOnScopeChains(D, S, /*AddToContext=*/false);
14080 D->CreateClauses(Context, ClauseList);
14081 }
14082
14083 return DeclGroupPtrTy::make(DeclGroupRef(D));
14084}
14085
David Majnemer9d168222016-08-05 17:44:54 +000014086OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014087 SourceLocation StartLoc,
14088 SourceLocation LParenLoc,
14089 SourceLocation EndLoc) {
14090 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014091 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014092
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014093 // OpenMP [teams Constrcut, Restrictions]
14094 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014095 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014096 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014097 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014098
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014099 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014100 OpenMPDirectiveKind CaptureRegion =
14101 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14102 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014103 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014104 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014105 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14106 HelperValStmt = buildPreInits(Context, Captures);
14107 }
14108
14109 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14110 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014111}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014112
14113OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14114 SourceLocation StartLoc,
14115 SourceLocation LParenLoc,
14116 SourceLocation EndLoc) {
14117 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014118 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014119
14120 // OpenMP [teams Constrcut, Restrictions]
14121 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014122 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014123 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014124 return nullptr;
14125
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014126 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014127 OpenMPDirectiveKind CaptureRegion =
14128 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14129 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014130 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014131 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014132 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14133 HelperValStmt = buildPreInits(Context, Captures);
14134 }
14135
14136 return new (Context) OMPThreadLimitClause(
14137 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014138}
Alexey Bataeva0569352015-12-01 10:17:31 +000014139
14140OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14141 SourceLocation StartLoc,
14142 SourceLocation LParenLoc,
14143 SourceLocation EndLoc) {
14144 Expr *ValExpr = Priority;
14145
14146 // OpenMP [2.9.1, task Constrcut]
14147 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014148 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014149 /*StrictlyPositive=*/false))
14150 return nullptr;
14151
14152 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14153}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014154
14155OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14156 SourceLocation StartLoc,
14157 SourceLocation LParenLoc,
14158 SourceLocation EndLoc) {
14159 Expr *ValExpr = Grainsize;
14160
14161 // OpenMP [2.9.2, taskloop Constrcut]
14162 // The parameter of the grainsize clause must be a positive integer
14163 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014164 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014165 /*StrictlyPositive=*/true))
14166 return nullptr;
14167
14168 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14169}
Alexey Bataev382967a2015-12-08 12:06:20 +000014170
14171OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14172 SourceLocation StartLoc,
14173 SourceLocation LParenLoc,
14174 SourceLocation EndLoc) {
14175 Expr *ValExpr = NumTasks;
14176
14177 // OpenMP [2.9.2, taskloop Constrcut]
14178 // The parameter of the num_tasks clause must be a positive integer
14179 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014180 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014181 /*StrictlyPositive=*/true))
14182 return nullptr;
14183
14184 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14185}
14186
Alexey Bataev28c75412015-12-15 08:19:24 +000014187OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14188 SourceLocation LParenLoc,
14189 SourceLocation EndLoc) {
14190 // OpenMP [2.13.2, critical construct, Description]
14191 // ... where hint-expression is an integer constant expression that evaluates
14192 // to a valid lock hint.
14193 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14194 if (HintExpr.isInvalid())
14195 return nullptr;
14196 return new (Context)
14197 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14198}
14199
Carlo Bertollib4adf552016-01-15 18:50:31 +000014200OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14201 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14202 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14203 SourceLocation EndLoc) {
14204 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14205 std::string Values;
14206 Values += "'";
14207 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14208 Values += "'";
14209 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14210 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14211 return nullptr;
14212 }
14213 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014214 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014215 if (ChunkSize) {
14216 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14217 !ChunkSize->isInstantiationDependent() &&
14218 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014219 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014220 ExprResult Val =
14221 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14222 if (Val.isInvalid())
14223 return nullptr;
14224
14225 ValExpr = Val.get();
14226
14227 // OpenMP [2.7.1, Restrictions]
14228 // chunk_size must be a loop invariant integer expression with a positive
14229 // value.
14230 llvm::APSInt Result;
14231 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14232 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14233 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14234 << "dist_schedule" << ChunkSize->getSourceRange();
14235 return nullptr;
14236 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014237 } else if (getOpenMPCaptureRegionForClause(
14238 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14239 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014240 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014241 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014242 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014243 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14244 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014245 }
14246 }
14247 }
14248
14249 return new (Context)
14250 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014251 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014252}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014253
14254OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14255 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14256 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14257 SourceLocation KindLoc, SourceLocation EndLoc) {
14258 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014259 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014260 std::string Value;
14261 SourceLocation Loc;
14262 Value += "'";
14263 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14264 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014265 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014266 Loc = MLoc;
14267 } else {
14268 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014269 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014270 Loc = KindLoc;
14271 }
14272 Value += "'";
14273 Diag(Loc, diag::err_omp_unexpected_clause_value)
14274 << Value << getOpenMPClauseName(OMPC_defaultmap);
14275 return nullptr;
14276 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014277 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014278
14279 return new (Context)
14280 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14281}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014282
14283bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14284 DeclContext *CurLexicalContext = getCurLexicalContext();
14285 if (!CurLexicalContext->isFileContext() &&
14286 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014287 !CurLexicalContext->isExternCXXContext() &&
14288 !isa<CXXRecordDecl>(CurLexicalContext) &&
14289 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14290 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14291 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014292 Diag(Loc, diag::err_omp_region_not_file_context);
14293 return false;
14294 }
Kelvin Libc38e632018-09-10 02:07:09 +000014295 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014296 return true;
14297}
14298
14299void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014300 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014301 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014302 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014303}
14304
David Majnemer9d168222016-08-05 17:44:54 +000014305void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14306 CXXScopeSpec &ScopeSpec,
14307 const DeclarationNameInfo &Id,
14308 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14309 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014310 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14311 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14312
14313 if (Lookup.isAmbiguous())
14314 return;
14315 Lookup.suppressDiagnostics();
14316
14317 if (!Lookup.isSingleResult()) {
14318 if (TypoCorrection Corrected =
14319 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14320 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14321 CTK_ErrorRecovery)) {
14322 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14323 << Id.getName());
14324 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14325 return;
14326 }
14327
14328 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14329 return;
14330 }
14331
14332 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014333 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14334 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014335 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14336 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014337 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14338 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14339 cast<ValueDecl>(ND));
14340 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014341 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014342 ND->addAttr(A);
14343 if (ASTMutationListener *ML = Context.getASTMutationListener())
14344 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014345 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014346 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014347 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14348 << Id.getName();
14349 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014350 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014351 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014352 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014353}
14354
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014355static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14356 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014357 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014358 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014359 auto *VD = cast<VarDecl>(D);
14360 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14361 return;
14362 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14363 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014364}
14365
14366static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14367 Sema &SemaRef, DSAStackTy *Stack,
14368 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014369 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14370 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14371 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014372}
14373
Kelvin Li1ce87c72017-12-12 20:08:12 +000014374void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14375 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014376 if (!D || D->isInvalidDecl())
14377 return;
14378 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014379 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014380 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014381 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014382 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14383 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014384 return;
14385 // 2.10.6: threadprivate variable cannot appear in a declare target
14386 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014387 if (DSAStack->isThreadPrivate(VD)) {
14388 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014389 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014390 return;
14391 }
14392 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014393 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14394 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014395 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014396 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14397 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14398 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014399 assert(IdLoc.isValid() && "Source location is expected");
14400 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14401 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14402 return;
14403 }
14404 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014405 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14406 // Problem if any with var declared with incomplete type will be reported
14407 // as normal, so no need to check it here.
14408 if ((E || !VD->getType()->isIncompleteType()) &&
14409 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14410 return;
14411 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14412 // Checking declaration inside declare target region.
14413 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14414 isa<FunctionTemplateDecl>(D)) {
14415 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14416 Context, OMPDeclareTargetDeclAttr::MT_To);
14417 D->addAttr(A);
14418 if (ASTMutationListener *ML = Context.getASTMutationListener())
14419 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14420 }
14421 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014422 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014423 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014424 if (!E)
14425 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014426 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14427}
Samuel Antao661c0902016-05-26 17:39:58 +000014428
14429OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014430 CXXScopeSpec &MapperIdScopeSpec,
14431 DeclarationNameInfo &MapperId,
14432 const OMPVarListLocTy &Locs,
14433 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014434 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014435 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14436 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014437 if (MVLI.ProcessedVarList.empty())
14438 return nullptr;
14439
Michael Kruse01f670d2019-02-22 22:29:42 +000014440 return OMPToClause::Create(
14441 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14442 MVLI.VarComponents, MVLI.UDMapperList,
14443 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014444}
Samuel Antaoec172c62016-05-26 17:49:04 +000014445
14446OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014447 CXXScopeSpec &MapperIdScopeSpec,
14448 DeclarationNameInfo &MapperId,
14449 const OMPVarListLocTy &Locs,
14450 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014451 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014452 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14453 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014454 if (MVLI.ProcessedVarList.empty())
14455 return nullptr;
14456
Michael Kruse0336c752019-02-25 20:34:15 +000014457 return OMPFromClause::Create(
14458 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14459 MVLI.VarComponents, MVLI.UDMapperList,
14460 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014461}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014462
14463OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014464 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014465 MappableVarListInfo MVLI(VarList);
14466 SmallVector<Expr *, 8> PrivateCopies;
14467 SmallVector<Expr *, 8> Inits;
14468
Alexey Bataeve3727102018-04-18 15:57:46 +000014469 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014470 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14471 SourceLocation ELoc;
14472 SourceRange ERange;
14473 Expr *SimpleRefExpr = RefExpr;
14474 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14475 if (Res.second) {
14476 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014477 MVLI.ProcessedVarList.push_back(RefExpr);
14478 PrivateCopies.push_back(nullptr);
14479 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014480 }
14481 ValueDecl *D = Res.first;
14482 if (!D)
14483 continue;
14484
14485 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014486 Type = Type.getNonReferenceType().getUnqualifiedType();
14487
14488 auto *VD = dyn_cast<VarDecl>(D);
14489
14490 // Item should be a pointer or reference to pointer.
14491 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014492 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14493 << 0 << RefExpr->getSourceRange();
14494 continue;
14495 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014496
14497 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014498 auto VDPrivate =
14499 buildVarDecl(*this, ELoc, Type, D->getName(),
14500 D->hasAttrs() ? &D->getAttrs() : nullptr,
14501 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014502 if (VDPrivate->isInvalidDecl())
14503 continue;
14504
14505 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014506 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014507 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14508
14509 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014510 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014511 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014512 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14513 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014514 AddInitializerToDecl(VDPrivate,
14515 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014516 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014517
14518 // If required, build a capture to implement the privatization initialized
14519 // with the current list item value.
14520 DeclRefExpr *Ref = nullptr;
14521 if (!VD)
14522 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14523 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14524 PrivateCopies.push_back(VDPrivateRefExpr);
14525 Inits.push_back(VDInitRefExpr);
14526
14527 // We need to add a data sharing attribute for this variable to make sure it
14528 // is correctly captured. A variable that shows up in a use_device_ptr has
14529 // similar properties of a first private variable.
14530 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14531
14532 // Create a mappable component for the list item. List items in this clause
14533 // only need a component.
14534 MVLI.VarBaseDeclarations.push_back(D);
14535 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14536 MVLI.VarComponents.back().push_back(
14537 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014538 }
14539
Samuel Antaocc10b852016-07-28 14:23:26 +000014540 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014541 return nullptr;
14542
Samuel Antaocc10b852016-07-28 14:23:26 +000014543 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014544 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14545 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014546}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014547
14548OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014549 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014550 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014551 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014552 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014553 SourceLocation ELoc;
14554 SourceRange ERange;
14555 Expr *SimpleRefExpr = RefExpr;
14556 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14557 if (Res.second) {
14558 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014559 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014560 }
14561 ValueDecl *D = Res.first;
14562 if (!D)
14563 continue;
14564
14565 QualType Type = D->getType();
14566 // item should be a pointer or array or reference to pointer or array
14567 if (!Type.getNonReferenceType()->isPointerType() &&
14568 !Type.getNonReferenceType()->isArrayType()) {
14569 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14570 << 0 << RefExpr->getSourceRange();
14571 continue;
14572 }
Samuel Antao6890b092016-07-28 14:25:09 +000014573
14574 // Check if the declaration in the clause does not show up in any data
14575 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014576 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014577 if (isOpenMPPrivate(DVar.CKind)) {
14578 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14579 << getOpenMPClauseName(DVar.CKind)
14580 << getOpenMPClauseName(OMPC_is_device_ptr)
14581 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014582 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014583 continue;
14584 }
14585
Alexey Bataeve3727102018-04-18 15:57:46 +000014586 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014587 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014588 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014589 [&ConflictExpr](
14590 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14591 OpenMPClauseKind) -> bool {
14592 ConflictExpr = R.front().getAssociatedExpression();
14593 return true;
14594 })) {
14595 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14596 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14597 << ConflictExpr->getSourceRange();
14598 continue;
14599 }
14600
14601 // Store the components in the stack so that they can be used to check
14602 // against other clauses later on.
14603 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14604 DSAStack->addMappableExpressionComponents(
14605 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14606
14607 // Record the expression we've just processed.
14608 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14609
14610 // Create a mappable component for the list item. List items in this clause
14611 // only need a component. We use a null declaration to signal fields in
14612 // 'this'.
14613 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14614 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14615 "Unexpected device pointer expression!");
14616 MVLI.VarBaseDeclarations.push_back(
14617 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14618 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14619 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014620 }
14621
Samuel Antao6890b092016-07-28 14:25:09 +000014622 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014623 return nullptr;
14624
Michael Kruse4304e9d2019-02-19 16:38:20 +000014625 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14626 MVLI.VarBaseDeclarations,
14627 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014628}