blob: 7fed3725edd4c72e5c8368083ec96d59e4deb477 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
142 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000143 bool NowaitRegion = false;
144 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000145 bool LoopStart = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000146 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000147 /// Reference to the taskgroup task_reduction reference expression.
148 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000149 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeved09d242014-05-28 05:53:51 +0000150 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000151 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000152 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
153 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000154 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000155 };
156
Alexey Bataeve3727102018-04-18 15:57:46 +0000157 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000159 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000160 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000161 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
162 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000163 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000164 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000165 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000166 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000167 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000168 /// true if all the vaiables in the target executable directives must be
169 /// captured by reference.
170 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000171 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000172
Alexey Bataeve3727102018-04-18 15:57:46 +0000173 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000174
Alexey Bataeve3727102018-04-18 15:57:46 +0000175 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000178 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000179
Alexey Bataev4b465392017-04-26 15:06:24 +0000180 bool isStackEmpty() const {
181 return Stack.empty() ||
182 Stack.back().second != CurrentNonCapturingFunctionScope ||
183 Stack.back().first.empty();
184 }
185
Kelvin Li1408f912018-09-26 04:28:39 +0000186 /// Vector of previously declared requires directives
187 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
188
Alexey Bataev758e55e2013-09-06 18:03:48 +0000189public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000190 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000191
Alexey Bataevaac108a2015-06-23 04:51:00 +0000192 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000193 OpenMPClauseKind getClauseParsingMode() const {
194 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
195 return ClauseKindMode;
196 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000197 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000199 bool isForceVarCapturing() const { return ForceCapturing; }
200 void setForceVarCapturing(bool V) { ForceCapturing = V; }
201
Alexey Bataev60705422018-10-30 15:50:12 +0000202 void setForceCaptureByReferenceInTargetExecutable(bool V) {
203 ForceCaptureByReferenceInTargetExecutable = V;
204 }
205 bool isForceCaptureByReferenceInTargetExecutable() const {
206 return ForceCaptureByReferenceInTargetExecutable;
207 }
208
Alexey Bataev758e55e2013-09-06 18:03:48 +0000209 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000210 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000211 if (Stack.empty() ||
212 Stack.back().second != CurrentNonCapturingFunctionScope)
213 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
214 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
215 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000216 }
217
218 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000219 assert(!Stack.back().first.empty() &&
220 "Data-sharing attributes stack is empty!");
221 Stack.back().first.pop_back();
222 }
223
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000224 /// Marks that we're started loop parsing.
225 void loopInit() {
226 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
227 "Expected loop-based directive.");
228 Stack.back().first.back().LoopStart = true;
229 }
230 /// Start capturing of the variables in the loop context.
231 void loopStart() {
232 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
233 "Expected loop-based directive.");
234 Stack.back().first.back().LoopStart = false;
235 }
236 /// true, if variables are captured, false otherwise.
237 bool isLoopStarted() const {
238 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
239 "Expected loop-based directive.");
240 return !Stack.back().first.back().LoopStart;
241 }
242 /// Marks (or clears) declaration as possibly loop counter.
243 void resetPossibleLoopCounter(const Decl *D = nullptr) {
244 Stack.back().first.back().PossiblyLoopCounter =
245 D ? D->getCanonicalDecl() : D;
246 }
247 /// Gets the possible loop counter decl.
248 const Decl *getPossiblyLoopCunter() const {
249 return Stack.back().first.back().PossiblyLoopCounter;
250 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000251 /// Start new OpenMP region stack in new non-capturing function.
252 void pushFunction() {
253 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
254 assert(!isa<CapturingScopeInfo>(CurFnScope));
255 CurrentNonCapturingFunctionScope = CurFnScope;
256 }
257 /// Pop region stack for non-capturing function.
258 void popFunction(const FunctionScopeInfo *OldFSI) {
259 if (!Stack.empty() && Stack.back().second == OldFSI) {
260 assert(Stack.back().first.empty());
261 Stack.pop_back();
262 }
263 CurrentNonCapturingFunctionScope = nullptr;
264 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
265 if (!isa<CapturingScopeInfo>(FSI)) {
266 CurrentNonCapturingFunctionScope = FSI;
267 break;
268 }
269 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000270 }
271
Alexey Bataeve3727102018-04-18 15:57:46 +0000272 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000273 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000274 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000275 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000276 getCriticalWithHint(const DeclarationNameInfo &Name) const {
277 auto I = Criticals.find(Name.getAsString());
278 if (I != Criticals.end())
279 return I->second;
280 return std::make_pair(nullptr, llvm::APSInt());
281 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000282 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000283 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000284 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000285 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000287 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000288 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000289 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000290 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000291 /// \return The index of the loop control variable in the list of associated
292 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000293 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000294 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000295 /// parent region.
296 /// \return The index of the loop control variable in the list of associated
297 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000298 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000300 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000301 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000303 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000304 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000305 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000306
Alexey Bataevfa312f32017-07-21 18:48:21 +0000307 /// Adds additional information for the reduction items with the reduction id
308 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000309 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000310 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000311 /// Adds additional information for the reduction items with the reduction id
312 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000313 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000314 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000315 /// Returns the location and reduction operation from the innermost parent
316 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000317 const DSAVarData
318 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
319 BinaryOperatorKind &BOK,
320 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000321 /// Returns the location and reduction operation from the innermost parent
322 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000323 const DSAVarData
324 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
325 const Expr *&ReductionRef,
326 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000327 /// Return reduction reference expression for the current taskgroup.
328 Expr *getTaskgroupReductionRef() const {
329 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
330 "taskgroup reference expression requested for non taskgroup "
331 "directive.");
332 return Stack.back().first.back().TaskgroupReductionRef;
333 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000334 /// Checks if the given \p VD declaration is actually a taskgroup reduction
335 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000336 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000337 return Stack.back().first[Level].TaskgroupReductionRef &&
338 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
339 ->getDecl() == VD;
340 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000341
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000342 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000344 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000345 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000346 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000347 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000348 /// match specified \a CPred predicate in any directive which matches \a DPred
349 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000350 const DSAVarData
351 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
352 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
353 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000354 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000355 /// match specified \a CPred predicate in any innermost directive which
356 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000357 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000358 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000359 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
360 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000361 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000362 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000363 /// attributes which match specified \a CPred predicate at the specified
364 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000365 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000366 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000367 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000369 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000370 /// specified \a DPred predicate.
371 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000372 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000373 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000375 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000376 bool hasDirective(
377 const llvm::function_ref<bool(
378 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
379 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000380 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000383 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000385 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000386 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000387 OpenMPDirectiveKind getDirective(unsigned Level) const {
388 assert(!isStackEmpty() && "No directive at specified level.");
389 return Stack.back().first[Level].Directive;
390 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000391 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000392 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000393 if (isStackEmpty() || Stack.back().first.size() == 1)
394 return OMPD_unknown;
395 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000396 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000397
Kelvin Li1408f912018-09-26 04:28:39 +0000398 /// Add requires decl to internal vector
399 void addRequiresDecl(OMPRequiresDecl *RD) {
400 RequiresDecls.push_back(RD);
401 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402
Kelvin Li1408f912018-09-26 04:28:39 +0000403 /// Checks for a duplicate clause amongst previously declared requires
404 /// directives
405 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
406 bool IsDuplicate = false;
407 for (OMPClause *CNew : ClauseList) {
408 for (const OMPRequiresDecl *D : RequiresDecls) {
409 for (const OMPClause *CPrev : D->clauselists()) {
410 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
411 SemaRef.Diag(CNew->getBeginLoc(),
412 diag::err_omp_requires_clause_redeclaration)
413 << getOpenMPClauseName(CNew->getClauseKind());
414 SemaRef.Diag(CPrev->getBeginLoc(),
415 diag::note_omp_requires_previous_clause)
416 << getOpenMPClauseName(CPrev->getClauseKind());
417 IsDuplicate = true;
418 }
419 }
420 }
421 }
422 return IsDuplicate;
423 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000425 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000426 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 assert(!isStackEmpty());
428 Stack.back().first.back().DefaultAttr = DSA_none;
429 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000430 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000432 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000433 assert(!isStackEmpty());
434 Stack.back().first.back().DefaultAttr = DSA_shared;
435 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000436 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000437 /// Set default data mapping attribute to 'tofrom:scalar'.
438 void setDefaultDMAToFromScalar(SourceLocation Loc) {
439 assert(!isStackEmpty());
440 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
441 Stack.back().first.back().DefaultMapAttrLoc = Loc;
442 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000443
444 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000445 return isStackEmpty() ? DSA_unspecified
446 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000448 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000449 return isStackEmpty() ? SourceLocation()
450 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000451 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000452 DefaultMapAttributes getDefaultDMA() const {
453 return isStackEmpty() ? DMA_unspecified
454 : Stack.back().first.back().DefaultMapAttr;
455 }
456 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
457 return Stack.back().first[Level].DefaultMapAttr;
458 }
459 SourceLocation getDefaultDMALocation() const {
460 return isStackEmpty() ? SourceLocation()
461 : Stack.back().first.back().DefaultMapAttrLoc;
462 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000463
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000464 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000465 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000466 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000467 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000468 }
469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000470 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000471 void setOrderedRegion(bool IsOrdered, const Expr *Param,
472 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000473 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000474 if (IsOrdered)
475 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
476 else
477 Stack.back().first.back().OrderedRegion.reset();
478 }
479 /// Returns true, if region is ordered (has associated 'ordered' clause),
480 /// false - otherwise.
481 bool isOrderedRegion() const {
482 if (isStackEmpty())
483 return false;
484 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
485 }
486 /// Returns optional parameter for the ordered region.
487 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
488 if (isStackEmpty() ||
489 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
490 return std::make_pair(nullptr, nullptr);
491 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000492 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000494 /// 'ordered' clause), false - otherwise.
495 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000496 if (isStackEmpty() || Stack.back().first.size() == 1)
497 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000498 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000499 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000500 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000501 std::pair<const Expr *, OMPOrderedClause *>
502 getParentOrderedRegionParam() const {
503 if (isStackEmpty() || Stack.back().first.size() == 1 ||
504 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
505 return std::make_pair(nullptr, nullptr);
506 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000507 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000509 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000510 assert(!isStackEmpty());
511 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000512 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000513 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000514 /// 'nowait' clause), false - otherwise.
515 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000516 if (isStackEmpty() || Stack.back().first.size() == 1)
517 return false;
518 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000521 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000522 if (!isStackEmpty() && Stack.back().first.size() > 1) {
523 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
524 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
525 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000526 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000527 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000528 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000529 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000530 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000531
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000533 void setAssociatedLoops(unsigned Val) {
534 assert(!isStackEmpty());
535 Stack.back().first.back().AssociatedLoops = Val;
536 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000538 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000539 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000540 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000541
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000543 /// region.
544 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000545 if (!isStackEmpty() && Stack.back().first.size() > 1) {
546 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
547 TeamsRegionLoc;
548 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000549 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000550 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000551 bool hasInnerTeamsRegion() const {
552 return getInnerTeamsRegionLoc().isValid();
553 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000554 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000555 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000556 return isStackEmpty() ? SourceLocation()
557 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000558 }
559
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000562 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000563 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000564 return isStackEmpty() ? SourceLocation()
565 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000566 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000567
Samuel Antao4c8035b2016-12-12 18:00:20 +0000568 /// Do the check specified in \a Check to all component lists and return true
569 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000570 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000571 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000572 const llvm::function_ref<
573 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000574 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000575 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000576 if (isStackEmpty())
577 return false;
578 auto SI = Stack.back().first.rbegin();
579 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000580
581 if (SI == SE)
582 return false;
583
Alexey Bataeve3727102018-04-18 15:57:46 +0000584 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000585 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000586 else
587 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000588
589 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000590 auto MI = SI->MappedExprComponents.find(VD);
591 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000592 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
593 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000594 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000595 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000596 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000597 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000598 }
599
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000600 /// Do the check specified in \a Check to all component lists at a given level
601 /// and return true if any issue is found.
602 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000603 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000604 const llvm::function_ref<
605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000606 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000607 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000608 if (isStackEmpty())
609 return false;
610
611 auto StartI = Stack.back().first.begin();
612 auto EndI = Stack.back().first.end();
613 if (std::distance(StartI, EndI) <= (int)Level)
614 return false;
615 std::advance(StartI, Level);
616
617 auto MI = StartI->MappedExprComponents.find(VD);
618 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000619 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
620 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000621 if (Check(L, MI->second.Kind))
622 return true;
623 return false;
624 }
625
Samuel Antao4c8035b2016-12-12 18:00:20 +0000626 /// Create a new mappable expression component list associated with a given
627 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000628 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000629 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
631 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000632 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000633 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000634 MappedExprComponentTy &MEC =
635 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000636 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000637 MEC.Components.resize(MEC.Components.size() + 1);
638 MEC.Components.back().append(Components.begin(), Components.end());
639 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000640 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000641
642 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000643 assert(!isStackEmpty());
644 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000645 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000646 void addDoacrossDependClause(OMPDependClause *C,
647 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000648 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000649 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000650 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000652 }
653 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
654 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000655 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000656 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000657 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000658 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000659 return llvm::make_range(Ref.begin(), Ref.end());
660 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000661 return llvm::make_range(StackElem.DoacrossDepends.end(),
662 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000663 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000664
665 // Store types of classes which have been explicitly mapped
666 void addMappedClassesQualTypes(QualType QT) {
667 SharingMapTy &StackElem = Stack.back().first.back();
668 StackElem.MappedClassesQualTypes.insert(QT);
669 }
670
671 // Return set of mapped classes types
672 bool isClassPreviouslyMapped(QualType QT) const {
673 const SharingMapTy &StackElem = Stack.back().first.back();
674 return StackElem.MappedClassesQualTypes.count(QT) != 0;
675 }
676
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000678
679bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
680 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
681}
682
683bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
684 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000685}
Alexey Bataeve3727102018-04-18 15:57:46 +0000686
Alexey Bataeved09d242014-05-28 05:53:51 +0000687} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000688
Alexey Bataeve3727102018-04-18 15:57:46 +0000689static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000690 if (const auto *FE = dyn_cast<FullExpr>(E))
691 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000692
Alexey Bataeve3727102018-04-18 15:57:46 +0000693 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000694 E = MTE->GetTemporaryExpr();
695
Alexey Bataeve3727102018-04-18 15:57:46 +0000696 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000697 E = Binder->getSubExpr();
698
Alexey Bataeve3727102018-04-18 15:57:46 +0000699 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000700 E = ICE->getSubExprAsWritten();
701 return E->IgnoreParens();
702}
703
Alexey Bataeve3727102018-04-18 15:57:46 +0000704static Expr *getExprAsWritten(Expr *E) {
705 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
706}
707
708static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
709 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
710 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000711 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000712 const auto *VD = dyn_cast<VarDecl>(D);
713 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000714 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000715 VD = VD->getCanonicalDecl();
716 D = VD;
717 } else {
718 assert(FD);
719 FD = FD->getCanonicalDecl();
720 D = FD;
721 }
722 return D;
723}
724
Alexey Bataeve3727102018-04-18 15:57:46 +0000725static ValueDecl *getCanonicalDecl(ValueDecl *D) {
726 return const_cast<ValueDecl *>(
727 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
728}
729
730DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
731 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000732 D = getCanonicalDecl(D);
733 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000734 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000735 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000737 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
738 // in a region but not in construct]
739 // File-scope or namespace-scope variables referenced in called routines
740 // in the region are shared unless they appear in a threadprivate
741 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000742 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000743 DVar.CKind = OMPC_shared;
744
745 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
746 // in a region but not in construct]
747 // Variables with static storage duration that are declared in called
748 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000749 if (VD && VD->hasGlobalStorage())
750 DVar.CKind = OMPC_shared;
751
752 // Non-static data members are shared by default.
753 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000754 DVar.CKind = OMPC_shared;
755
Alexey Bataev758e55e2013-09-06 18:03:48 +0000756 return DVar;
757 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000758
Alexey Bataevec3da872014-01-31 05:15:34 +0000759 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
760 // in a Construct, C/C++, predetermined, p.1]
761 // Variables with automatic storage duration that are declared in a scope
762 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000763 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
764 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000765 DVar.CKind = OMPC_private;
766 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000767 }
768
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000769 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 // Explicitly specified attributes and local variables with predetermined
771 // attributes.
772 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000773 const DSAInfo &Data = Iter->SharingMap.lookup(D);
774 DVar.RefExpr = Data.RefExpr.getPointer();
775 DVar.PrivateCopy = Data.PrivateCopy;
776 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000777 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000778 return DVar;
779 }
780
781 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
782 // in a Construct, C/C++, implicitly determined, p.1]
783 // In a parallel or task construct, the data-sharing attributes of these
784 // variables are determined by the default clause, if present.
785 switch (Iter->DefaultAttr) {
786 case DSA_shared:
787 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000788 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000789 return DVar;
790 case DSA_none:
791 return DVar;
792 case DSA_unspecified:
793 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
794 // in a Construct, implicitly determined, p.2]
795 // In a parallel construct, if no default clause is present, these
796 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000797 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000798 if (isOpenMPParallelDirective(DVar.DKind) ||
799 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000800 DVar.CKind = OMPC_shared;
801 return DVar;
802 }
803
804 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
805 // in a Construct, implicitly determined, p.4]
806 // In a task construct, if no default clause is present, a variable that in
807 // the enclosing context is determined to be shared by all implicit tasks
808 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000809 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000810 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000811 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000812 do {
813 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000814 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000815 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000816 // In a task construct, if no default clause is present, a variable
817 // whose data-sharing attribute is not determined by the rules above is
818 // firstprivate.
819 DVarTemp = getDSA(I, D);
820 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000821 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000822 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000823 return DVar;
824 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000825 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000826 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000827 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000828 return DVar;
829 }
830 }
831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
832 // in a Construct, implicitly determined, p.3]
833 // For constructs other than task, if no default clause is present, these
834 // variables inherit their data-sharing attributes from the enclosing
835 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000836 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000837}
838
Alexey Bataeve3727102018-04-18 15:57:46 +0000839const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
840 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000841 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000842 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000843 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000844 auto It = StackElem.AlignedMap.find(D);
845 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000846 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000847 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000848 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000849 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000850 assert(It->second && "Unexpected nullptr expr in the aligned map");
851 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000852}
853
Alexey Bataeve3727102018-04-18 15:57:46 +0000854void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000855 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000856 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000857 SharingMapTy &StackElem = Stack.back().first.back();
858 StackElem.LCVMap.try_emplace(
859 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000860}
861
Alexey Bataeve3727102018-04-18 15:57:46 +0000862const DSAStackTy::LCDeclInfo
863DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000864 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000865 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000866 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000867 auto It = StackElem.LCVMap.find(D);
868 if (It != StackElem.LCVMap.end())
869 return It->second;
870 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000871}
872
Alexey Bataeve3727102018-04-18 15:57:46 +0000873const DSAStackTy::LCDeclInfo
874DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000875 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
876 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000877 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000878 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000879 auto It = StackElem.LCVMap.find(D);
880 if (It != StackElem.LCVMap.end())
881 return It->second;
882 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000883}
884
Alexey Bataeve3727102018-04-18 15:57:46 +0000885const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000886 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
887 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000888 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000889 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000890 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000891 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000892 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000893 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000894 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000895}
896
Alexey Bataeve3727102018-04-18 15:57:46 +0000897void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000898 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000899 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000900 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000901 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000902 Data.Attributes = A;
903 Data.RefExpr.setPointer(E);
904 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000905 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000906 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000907 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000908 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
909 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
910 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
911 (isLoopControlVariable(D).first && A == OMPC_private));
912 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
913 Data.RefExpr.setInt(/*IntVal=*/true);
914 return;
915 }
916 const bool IsLastprivate =
917 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
918 Data.Attributes = A;
919 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
920 Data.PrivateCopy = PrivateCopy;
921 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000922 DSAInfo &Data =
923 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000924 Data.Attributes = A;
925 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
926 Data.PrivateCopy = nullptr;
927 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000928 }
929}
930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000931/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000932static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000933 StringRef Name, const AttrVec *Attrs = nullptr,
934 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000935 DeclContext *DC = SemaRef.CurContext;
936 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
937 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000938 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000939 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
940 if (Attrs) {
941 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
942 I != E; ++I)
943 Decl->addAttr(*I);
944 }
945 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000946 if (OrigRef) {
947 Decl->addAttr(
948 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
949 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000950 return Decl;
951}
952
953static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
954 SourceLocation Loc,
955 bool RefersToCapture = false) {
956 D->setReferenced();
957 D->markUsed(S.Context);
958 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
959 SourceLocation(), D, RefersToCapture, Loc, Ty,
960 VK_LValue);
961}
962
Alexey Bataeve3727102018-04-18 15:57:46 +0000963void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000964 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000965 D = getCanonicalDecl(D);
966 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000967 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000968 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000969 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000970 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000971 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000972 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000973 "Additional reduction info may be specified only once for reduction "
974 "items.");
975 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000976 Expr *&TaskgroupReductionRef =
977 Stack.back().first.back().TaskgroupReductionRef;
978 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000979 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
980 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000981 TaskgroupReductionRef =
982 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000983 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000984}
985
Alexey Bataeve3727102018-04-18 15:57:46 +0000986void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000987 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000988 D = getCanonicalDecl(D);
989 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000990 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000991 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000992 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000993 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000994 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000995 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000996 "Additional reduction info may be specified only once for reduction "
997 "items.");
998 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000999 Expr *&TaskgroupReductionRef =
1000 Stack.back().first.back().TaskgroupReductionRef;
1001 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001002 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1003 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001004 TaskgroupReductionRef =
1005 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001006 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001007}
1008
Alexey Bataeve3727102018-04-18 15:57:46 +00001009const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1010 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1011 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001012 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1014 if (Stack.back().first.empty())
1015 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001016 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1017 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001018 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001019 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001020 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001021 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001022 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001023 if (!ReductionData.ReductionOp ||
1024 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001025 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001026 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001027 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001028 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1029 "expression for the descriptor is not "
1030 "set.");
1031 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001032 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1033 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001034 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001035 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001036}
1037
Alexey Bataeve3727102018-04-18 15:57:46 +00001038const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1039 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1040 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001041 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001042 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1043 if (Stack.back().first.empty())
1044 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001045 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1046 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001047 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001048 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001049 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001050 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001051 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001052 if (!ReductionData.ReductionOp ||
1053 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001054 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001055 SR = ReductionData.ReductionRange;
1056 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001057 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1058 "expression for the descriptor is not "
1059 "set.");
1060 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001061 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1062 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001063 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001064 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001065}
1066
Alexey Bataeve3727102018-04-18 15:57:46 +00001067bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001068 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001069 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001070 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001071 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001072 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001073 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001074 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001075 if (I == E)
1076 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001077 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001078 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001079 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001080 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001081 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001082 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001083 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001084}
1085
Joel E. Dennyd2649292019-01-04 22:11:56 +00001086static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1087 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001088 bool *IsClassType = nullptr) {
1089 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001090 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001091 bool IsConstant = Type.isConstant(Context);
1092 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001093 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1094 ? Type->getAsCXXRecordDecl()
1095 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001096 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1097 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1098 RD = CTD->getTemplatedDecl();
1099 if (IsClassType)
1100 *IsClassType = RD;
1101 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1102 RD->hasDefinition() && RD->hasMutableFields());
1103}
1104
Joel E. Dennyd2649292019-01-04 22:11:56 +00001105static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1106 QualType Type, OpenMPClauseKind CKind,
1107 SourceLocation ELoc,
1108 bool AcceptIfMutable = true,
1109 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001110 ASTContext &Context = SemaRef.getASTContext();
1111 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001112 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1113 unsigned Diag = ListItemNotVar
1114 ? diag::err_omp_const_list_item
1115 : IsClassType ? diag::err_omp_const_not_mutable_variable
1116 : diag::err_omp_const_variable;
1117 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1118 if (!ListItemNotVar && D) {
1119 const VarDecl *VD = dyn_cast<VarDecl>(D);
1120 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1121 VarDecl::DeclarationOnly;
1122 SemaRef.Diag(D->getLocation(),
1123 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1124 << D;
1125 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001126 return true;
1127 }
1128 return false;
1129}
1130
Alexey Bataeve3727102018-04-18 15:57:46 +00001131const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1132 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001133 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001134 DSAVarData DVar;
1135
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001136 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001137 auto TI = Threadprivates.find(D);
1138 if (TI != Threadprivates.end()) {
1139 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001140 DVar.CKind = OMPC_threadprivate;
1141 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001142 }
1143 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001144 DVar.RefExpr = buildDeclRefExpr(
1145 SemaRef, VD, D->getType().getNonReferenceType(),
1146 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1147 DVar.CKind = OMPC_threadprivate;
1148 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001149 return DVar;
1150 }
1151 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1152 // in a Construct, C/C++, predetermined, p.1]
1153 // Variables appearing in threadprivate directives are threadprivate.
1154 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1155 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1156 SemaRef.getLangOpts().OpenMPUseTLS &&
1157 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1158 (VD && VD->getStorageClass() == SC_Register &&
1159 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1160 DVar.RefExpr = buildDeclRefExpr(
1161 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1162 DVar.CKind = OMPC_threadprivate;
1163 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1164 return DVar;
1165 }
1166 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1167 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1168 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001169 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001170 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1171 [](const SharingMapTy &Data) {
1172 return isOpenMPTargetExecutionDirective(Data.Directive);
1173 });
1174 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001175 iterator ParentIterTarget = std::next(IterTarget, 1);
1176 for (iterator Iter = Stack.back().first.rbegin();
1177 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001178 if (isOpenMPLocal(VD, Iter)) {
1179 DVar.RefExpr =
1180 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1181 D->getLocation());
1182 DVar.CKind = OMPC_threadprivate;
1183 return DVar;
1184 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001185 }
1186 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1187 auto DSAIter = IterTarget->SharingMap.find(D);
1188 if (DSAIter != IterTarget->SharingMap.end() &&
1189 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1190 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1191 DVar.CKind = OMPC_threadprivate;
1192 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001193 }
1194 iterator End = Stack.back().first.rend();
1195 if (!SemaRef.isOpenMPCapturedByRef(
1196 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001197 DVar.RefExpr =
1198 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1199 IterTarget->ConstructLoc);
1200 DVar.CKind = OMPC_threadprivate;
1201 return DVar;
1202 }
1203 }
1204 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001205 }
1206
Alexey Bataev4b465392017-04-26 15:06:24 +00001207 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001208 // Not in OpenMP execution region and top scope was already checked.
1209 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001210
Alexey Bataev758e55e2013-09-06 18:03:48 +00001211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001212 // in a Construct, C/C++, predetermined, p.4]
1213 // Static data members are shared.
1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1215 // in a Construct, C/C++, predetermined, p.7]
1216 // Variables with static storage duration that are declared in a scope
1217 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001218 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001219 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001220 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001221 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001222 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001223
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001224 DVar.CKind = OMPC_shared;
1225 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001226 }
1227
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001228 // The predetermined shared attribute for const-qualified types having no
1229 // mutable members was removed after OpenMP 3.1.
1230 if (SemaRef.LangOpts.OpenMP <= 31) {
1231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1232 // in a Construct, C/C++, predetermined, p.6]
1233 // Variables with const qualified type having no mutable member are
1234 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001235 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001236 // Variables with const-qualified type having no mutable member may be
1237 // listed in a firstprivate clause, even if they are static data members.
1238 DSAVarData DVarTemp = hasInnermostDSA(
1239 D,
1240 [](OpenMPClauseKind C) {
1241 return C == OMPC_firstprivate || C == OMPC_shared;
1242 },
1243 MatchesAlways, FromParent);
1244 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1245 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001246
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001247 DVar.CKind = OMPC_shared;
1248 return DVar;
1249 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001250 }
1251
Alexey Bataev758e55e2013-09-06 18:03:48 +00001252 // Explicitly specified attributes and local variables with predetermined
1253 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001254 iterator I = Stack.back().first.rbegin();
1255 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001256 if (FromParent && I != EndI)
1257 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001258 auto It = I->SharingMap.find(D);
1259 if (It != I->SharingMap.end()) {
1260 const DSAInfo &Data = It->getSecond();
1261 DVar.RefExpr = Data.RefExpr.getPointer();
1262 DVar.PrivateCopy = Data.PrivateCopy;
1263 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001264 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001265 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001266 }
1267
1268 return DVar;
1269}
1270
Alexey Bataeve3727102018-04-18 15:57:46 +00001271const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1272 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001273 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001274 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001275 return getDSA(I, D);
1276 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001277 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001278 iterator StartI = Stack.back().first.rbegin();
1279 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001280 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001281 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001282 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001283}
1284
Alexey Bataeve3727102018-04-18 15:57:46 +00001285const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001286DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001287 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1288 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001289 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001290 if (isStackEmpty())
1291 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001292 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001293 iterator I = Stack.back().first.rbegin();
1294 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001295 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001296 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001297 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001298 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001299 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001300 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001301 DSAVarData DVar = getDSA(NewI, D);
1302 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001303 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001304 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001305 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001306}
1307
Alexey Bataeve3727102018-04-18 15:57:46 +00001308const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001309 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1310 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001311 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001312 if (isStackEmpty())
1313 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001314 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001315 iterator StartI = Stack.back().first.rbegin();
1316 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001317 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001318 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001319 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001320 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001321 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001322 DSAVarData DVar = getDSA(NewI, D);
1323 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001324}
1325
Alexey Bataevaac108a2015-06-23 04:51:00 +00001326bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001327 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1328 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001329 if (isStackEmpty())
1330 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001331 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001332 auto StartI = Stack.back().first.begin();
1333 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001334 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001335 return false;
1336 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001337 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001338 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001339 I->getSecond().RefExpr.getPointer() &&
1340 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001341 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1342 return true;
1343 // Check predetermined rules for the loop control variables.
1344 auto LI = StartI->LCVMap.find(D);
1345 if (LI != StartI->LCVMap.end())
1346 return CPred(OMPC_private);
1347 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001348}
1349
Samuel Antao4be30e92015-10-02 17:14:03 +00001350bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001351 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1352 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001353 if (isStackEmpty())
1354 return false;
1355 auto StartI = Stack.back().first.begin();
1356 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001357 if (std::distance(StartI, EndI) <= (int)Level)
1358 return false;
1359 std::advance(StartI, Level);
1360 return DPred(StartI->Directive);
1361}
1362
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001363bool DSAStackTy::hasDirective(
1364 const llvm::function_ref<bool(OpenMPDirectiveKind,
1365 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001366 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001367 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001368 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001369 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001370 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001371 auto StartI = std::next(Stack.back().first.rbegin());
1372 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001373 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001374 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001375 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1376 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1377 return true;
1378 }
1379 return false;
1380}
1381
Alexey Bataev758e55e2013-09-06 18:03:48 +00001382void Sema::InitDataSharingAttributesStack() {
1383 VarDataSharingAttributesStack = new DSAStackTy(*this);
1384}
1385
1386#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1387
Alexey Bataev4b465392017-04-26 15:06:24 +00001388void Sema::pushOpenMPFunctionRegion() {
1389 DSAStack->pushFunction();
1390}
1391
1392void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1393 DSAStack->popFunction(OldFSI);
1394}
1395
Alexey Bataevc416e642019-02-08 18:02:25 +00001396static bool isOpenMPDeviceDelayedContext(Sema &S) {
1397 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1398 "Expected OpenMP device compilation.");
1399 return !S.isInOpenMPTargetExecutionDirective() &&
1400 !S.isInOpenMPDeclareTargetContext();
1401}
1402
1403/// Do we know that we will eventually codegen the given function?
1404static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1405 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1406 "Expected OpenMP device compilation.");
1407 // Templates are emitted when they're instantiated.
1408 if (FD->isDependentContext())
1409 return false;
1410
1411 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1412 FD->getCanonicalDecl()))
1413 return true;
1414
1415 // Otherwise, the function is known-emitted if it's in our set of
1416 // known-emitted functions.
1417 return S.DeviceKnownEmittedFns.count(FD) > 0;
1418}
1419
1420Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1421 unsigned DiagID) {
1422 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1423 "Expected OpenMP device compilation.");
1424 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1425 !isKnownEmitted(*this, getCurFunctionDecl()))
1426 ? DeviceDiagBuilder::K_Deferred
1427 : DeviceDiagBuilder::K_Immediate,
1428 Loc, DiagID, getCurFunctionDecl(), *this);
1429}
1430
1431void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1432 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1433 "Expected OpenMP device compilation.");
1434 assert(Callee && "Callee may not be null.");
1435 FunctionDecl *Caller = getCurFunctionDecl();
1436
1437 // If the caller is known-emitted, mark the callee as known-emitted.
1438 // Otherwise, mark the call in our call graph so we can traverse it later.
1439 if (!isOpenMPDeviceDelayedContext(*this) ||
1440 (Caller && isKnownEmitted(*this, Caller)))
1441 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1442 else if (Caller)
1443 DeviceCallGraph[Caller].insert({Callee, Loc});
1444}
1445
Alexey Bataev123ad192019-02-27 20:29:45 +00001446void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1447 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1448 "OpenMP device compilation mode is expected.");
1449 QualType Ty = E->getType();
1450 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1451 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1452 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1453 !Context.getTargetInfo().hasInt128Type()))
1454 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1455 << Ty << E->getSourceRange();
1456}
1457
Alexey Bataeve3727102018-04-18 15:57:46 +00001458bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001459 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1460
Alexey Bataeve3727102018-04-18 15:57:46 +00001461 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001462 bool IsByRef = true;
1463
1464 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001465 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001466 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001467
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001468 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001469 // This table summarizes how a given variable should be passed to the device
1470 // given its type and the clauses where it appears. This table is based on
1471 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1472 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1473 //
1474 // =========================================================================
1475 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1476 // | |(tofrom:scalar)| | pvt | | | |
1477 // =========================================================================
1478 // | scl | | | | - | | bycopy|
1479 // | scl | | - | x | - | - | bycopy|
1480 // | scl | | x | - | - | - | null |
1481 // | scl | x | | | - | | byref |
1482 // | scl | x | - | x | - | - | bycopy|
1483 // | scl | x | x | - | - | - | null |
1484 // | scl | | - | - | - | x | byref |
1485 // | scl | x | - | - | - | x | byref |
1486 //
1487 // | agg | n.a. | | | - | | byref |
1488 // | agg | n.a. | - | x | - | - | byref |
1489 // | agg | n.a. | x | - | - | - | null |
1490 // | agg | n.a. | - | - | - | x | byref |
1491 // | agg | n.a. | - | - | - | x[] | byref |
1492 //
1493 // | ptr | n.a. | | | - | | bycopy|
1494 // | ptr | n.a. | - | x | - | - | bycopy|
1495 // | ptr | n.a. | x | - | - | - | null |
1496 // | ptr | n.a. | - | - | - | x | byref |
1497 // | ptr | n.a. | - | - | - | x[] | bycopy|
1498 // | ptr | n.a. | - | - | x | | bycopy|
1499 // | ptr | n.a. | - | - | x | x | bycopy|
1500 // | ptr | n.a. | - | - | x | x[] | bycopy|
1501 // =========================================================================
1502 // Legend:
1503 // scl - scalar
1504 // ptr - pointer
1505 // agg - aggregate
1506 // x - applies
1507 // - - invalid in this combination
1508 // [] - mapped with an array section
1509 // byref - should be mapped by reference
1510 // byval - should be mapped by value
1511 // null - initialize a local variable to null on the device
1512 //
1513 // Observations:
1514 // - All scalar declarations that show up in a map clause have to be passed
1515 // by reference, because they may have been mapped in the enclosing data
1516 // environment.
1517 // - If the scalar value does not fit the size of uintptr, it has to be
1518 // passed by reference, regardless the result in the table above.
1519 // - For pointers mapped by value that have either an implicit map or an
1520 // array section, the runtime library may pass the NULL value to the
1521 // device instead of the value passed to it by the compiler.
1522
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001523 if (Ty->isReferenceType())
1524 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001525
1526 // Locate map clauses and see if the variable being captured is referred to
1527 // in any of those clauses. Here we only care about variables, not fields,
1528 // because fields are part of aggregates.
1529 bool IsVariableUsedInMapClause = false;
1530 bool IsVariableAssociatedWithSection = false;
1531
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001532 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001533 D, Level,
1534 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1535 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001536 MapExprComponents,
1537 OpenMPClauseKind WhereFoundClauseKind) {
1538 // Only the map clause information influences how a variable is
1539 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001540 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001541 if (WhereFoundClauseKind != OMPC_map)
1542 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001543
1544 auto EI = MapExprComponents.rbegin();
1545 auto EE = MapExprComponents.rend();
1546
1547 assert(EI != EE && "Invalid map expression!");
1548
1549 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1550 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1551
1552 ++EI;
1553 if (EI == EE)
1554 return false;
1555
1556 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1557 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1558 isa<MemberExpr>(EI->getAssociatedExpression())) {
1559 IsVariableAssociatedWithSection = true;
1560 // There is nothing more we need to know about this variable.
1561 return true;
1562 }
1563
1564 // Keep looking for more map info.
1565 return false;
1566 });
1567
1568 if (IsVariableUsedInMapClause) {
1569 // If variable is identified in a map clause it is always captured by
1570 // reference except if it is a pointer that is dereferenced somehow.
1571 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1572 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001573 // By default, all the data that has a scalar type is mapped by copy
1574 // (except for reduction variables).
1575 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001576 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1577 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001578 !Ty->isScalarType() ||
1579 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1580 DSAStack->hasExplicitDSA(
1581 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001582 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001583 }
1584
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001585 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001586 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001587 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1588 !Ty->isAnyPointerType()) ||
1589 !DSAStack->hasExplicitDSA(
1590 D,
1591 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1592 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001593 // If the variable is artificial and must be captured by value - try to
1594 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001595 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1596 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001597 }
1598
Samuel Antao86ace552016-04-27 22:40:57 +00001599 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001600 // and alignment, because the runtime library only deals with uintptr types.
1601 // If it does not fit the uintptr size, we need to pass the data by reference
1602 // instead.
1603 if (!IsByRef &&
1604 (Ctx.getTypeSizeInChars(Ty) >
1605 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001606 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001607 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001608 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001609
1610 return IsByRef;
1611}
1612
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001613unsigned Sema::getOpenMPNestingLevel() const {
1614 assert(getLangOpts().OpenMP);
1615 return DSAStack->getNestingLevel();
1616}
1617
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001618bool Sema::isInOpenMPTargetExecutionDirective() const {
1619 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1620 !DSAStack->isClauseParsingMode()) ||
1621 DSAStack->hasDirective(
1622 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1623 SourceLocation) -> bool {
1624 return isOpenMPTargetExecutionDirective(K);
1625 },
1626 false);
1627}
1628
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001629VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001630 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001631 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001632
1633 // If we are attempting to capture a global variable in a directive with
1634 // 'target' we return true so that this global is also mapped to the device.
1635 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001636 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001637 if (VD && !VD->hasLocalStorage()) {
1638 if (isInOpenMPDeclareTargetContext() &&
1639 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1640 // Try to mark variable as declare target if it is used in capturing
1641 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001642 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001643 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001644 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001645 } else if (isInOpenMPTargetExecutionDirective()) {
1646 // If the declaration is enclosed in a 'declare target' directive,
1647 // then it should not be captured.
1648 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001649 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001650 return nullptr;
1651 return VD;
1652 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001653 }
Alexey Bataev60705422018-10-30 15:50:12 +00001654 // Capture variables captured by reference in lambdas for target-based
1655 // directives.
1656 if (VD && !DSAStack->isClauseParsingMode()) {
1657 if (const auto *RD = VD->getType()
1658 .getCanonicalType()
1659 .getNonReferenceType()
1660 ->getAsCXXRecordDecl()) {
1661 bool SavedForceCaptureByReferenceInTargetExecutable =
1662 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1663 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001664 if (RD->isLambda()) {
1665 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1666 FieldDecl *ThisCapture;
1667 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001668 for (const LambdaCapture &LC : RD->captures()) {
1669 if (LC.getCaptureKind() == LCK_ByRef) {
1670 VarDecl *VD = LC.getCapturedVar();
1671 DeclContext *VDC = VD->getDeclContext();
1672 if (!VDC->Encloses(CurContext))
1673 continue;
1674 DSAStackTy::DSAVarData DVarPrivate =
1675 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1676 // Do not capture already captured variables.
1677 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1678 DVarPrivate.CKind == OMPC_unknown &&
1679 !DSAStack->checkMappableExprComponentListsForDecl(
1680 D, /*CurrentRegionOnly=*/true,
1681 [](OMPClauseMappableExprCommon::
1682 MappableExprComponentListRef,
1683 OpenMPClauseKind) { return true; }))
1684 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1685 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001686 QualType ThisTy = getCurrentThisType();
1687 if (!ThisTy.isNull() &&
1688 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1689 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001690 }
1691 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001692 }
Alexey Bataev60705422018-10-30 15:50:12 +00001693 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1694 SavedForceCaptureByReferenceInTargetExecutable);
1695 }
1696 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001697
Alexey Bataev48977c32015-08-04 08:10:48 +00001698 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1699 (!DSAStack->isClauseParsingMode() ||
1700 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001701 auto &&Info = DSAStack->isLoopControlVariable(D);
1702 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001703 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001704 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001705 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001706 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001707 DSAStackTy::DSAVarData DVarPrivate =
1708 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001709 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001710 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001711 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1712 [](OpenMPDirectiveKind) { return true; },
1713 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001714 if (DVarPrivate.CKind != OMPC_unknown)
1715 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001716 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001717 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001718}
1719
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001720void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1721 unsigned Level) const {
1722 SmallVector<OpenMPDirectiveKind, 4> Regions;
1723 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1724 FunctionScopesIndex -= Regions.size();
1725}
1726
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001727void Sema::startOpenMPLoop() {
1728 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1729 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1730 DSAStack->loopInit();
1731}
1732
Alexey Bataeve3727102018-04-18 15:57:46 +00001733bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001734 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001735 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1736 if (DSAStack->getAssociatedLoops() > 0 &&
1737 !DSAStack->isLoopStarted()) {
1738 DSAStack->resetPossibleLoopCounter(D);
1739 DSAStack->loopStart();
1740 return true;
1741 }
1742 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1743 DSAStack->isLoopControlVariable(D).first) &&
1744 !DSAStack->hasExplicitDSA(
1745 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1746 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1747 return true;
1748 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001749 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001750 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001751 (DSAStack->isClauseParsingMode() &&
1752 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001753 // Consider taskgroup reduction descriptor variable a private to avoid
1754 // possible capture in the region.
1755 (DSAStack->hasExplicitDirective(
1756 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1757 Level) &&
1758 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001759}
1760
Alexey Bataeve3727102018-04-18 15:57:46 +00001761void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1762 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001763 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1764 D = getCanonicalDecl(D);
1765 OpenMPClauseKind OMPC = OMPC_unknown;
1766 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1767 const unsigned NewLevel = I - 1;
1768 if (DSAStack->hasExplicitDSA(D,
1769 [&OMPC](const OpenMPClauseKind K) {
1770 if (isOpenMPPrivate(K)) {
1771 OMPC = K;
1772 return true;
1773 }
1774 return false;
1775 },
1776 NewLevel))
1777 break;
1778 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1779 D, NewLevel,
1780 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1781 OpenMPClauseKind) { return true; })) {
1782 OMPC = OMPC_map;
1783 break;
1784 }
1785 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1786 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001787 OMPC = OMPC_map;
1788 if (D->getType()->isScalarType() &&
1789 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1790 DefaultMapAttributes::DMA_tofrom_scalar)
1791 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001792 break;
1793 }
1794 }
1795 if (OMPC != OMPC_unknown)
1796 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1797}
1798
Alexey Bataeve3727102018-04-18 15:57:46 +00001799bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1800 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001801 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1802 // Return true if the current level is no longer enclosed in a target region.
1803
Alexey Bataeve3727102018-04-18 15:57:46 +00001804 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001805 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001806 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1807 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001808}
1809
Alexey Bataeved09d242014-05-28 05:53:51 +00001810void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001811
1812void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1813 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001814 Scope *CurScope, SourceLocation Loc) {
1815 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001816 PushExpressionEvaluationContext(
1817 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001818}
1819
Alexey Bataevaac108a2015-06-23 04:51:00 +00001820void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1821 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001822}
1823
Alexey Bataevaac108a2015-06-23 04:51:00 +00001824void Sema::EndOpenMPClause() {
1825 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001826}
1827
Alexey Bataev758e55e2013-09-06 18:03:48 +00001828void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001829 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1830 // A variable of class type (or array thereof) that appears in a lastprivate
1831 // clause requires an accessible, unambiguous default constructor for the
1832 // class type, unless the list item is also specified in a firstprivate
1833 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001834 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1835 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001836 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1837 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001838 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001839 if (DE->isValueDependent() || DE->isTypeDependent()) {
1840 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001841 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001842 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001843 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001844 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001845 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001846 const DSAStackTy::DSAVarData DVar =
1847 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001848 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001849 // Generate helper private variable and initialize it with the
1850 // default value. The address of the original variable is replaced
1851 // by the address of the new private variable in CodeGen. This new
1852 // variable is not added to IdResolver, so the code in the OpenMP
1853 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001854 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001855 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001856 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001857 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001858 if (VDPrivate->isInvalidDecl())
1859 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001860 PrivateCopies.push_back(buildDeclRefExpr(
1861 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001862 } else {
1863 // The variable is also a firstprivate, so initialization sequence
1864 // for private copy is generated already.
1865 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001866 }
1867 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001868 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001869 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001870 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001871 }
1872 }
1873 }
1874
Alexey Bataev758e55e2013-09-06 18:03:48 +00001875 DSAStack->pop();
1876 DiscardCleanupsInEvaluationContext();
1877 PopExpressionEvaluationContext();
1878}
1879
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001880static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1881 Expr *NumIterations, Sema &SemaRef,
1882 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001883
Alexey Bataeva769e072013-03-22 06:34:35 +00001884namespace {
1885
Alexey Bataeve3727102018-04-18 15:57:46 +00001886class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001887private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001888 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001889
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001890public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001891 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001892 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001893 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001894 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001895 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001896 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1897 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001898 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001899 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001900 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001901};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001902
Alexey Bataeve3727102018-04-18 15:57:46 +00001903class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001904private:
1905 Sema &SemaRef;
1906
1907public:
1908 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1909 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1910 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001911 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001912 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1913 SemaRef.getCurScope());
1914 }
1915 return false;
1916 }
1917};
1918
Alexey Bataeved09d242014-05-28 05:53:51 +00001919} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001920
1921ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1922 CXXScopeSpec &ScopeSpec,
1923 const DeclarationNameInfo &Id) {
1924 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1925 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1926
1927 if (Lookup.isAmbiguous())
1928 return ExprError();
1929
1930 VarDecl *VD;
1931 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001932 if (TypoCorrection Corrected = CorrectTypo(
1933 Id, LookupOrdinaryName, CurScope, nullptr,
1934 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001935 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001936 PDiag(Lookup.empty()
1937 ? diag::err_undeclared_var_use_suggest
1938 : diag::err_omp_expected_var_arg_suggest)
1939 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001940 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001941 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001942 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1943 : diag::err_omp_expected_var_arg)
1944 << Id.getName();
1945 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001946 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001947 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1948 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1949 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1950 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001951 }
1952 Lookup.suppressDiagnostics();
1953
1954 // OpenMP [2.9.2, Syntax, C/C++]
1955 // Variables must be file-scope, namespace-scope, or static block-scope.
1956 if (!VD->hasGlobalStorage()) {
1957 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001958 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1959 bool IsDecl =
1960 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001961 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001962 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1963 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001964 return ExprError();
1965 }
1966
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001967 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001968 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001969 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1970 // A threadprivate directive for file-scope variables must appear outside
1971 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001972 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1973 !getCurLexicalContext()->isTranslationUnit()) {
1974 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001975 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1976 bool IsDecl =
1977 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1978 Diag(VD->getLocation(),
1979 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1980 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001981 return ExprError();
1982 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001983 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1984 // A threadprivate directive for static class member variables must appear
1985 // in the class definition, in the same scope in which the member
1986 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001987 if (CanonicalVD->isStaticDataMember() &&
1988 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1989 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001990 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1991 bool IsDecl =
1992 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1993 Diag(VD->getLocation(),
1994 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1995 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001996 return ExprError();
1997 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001998 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1999 // A threadprivate directive for namespace-scope variables must appear
2000 // outside any definition or declaration other than the namespace
2001 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002002 if (CanonicalVD->getDeclContext()->isNamespace() &&
2003 (!getCurLexicalContext()->isFileContext() ||
2004 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2005 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00002006 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
2007 bool IsDecl =
2008 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2009 Diag(VD->getLocation(),
2010 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2011 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002012 return ExprError();
2013 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002014 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2015 // A threadprivate directive for static block-scope variables must appear
2016 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002017 if (CanonicalVD->isStaticLocal() && CurScope &&
2018 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002019 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00002020 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
2021 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 Bataev6f6f3b42013-05-13 04:18:18 +00002026 return ExprError();
2027 }
2028
2029 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2030 // A threadprivate directive must lexically precede all references to any
2031 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00002032 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002033 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00002034 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002035 return ExprError();
2036 }
2037
2038 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002039 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2040 SourceLocation(), VD,
2041 /*RefersToEnclosingVariableOrCapture=*/false,
2042 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002043}
2044
Alexey Bataeved09d242014-05-28 05:53:51 +00002045Sema::DeclGroupPtrTy
2046Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2047 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002048 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002049 CurContext->addDecl(D);
2050 return DeclGroupPtrTy::make(DeclGroupRef(D));
2051 }
David Blaikie0403cb12016-01-15 23:43:25 +00002052 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002053}
2054
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002055namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002056class LocalVarRefChecker final
2057 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002058 Sema &SemaRef;
2059
2060public:
2061 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002062 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002063 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002064 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002065 diag::err_omp_local_var_in_threadprivate_init)
2066 << E->getSourceRange();
2067 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2068 << VD << VD->getSourceRange();
2069 return true;
2070 }
2071 }
2072 return false;
2073 }
2074 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002075 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002076 if (Child && Visit(Child))
2077 return true;
2078 }
2079 return false;
2080 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002081 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002082};
2083} // namespace
2084
Alexey Bataeved09d242014-05-28 05:53:51 +00002085OMPThreadPrivateDecl *
2086Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002087 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002088 for (Expr *RefExpr : VarList) {
2089 auto *DE = cast<DeclRefExpr>(RefExpr);
2090 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002091 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002092
Alexey Bataev376b4a42016-02-09 09:41:09 +00002093 // Mark variable as used.
2094 VD->setReferenced();
2095 VD->markUsed(Context);
2096
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002097 QualType QType = VD->getType();
2098 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2099 // It will be analyzed later.
2100 Vars.push_back(DE);
2101 continue;
2102 }
2103
Alexey Bataeva769e072013-03-22 06:34:35 +00002104 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2105 // A threadprivate variable must not have an incomplete type.
2106 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002107 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002108 continue;
2109 }
2110
2111 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2112 // A threadprivate variable must not have a reference type.
2113 if (VD->getType()->isReferenceType()) {
2114 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002115 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2116 bool IsDecl =
2117 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2118 Diag(VD->getLocation(),
2119 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2120 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002121 continue;
2122 }
2123
Samuel Antaof8b50122015-07-13 22:54:53 +00002124 // Check if this is a TLS variable. If TLS is not being supported, produce
2125 // the corresponding diagnostic.
2126 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2127 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2128 getLangOpts().OpenMPUseTLS &&
2129 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002130 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2131 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002132 Diag(ILoc, diag::err_omp_var_thread_local)
2133 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002134 bool IsDecl =
2135 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2136 Diag(VD->getLocation(),
2137 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2138 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002139 continue;
2140 }
2141
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002142 // Check if initial value of threadprivate variable reference variable with
2143 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002144 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002145 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002146 if (Checker.Visit(Init))
2147 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002148 }
2149
Alexey Bataeved09d242014-05-28 05:53:51 +00002150 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002151 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002152 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2153 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002154 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002155 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002156 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002157 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002158 if (!Vars.empty()) {
2159 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2160 Vars);
2161 D->setAccess(AS_public);
2162 }
2163 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002164}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002165
Kelvin Li1408f912018-09-26 04:28:39 +00002166Sema::DeclGroupPtrTy
2167Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2168 ArrayRef<OMPClause *> ClauseList) {
2169 OMPRequiresDecl *D = nullptr;
2170 if (!CurContext->isFileContext()) {
2171 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2172 } else {
2173 D = CheckOMPRequiresDecl(Loc, ClauseList);
2174 if (D) {
2175 CurContext->addDecl(D);
2176 DSAStack->addRequiresDecl(D);
2177 }
2178 }
2179 return DeclGroupPtrTy::make(DeclGroupRef(D));
2180}
2181
2182OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2183 ArrayRef<OMPClause *> ClauseList) {
2184 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2185 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2186 ClauseList);
2187 return nullptr;
2188}
2189
Alexey Bataeve3727102018-04-18 15:57:46 +00002190static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2191 const ValueDecl *D,
2192 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002193 bool IsLoopIterVar = false) {
2194 if (DVar.RefExpr) {
2195 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2196 << getOpenMPClauseName(DVar.CKind);
2197 return;
2198 }
2199 enum {
2200 PDSA_StaticMemberShared,
2201 PDSA_StaticLocalVarShared,
2202 PDSA_LoopIterVarPrivate,
2203 PDSA_LoopIterVarLinear,
2204 PDSA_LoopIterVarLastprivate,
2205 PDSA_ConstVarShared,
2206 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002207 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002208 PDSA_LocalVarPrivate,
2209 PDSA_Implicit
2210 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002211 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002212 auto ReportLoc = D->getLocation();
2213 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002214 if (IsLoopIterVar) {
2215 if (DVar.CKind == OMPC_private)
2216 Reason = PDSA_LoopIterVarPrivate;
2217 else if (DVar.CKind == OMPC_lastprivate)
2218 Reason = PDSA_LoopIterVarLastprivate;
2219 else
2220 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002221 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2222 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002223 Reason = PDSA_TaskVarFirstprivate;
2224 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002225 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002226 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002227 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002228 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002229 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002230 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002231 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002232 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002233 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002234 ReportHint = true;
2235 Reason = PDSA_LocalVarPrivate;
2236 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002237 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002238 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002239 << Reason << ReportHint
2240 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2241 } else if (DVar.ImplicitDSALoc.isValid()) {
2242 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2243 << getOpenMPClauseName(DVar.CKind);
2244 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002245}
2246
Alexey Bataev758e55e2013-09-06 18:03:48 +00002247namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002248class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002249 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002250 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002251 bool ErrorFound = false;
2252 CapturedStmt *CS = nullptr;
2253 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2254 llvm::SmallVector<Expr *, 4> ImplicitMap;
2255 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2256 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002257
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002258 void VisitSubCaptures(OMPExecutableDirective *S) {
2259 // Check implicitly captured variables.
2260 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2261 return;
2262 for (const CapturedStmt::Capture &Cap :
2263 S->getInnermostCapturedStmt()->captures()) {
2264 if (!Cap.capturesVariable())
2265 continue;
2266 VarDecl *VD = Cap.getCapturedVar();
2267 // Do not try to map the variable if it or its sub-component was mapped
2268 // already.
2269 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2270 Stack->checkMappableExprComponentListsForDecl(
2271 VD, /*CurrentRegionOnly=*/true,
2272 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2273 OpenMPClauseKind) { return true; }))
2274 continue;
2275 DeclRefExpr *DRE = buildDeclRefExpr(
2276 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2277 Cap.getLocation(), /*RefersToCapture=*/true);
2278 Visit(DRE);
2279 }
2280 }
2281
Alexey Bataev758e55e2013-09-06 18:03:48 +00002282public:
2283 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002284 if (E->isTypeDependent() || E->isValueDependent() ||
2285 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2286 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002287 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002288 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002289 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002290 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002291 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002292
Alexey Bataeve3727102018-04-18 15:57:46 +00002293 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002294 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002295 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002296 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002297
Alexey Bataevafe50572017-10-06 17:00:28 +00002298 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002299 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002300 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002301 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2302 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002303 return;
2304
Alexey Bataeve3727102018-04-18 15:57:46 +00002305 SourceLocation ELoc = E->getExprLoc();
2306 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002307 // The default(none) clause requires that each variable that is referenced
2308 // in the construct, and does not have a predetermined data-sharing
2309 // attribute, must have its data-sharing attribute explicitly determined
2310 // by being listed in a data-sharing attribute clause.
2311 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002312 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002313 VarsWithInheritedDSA.count(VD) == 0) {
2314 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002315 return;
2316 }
2317
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002318 if (isOpenMPTargetExecutionDirective(DKind) &&
2319 !Stack->isLoopControlVariable(VD).first) {
2320 if (!Stack->checkMappableExprComponentListsForDecl(
2321 VD, /*CurrentRegionOnly=*/true,
2322 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2323 StackComponents,
2324 OpenMPClauseKind) {
2325 // Variable is used if it has been marked as an array, array
2326 // section or the variable iself.
2327 return StackComponents.size() == 1 ||
2328 std::all_of(
2329 std::next(StackComponents.rbegin()),
2330 StackComponents.rend(),
2331 [](const OMPClauseMappableExprCommon::
2332 MappableComponent &MC) {
2333 return MC.getAssociatedDeclaration() ==
2334 nullptr &&
2335 (isa<OMPArraySectionExpr>(
2336 MC.getAssociatedExpression()) ||
2337 isa<ArraySubscriptExpr>(
2338 MC.getAssociatedExpression()));
2339 });
2340 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002341 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002342 // By default lambdas are captured as firstprivates.
2343 if (const auto *RD =
2344 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002345 IsFirstprivate = RD->isLambda();
2346 IsFirstprivate =
2347 IsFirstprivate ||
2348 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002349 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002350 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002351 ImplicitFirstprivate.emplace_back(E);
2352 else
2353 ImplicitMap.emplace_back(E);
2354 return;
2355 }
2356 }
2357
Alexey Bataev758e55e2013-09-06 18:03:48 +00002358 // OpenMP [2.9.3.6, Restrictions, p.2]
2359 // A list item that appears in a reduction clause of the innermost
2360 // enclosing worksharing or parallel construct may not be accessed in an
2361 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002362 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002363 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2364 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002365 return isOpenMPParallelDirective(K) ||
2366 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2367 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002368 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002369 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002370 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002371 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002372 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002373 return;
2374 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002375
2376 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002377 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002378 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2379 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002380 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002381 }
2382 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002383 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002384 if (E->isTypeDependent() || E->isValueDependent() ||
2385 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2386 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002387 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002388 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002389 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002390 if (!FD)
2391 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002392 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002393 // Check if the variable has explicit DSA set and stop analysis if it
2394 // so.
2395 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2396 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002397
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002398 if (isOpenMPTargetExecutionDirective(DKind) &&
2399 !Stack->isLoopControlVariable(FD).first &&
2400 !Stack->checkMappableExprComponentListsForDecl(
2401 FD, /*CurrentRegionOnly=*/true,
2402 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2403 StackComponents,
2404 OpenMPClauseKind) {
2405 return isa<CXXThisExpr>(
2406 cast<MemberExpr>(
2407 StackComponents.back().getAssociatedExpression())
2408 ->getBase()
2409 ->IgnoreParens());
2410 })) {
2411 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2412 // A bit-field cannot appear in a map clause.
2413 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002414 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002415 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002416
2417 // Check to see if the member expression is referencing a class that
2418 // has already been explicitly mapped
2419 if (Stack->isClassPreviouslyMapped(TE->getType()))
2420 return;
2421
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002422 ImplicitMap.emplace_back(E);
2423 return;
2424 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002425
Alexey Bataeve3727102018-04-18 15:57:46 +00002426 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002427 // OpenMP [2.9.3.6, Restrictions, p.2]
2428 // A list item that appears in a reduction clause of the innermost
2429 // enclosing worksharing or parallel construct may not be accessed in
2430 // an explicit task.
2431 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002432 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2433 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002434 return isOpenMPParallelDirective(K) ||
2435 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2436 },
2437 /*FromParent=*/true);
2438 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2439 ErrorFound = true;
2440 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002441 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002442 return;
2443 }
2444
2445 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002446 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002447 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002448 !Stack->isLoopControlVariable(FD).first) {
2449 // Check if there is a captured expression for the current field in the
2450 // region. Do not mark it as firstprivate unless there is no captured
2451 // expression.
2452 // TODO: try to make it firstprivate.
2453 if (DVar.CKind != OMPC_unknown)
2454 ImplicitFirstprivate.push_back(E);
2455 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002456 return;
2457 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002458 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002459 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002460 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002461 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002462 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002463 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002464 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2465 if (!Stack->checkMappableExprComponentListsForDecl(
2466 VD, /*CurrentRegionOnly=*/true,
2467 [&CurComponents](
2468 OMPClauseMappableExprCommon::MappableExprComponentListRef
2469 StackComponents,
2470 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002471 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002472 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002473 for (const auto &SC : llvm::reverse(StackComponents)) {
2474 // Do both expressions have the same kind?
2475 if (CCI->getAssociatedExpression()->getStmtClass() !=
2476 SC.getAssociatedExpression()->getStmtClass())
2477 if (!(isa<OMPArraySectionExpr>(
2478 SC.getAssociatedExpression()) &&
2479 isa<ArraySubscriptExpr>(
2480 CCI->getAssociatedExpression())))
2481 return false;
2482
Alexey Bataeve3727102018-04-18 15:57:46 +00002483 const Decl *CCD = CCI->getAssociatedDeclaration();
2484 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002485 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2486 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2487 if (SCD != CCD)
2488 return false;
2489 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002490 if (CCI == CCE)
2491 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002492 }
2493 return true;
2494 })) {
2495 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002496 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002497 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002498 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002499 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002500 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002501 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002502 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002503 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002504 // for task|target directives.
2505 // Skip analysis of arguments of implicitly defined map clause for target
2506 // directives.
2507 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2508 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002509 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002510 if (CC)
2511 Visit(CC);
2512 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002513 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002514 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002515 // Check implicitly captured variables.
2516 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002517 }
2518 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002519 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002520 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002521 // Check implicitly captured variables in the task-based directives to
2522 // check if they must be firstprivatized.
2523 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002524 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002525 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002526 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002527
Alexey Bataeve3727102018-04-18 15:57:46 +00002528 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002529 ArrayRef<Expr *> getImplicitFirstprivate() const {
2530 return ImplicitFirstprivate;
2531 }
2532 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002533 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002534 return VarsWithInheritedDSA;
2535 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002536
Alexey Bataev7ff55242014-06-19 09:13:45 +00002537 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2538 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002539};
Alexey Bataeved09d242014-05-28 05:53:51 +00002540} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002541
Alexey Bataevbae9a792014-06-27 10:37:06 +00002542void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002543 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002544 case OMPD_parallel:
2545 case OMPD_parallel_for:
2546 case OMPD_parallel_for_simd:
2547 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002548 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002549 case OMPD_teams_distribute:
2550 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002551 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002552 QualType KmpInt32PtrTy =
2553 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002554 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002555 std::make_pair(".global_tid.", KmpInt32PtrTy),
2556 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2557 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002558 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002559 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2560 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002561 break;
2562 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002563 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002564 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002565 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002566 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002567 case OMPD_target_teams_distribute:
2568 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002569 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2570 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2571 QualType KmpInt32PtrTy =
2572 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2573 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002574 FunctionProtoType::ExtProtoInfo EPI;
2575 EPI.Variadic = true;
2576 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2577 Sema::CapturedParamNameType Params[] = {
2578 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002579 std::make_pair(".part_id.", KmpInt32PtrTy),
2580 std::make_pair(".privates.", VoidPtrTy),
2581 std::make_pair(
2582 ".copy_fn.",
2583 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002584 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2585 std::make_pair(StringRef(), QualType()) // __context with shared vars
2586 };
2587 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2588 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002589 // Mark this captured region as inlined, because we don't use outlined
2590 // function directly.
2591 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2592 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002593 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002594 Sema::CapturedParamNameType ParamsTarget[] = {
2595 std::make_pair(StringRef(), QualType()) // __context with shared vars
2596 };
2597 // Start a captured region for 'target' with no implicit parameters.
2598 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2599 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002600 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002601 std::make_pair(".global_tid.", KmpInt32PtrTy),
2602 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2603 std::make_pair(StringRef(), QualType()) // __context with shared vars
2604 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002605 // Start a captured region for 'teams' or 'parallel'. Both regions have
2606 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002608 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002609 break;
2610 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002611 case OMPD_target:
2612 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002613 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2614 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2615 QualType KmpInt32PtrTy =
2616 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2617 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002618 FunctionProtoType::ExtProtoInfo EPI;
2619 EPI.Variadic = true;
2620 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2621 Sema::CapturedParamNameType Params[] = {
2622 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002623 std::make_pair(".part_id.", KmpInt32PtrTy),
2624 std::make_pair(".privates.", VoidPtrTy),
2625 std::make_pair(
2626 ".copy_fn.",
2627 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002628 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2629 std::make_pair(StringRef(), QualType()) // __context with shared vars
2630 };
2631 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2632 Params);
2633 // Mark this captured region as inlined, because we don't use outlined
2634 // function directly.
2635 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2636 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002637 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002638 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2639 std::make_pair(StringRef(), QualType()));
2640 break;
2641 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002642 case OMPD_simd:
2643 case OMPD_for:
2644 case OMPD_for_simd:
2645 case OMPD_sections:
2646 case OMPD_section:
2647 case OMPD_single:
2648 case OMPD_master:
2649 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002650 case OMPD_taskgroup:
2651 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002652 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002653 case OMPD_ordered:
2654 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002655 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002656 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002657 std::make_pair(StringRef(), QualType()) // __context with shared vars
2658 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002659 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2660 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002661 break;
2662 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002663 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002664 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2665 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2666 QualType KmpInt32PtrTy =
2667 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2668 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002669 FunctionProtoType::ExtProtoInfo EPI;
2670 EPI.Variadic = true;
2671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002672 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002673 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002674 std::make_pair(".part_id.", KmpInt32PtrTy),
2675 std::make_pair(".privates.", VoidPtrTy),
2676 std::make_pair(
2677 ".copy_fn.",
2678 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002679 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002680 std::make_pair(StringRef(), QualType()) // __context with shared vars
2681 };
2682 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2683 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002684 // Mark this captured region as inlined, because we don't use outlined
2685 // function directly.
2686 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2687 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002688 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002689 break;
2690 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002691 case OMPD_taskloop:
2692 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002693 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002694 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2695 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002696 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002697 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2698 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002699 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002700 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2701 .withConst();
2702 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2703 QualType KmpInt32PtrTy =
2704 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2705 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002706 FunctionProtoType::ExtProtoInfo EPI;
2707 EPI.Variadic = true;
2708 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002709 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002710 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002711 std::make_pair(".part_id.", KmpInt32PtrTy),
2712 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002713 std::make_pair(
2714 ".copy_fn.",
2715 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2716 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2717 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002718 std::make_pair(".ub.", KmpUInt64Ty),
2719 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002720 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002721 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002722 std::make_pair(StringRef(), QualType()) // __context with shared vars
2723 };
2724 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2725 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002726 // Mark this captured region as inlined, because we don't use outlined
2727 // function directly.
2728 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2729 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002730 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002731 break;
2732 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002733 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002734 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002735 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002736 QualType KmpInt32PtrTy =
2737 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2738 Sema::CapturedParamNameType Params[] = {
2739 std::make_pair(".global_tid.", KmpInt32PtrTy),
2740 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002741 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2742 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002743 std::make_pair(StringRef(), QualType()) // __context with shared vars
2744 };
2745 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2746 Params);
2747 break;
2748 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002749 case OMPD_target_teams_distribute_parallel_for:
2750 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002751 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002752 QualType KmpInt32PtrTy =
2753 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002754 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002755
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002756 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002757 FunctionProtoType::ExtProtoInfo EPI;
2758 EPI.Variadic = true;
2759 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2760 Sema::CapturedParamNameType Params[] = {
2761 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002762 std::make_pair(".part_id.", KmpInt32PtrTy),
2763 std::make_pair(".privates.", VoidPtrTy),
2764 std::make_pair(
2765 ".copy_fn.",
2766 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002767 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2768 std::make_pair(StringRef(), QualType()) // __context with shared vars
2769 };
2770 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2771 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002772 // Mark this captured region as inlined, because we don't use outlined
2773 // function directly.
2774 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2775 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002776 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002777 Sema::CapturedParamNameType ParamsTarget[] = {
2778 std::make_pair(StringRef(), QualType()) // __context with shared vars
2779 };
2780 // Start a captured region for 'target' with no implicit parameters.
2781 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2782 ParamsTarget);
2783
2784 Sema::CapturedParamNameType ParamsTeams[] = {
2785 std::make_pair(".global_tid.", KmpInt32PtrTy),
2786 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2787 std::make_pair(StringRef(), QualType()) // __context with shared vars
2788 };
2789 // Start a captured region for 'target' with no implicit parameters.
2790 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2791 ParamsTeams);
2792
2793 Sema::CapturedParamNameType ParamsParallel[] = {
2794 std::make_pair(".global_tid.", KmpInt32PtrTy),
2795 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002796 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2797 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002798 std::make_pair(StringRef(), QualType()) // __context with shared vars
2799 };
2800 // Start a captured region for 'teams' or 'parallel'. Both regions have
2801 // the same implicit parameters.
2802 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2803 ParamsParallel);
2804 break;
2805 }
2806
Alexey Bataev46506272017-12-05 17:41:34 +00002807 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002808 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002809 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002810 QualType KmpInt32PtrTy =
2811 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2812
2813 Sema::CapturedParamNameType ParamsTeams[] = {
2814 std::make_pair(".global_tid.", KmpInt32PtrTy),
2815 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2816 std::make_pair(StringRef(), QualType()) // __context with shared vars
2817 };
2818 // Start a captured region for 'target' with no implicit parameters.
2819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2820 ParamsTeams);
2821
2822 Sema::CapturedParamNameType ParamsParallel[] = {
2823 std::make_pair(".global_tid.", KmpInt32PtrTy),
2824 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002825 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2826 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00002827 std::make_pair(StringRef(), QualType()) // __context with shared vars
2828 };
2829 // Start a captured region for 'teams' or 'parallel'. Both regions have
2830 // the same implicit parameters.
2831 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2832 ParamsParallel);
2833 break;
2834 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002835 case OMPD_target_update:
2836 case OMPD_target_enter_data:
2837 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002838 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2839 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2840 QualType KmpInt32PtrTy =
2841 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2842 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00002843 FunctionProtoType::ExtProtoInfo EPI;
2844 EPI.Variadic = true;
2845 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2846 Sema::CapturedParamNameType Params[] = {
2847 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002848 std::make_pair(".part_id.", KmpInt32PtrTy),
2849 std::make_pair(".privates.", VoidPtrTy),
2850 std::make_pair(
2851 ".copy_fn.",
2852 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00002853 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2854 std::make_pair(StringRef(), QualType()) // __context with shared vars
2855 };
2856 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2857 Params);
2858 // Mark this captured region as inlined, because we don't use outlined
2859 // function directly.
2860 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2861 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002862 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00002863 break;
2864 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002865 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002866 case OMPD_taskyield:
2867 case OMPD_barrier:
2868 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002869 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002870 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002871 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002872 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00002873 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002874 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002875 case OMPD_declare_target:
2876 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00002877 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00002878 llvm_unreachable("OpenMP Directive is not allowed");
2879 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002880 llvm_unreachable("Unknown OpenMP directive");
2881 }
2882}
2883
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002884int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2885 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2886 getOpenMPCaptureRegions(CaptureRegions, DKind);
2887 return CaptureRegions.size();
2888}
2889
Alexey Bataev3392d762016-02-16 11:18:12 +00002890static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002891 Expr *CaptureExpr, bool WithInit,
2892 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002893 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002894 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002895 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002896 QualType Ty = Init->getType();
2897 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002898 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002899 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002900 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002901 Ty = C.getPointerType(Ty);
2902 ExprResult Res =
2903 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2904 if (!Res.isUsable())
2905 return nullptr;
2906 Init = Res.get();
2907 }
Alexey Bataev61205072016-03-02 04:57:40 +00002908 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002909 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002910 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002911 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002912 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00002913 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00002914 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002915 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002916 return CED;
2917}
2918
Alexey Bataev61205072016-03-02 04:57:40 +00002919static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2920 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002921 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00002922 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002923 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00002924 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002925 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2926 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002927 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002928 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002929}
2930
Alexey Bataev5a3af132016-03-29 08:58:54 +00002931static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002932 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002933 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002934 OMPCapturedExprDecl *CD = buildCaptureDecl(
2935 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2936 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002937 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2938 CaptureExpr->getExprLoc());
2939 }
2940 ExprResult Res = Ref;
2941 if (!S.getLangOpts().CPlusPlus &&
2942 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002943 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002944 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002945 if (!Res.isUsable())
2946 return ExprError();
2947 }
2948 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002949}
2950
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002951namespace {
2952// OpenMP directives parsed in this section are represented as a
2953// CapturedStatement with an associated statement. If a syntax error
2954// is detected during the parsing of the associated statement, the
2955// compiler must abort processing and close the CapturedStatement.
2956//
2957// Combined directives such as 'target parallel' have more than one
2958// nested CapturedStatements. This RAII ensures that we unwind out
2959// of all the nested CapturedStatements when an error is found.
2960class CaptureRegionUnwinderRAII {
2961private:
2962 Sema &S;
2963 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00002964 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002965
2966public:
2967 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2968 OpenMPDirectiveKind DKind)
2969 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2970 ~CaptureRegionUnwinderRAII() {
2971 if (ErrorFound) {
2972 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2973 while (--ThisCaptureLevel >= 0)
2974 S.ActOnCapturedRegionError();
2975 }
2976 }
2977};
2978} // namespace
2979
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002980StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2981 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002982 bool ErrorFound = false;
2983 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2984 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002985 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002986 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002987 return StmtError();
2988 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002989
Alexey Bataev2ba67042017-11-28 21:11:44 +00002990 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2991 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002992 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002993 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00002994 SmallVector<const OMPLinearClause *, 4> LCs;
2995 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002996 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00002997 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002998 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2999 Clause->getClauseKind() == OMPC_in_reduction) {
3000 // Capture taskgroup task_reduction descriptors inside the tasking regions
3001 // with the corresponding in_reduction items.
3002 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003003 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003004 if (E)
3005 MarkDeclarationsReferencedInExpr(E);
3006 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003007 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003008 Clause->getClauseKind() == OMPC_copyprivate ||
3009 (getLangOpts().OpenMPUseTLS &&
3010 getASTContext().getTargetInfo().isTLSSupported() &&
3011 Clause->getClauseKind() == OMPC_copyin)) {
3012 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003013 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003014 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003015 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003016 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003017 }
3018 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003019 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003020 } else if (CaptureRegions.size() > 1 ||
3021 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003022 if (auto *C = OMPClauseWithPreInit::get(Clause))
3023 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003024 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003025 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003026 MarkDeclarationsReferencedInExpr(E);
3027 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003028 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003029 if (Clause->getClauseKind() == OMPC_schedule)
3030 SC = cast<OMPScheduleClause>(Clause);
3031 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003032 OC = cast<OMPOrderedClause>(Clause);
3033 else if (Clause->getClauseKind() == OMPC_linear)
3034 LCs.push_back(cast<OMPLinearClause>(Clause));
3035 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003036 // OpenMP, 2.7.1 Loop Construct, Restrictions
3037 // The nonmonotonic modifier cannot be specified if an ordered clause is
3038 // specified.
3039 if (SC &&
3040 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3041 SC->getSecondScheduleModifier() ==
3042 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3043 OC) {
3044 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3045 ? SC->getFirstScheduleModifierLoc()
3046 : SC->getSecondScheduleModifierLoc(),
3047 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003048 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003049 ErrorFound = true;
3050 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003051 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003052 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003053 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003054 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003055 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003056 ErrorFound = true;
3057 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003058 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3059 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3060 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003061 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003062 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3063 ErrorFound = true;
3064 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003065 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003066 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003067 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003068 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003069 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003070 // Mark all variables in private list clauses as used in inner region.
3071 // Required for proper codegen of combined directives.
3072 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003073 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003074 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003075 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3076 // Find the particular capture region for the clause if the
3077 // directive is a combined one with multiple capture regions.
3078 // If the directive is not a combined one, the capture region
3079 // associated with the clause is OMPD_unknown and is generated
3080 // only once.
3081 if (CaptureRegion == ThisCaptureRegion ||
3082 CaptureRegion == OMPD_unknown) {
3083 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003084 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003085 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3086 }
3087 }
3088 }
3089 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003090 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003091 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003092 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003093}
3094
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003095static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3096 OpenMPDirectiveKind CancelRegion,
3097 SourceLocation StartLoc) {
3098 // CancelRegion is only needed for cancel and cancellation_point.
3099 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3100 return false;
3101
3102 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3103 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3104 return false;
3105
3106 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3107 << getOpenMPDirectiveName(CancelRegion);
3108 return true;
3109}
3110
Alexey Bataeve3727102018-04-18 15:57:46 +00003111static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003112 OpenMPDirectiveKind CurrentRegion,
3113 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003114 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003115 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003116 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003117 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3118 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003119 bool NestingProhibited = false;
3120 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003121 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003122 enum {
3123 NoRecommend,
3124 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003125 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003126 ShouldBeInTargetRegion,
3127 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003128 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003129 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003130 // OpenMP [2.16, Nesting of Regions]
3131 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003132 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003133 // An ordered construct with the simd clause is the only OpenMP
3134 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003135 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003136 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3137 // message.
3138 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3139 ? diag::err_omp_prohibited_region_simd
3140 : diag::warn_omp_nesting_simd);
3141 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003142 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003143 if (ParentRegion == OMPD_atomic) {
3144 // OpenMP [2.16, Nesting of Regions]
3145 // OpenMP constructs may not be nested inside an atomic region.
3146 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3147 return true;
3148 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003149 if (CurrentRegion == OMPD_section) {
3150 // OpenMP [2.7.2, sections Construct, Restrictions]
3151 // Orphaned section directives are prohibited. That is, the section
3152 // directives must appear within the sections construct and must not be
3153 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003154 if (ParentRegion != OMPD_sections &&
3155 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003156 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3157 << (ParentRegion != OMPD_unknown)
3158 << getOpenMPDirectiveName(ParentRegion);
3159 return true;
3160 }
3161 return false;
3162 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003163 // Allow some constructs (except teams and cancellation constructs) to be
3164 // orphaned (they could be used in functions, called from OpenMP regions
3165 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003166 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003167 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3168 CurrentRegion != OMPD_cancellation_point &&
3169 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003170 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003171 if (CurrentRegion == OMPD_cancellation_point ||
3172 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003173 // OpenMP [2.16, Nesting of Regions]
3174 // A cancellation point construct for which construct-type-clause is
3175 // taskgroup must be nested inside a task construct. A cancellation
3176 // point construct for which construct-type-clause is not taskgroup must
3177 // be closely nested inside an OpenMP construct that matches the type
3178 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003179 // A cancel construct for which construct-type-clause is taskgroup must be
3180 // nested inside a task construct. A cancel construct for which
3181 // construct-type-clause is not taskgroup must be closely nested inside an
3182 // OpenMP construct that matches the type specified in
3183 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003184 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003185 !((CancelRegion == OMPD_parallel &&
3186 (ParentRegion == OMPD_parallel ||
3187 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003188 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003189 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003190 ParentRegion == OMPD_target_parallel_for ||
3191 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003192 ParentRegion == OMPD_teams_distribute_parallel_for ||
3193 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003194 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3195 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003196 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3197 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003198 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003199 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003200 // OpenMP [2.16, Nesting of Regions]
3201 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003202 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003203 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003204 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003205 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3206 // OpenMP [2.16, Nesting of Regions]
3207 // A critical region may not be nested (closely or otherwise) inside a
3208 // critical region with the same name. Note that this restriction is not
3209 // sufficient to prevent deadlock.
3210 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003211 bool DeadLock = Stack->hasDirective(
3212 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3213 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003214 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003215 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3216 PreviousCriticalLoc = Loc;
3217 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003218 }
3219 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003220 },
3221 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003222 if (DeadLock) {
3223 SemaRef.Diag(StartLoc,
3224 diag::err_omp_prohibited_region_critical_same_name)
3225 << CurrentName.getName();
3226 if (PreviousCriticalLoc.isValid())
3227 SemaRef.Diag(PreviousCriticalLoc,
3228 diag::note_omp_previous_critical_region);
3229 return true;
3230 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003231 } else if (CurrentRegion == OMPD_barrier) {
3232 // OpenMP [2.16, Nesting of Regions]
3233 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003234 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003235 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3236 isOpenMPTaskingDirective(ParentRegion) ||
3237 ParentRegion == OMPD_master ||
3238 ParentRegion == OMPD_critical ||
3239 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003240 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003241 !isOpenMPParallelDirective(CurrentRegion) &&
3242 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003243 // OpenMP [2.16, Nesting of Regions]
3244 // A worksharing region may not be closely nested inside a worksharing,
3245 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003246 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3247 isOpenMPTaskingDirective(ParentRegion) ||
3248 ParentRegion == OMPD_master ||
3249 ParentRegion == OMPD_critical ||
3250 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003251 Recommend = ShouldBeInParallelRegion;
3252 } else if (CurrentRegion == OMPD_ordered) {
3253 // OpenMP [2.16, Nesting of Regions]
3254 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003255 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003256 // An ordered region must be closely nested inside a loop region (or
3257 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003258 // OpenMP [2.8.1,simd Construct, Restrictions]
3259 // An ordered construct with the simd clause is the only OpenMP construct
3260 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003261 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003262 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003263 !(isOpenMPSimdDirective(ParentRegion) ||
3264 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003265 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003266 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003267 // OpenMP [2.16, Nesting of Regions]
3268 // If specified, a teams construct must be contained within a target
3269 // construct.
3270 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003271 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003272 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003273 }
Kelvin Libf594a52016-12-17 05:48:59 +00003274 if (!NestingProhibited &&
3275 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3276 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3277 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003278 // OpenMP [2.16, Nesting of Regions]
3279 // distribute, parallel, parallel sections, parallel workshare, and the
3280 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3281 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003282 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3283 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003284 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003285 }
David Majnemer9d168222016-08-05 17:44:54 +00003286 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003287 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003288 // OpenMP 4.5 [2.17 Nesting of Regions]
3289 // The region associated with the distribute construct must be strictly
3290 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003291 NestingProhibited =
3292 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003293 Recommend = ShouldBeInTeamsRegion;
3294 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003295 if (!NestingProhibited &&
3296 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3297 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3298 // OpenMP 4.5 [2.17 Nesting of Regions]
3299 // If a target, target update, target data, target enter data, or
3300 // target exit data construct is encountered during execution of a
3301 // target region, the behavior is unspecified.
3302 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003303 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003304 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003305 if (isOpenMPTargetExecutionDirective(K)) {
3306 OffendingRegion = K;
3307 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003308 }
3309 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003310 },
3311 false /* don't skip top directive */);
3312 CloseNesting = false;
3313 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003314 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003315 if (OrphanSeen) {
3316 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3317 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3318 } else {
3319 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3320 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3321 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3322 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003323 return true;
3324 }
3325 }
3326 return false;
3327}
3328
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003329static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3330 ArrayRef<OMPClause *> Clauses,
3331 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3332 bool ErrorFound = false;
3333 unsigned NamedModifiersNumber = 0;
3334 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3335 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003336 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003337 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003338 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3339 // At most one if clause without a directive-name-modifier can appear on
3340 // the directive.
3341 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3342 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003343 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003344 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3345 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3346 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003347 } else if (CurNM != OMPD_unknown) {
3348 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003349 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003350 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003351 FoundNameModifiers[CurNM] = IC;
3352 if (CurNM == OMPD_unknown)
3353 continue;
3354 // Check if the specified name modifier is allowed for the current
3355 // directive.
3356 // At most one if clause with the particular directive-name-modifier can
3357 // appear on the directive.
3358 bool MatchFound = false;
3359 for (auto NM : AllowedNameModifiers) {
3360 if (CurNM == NM) {
3361 MatchFound = true;
3362 break;
3363 }
3364 }
3365 if (!MatchFound) {
3366 S.Diag(IC->getNameModifierLoc(),
3367 diag::err_omp_wrong_if_directive_name_modifier)
3368 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3369 ErrorFound = true;
3370 }
3371 }
3372 }
3373 // If any if clause on the directive includes a directive-name-modifier then
3374 // all if clauses on the directive must include a directive-name-modifier.
3375 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3376 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003377 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003378 diag::err_omp_no_more_if_clause);
3379 } else {
3380 std::string Values;
3381 std::string Sep(", ");
3382 unsigned AllowedCnt = 0;
3383 unsigned TotalAllowedNum =
3384 AllowedNameModifiers.size() - NamedModifiersNumber;
3385 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3386 ++Cnt) {
3387 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3388 if (!FoundNameModifiers[NM]) {
3389 Values += "'";
3390 Values += getOpenMPDirectiveName(NM);
3391 Values += "'";
3392 if (AllowedCnt + 2 == TotalAllowedNum)
3393 Values += " or ";
3394 else if (AllowedCnt + 1 != TotalAllowedNum)
3395 Values += Sep;
3396 ++AllowedCnt;
3397 }
3398 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003399 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003400 diag::err_omp_unnamed_if_clause)
3401 << (TotalAllowedNum > 1) << Values;
3402 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003403 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003404 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3405 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003406 ErrorFound = true;
3407 }
3408 return ErrorFound;
3409}
3410
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003411StmtResult Sema::ActOnOpenMPExecutableDirective(
3412 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3413 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3414 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003415 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003416 // First check CancelRegion which is then used in checkNestingOfRegions.
3417 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3418 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003419 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003420 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003421
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003422 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003423 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003424 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003425 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003426 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003427 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3428
3429 // Check default data sharing attributes for referenced variables.
3430 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003431 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3432 Stmt *S = AStmt;
3433 while (--ThisCaptureLevel >= 0)
3434 S = cast<CapturedStmt>(S)->getCapturedStmt();
3435 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003436 if (DSAChecker.isErrorFound())
3437 return StmtError();
3438 // Generate list of implicitly defined firstprivate variables.
3439 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003440
Alexey Bataev88202be2017-07-27 13:20:36 +00003441 SmallVector<Expr *, 4> ImplicitFirstprivates(
3442 DSAChecker.getImplicitFirstprivate().begin(),
3443 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003444 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3445 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003446 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003447 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003448 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003449 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003450 if (E)
3451 ImplicitFirstprivates.emplace_back(E);
3452 }
3453 }
3454 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003455 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003456 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3457 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003458 ClausesWithImplicit.push_back(Implicit);
3459 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003460 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003461 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003462 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003463 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003464 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003465 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003466 CXXScopeSpec MapperIdScopeSpec;
3467 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003468 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003469 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3470 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3471 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003472 ClausesWithImplicit.emplace_back(Implicit);
3473 ErrorFound |=
3474 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003475 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003476 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003477 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003478 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003479 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003480
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003481 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003482 switch (Kind) {
3483 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003484 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3485 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003486 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003487 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003488 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003489 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3490 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003491 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003492 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003493 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3494 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003495 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003496 case OMPD_for_simd:
3497 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3498 EndLoc, VarsWithInheritedDSA);
3499 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003500 case OMPD_sections:
3501 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3502 EndLoc);
3503 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003504 case OMPD_section:
3505 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003506 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003507 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3508 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003509 case OMPD_single:
3510 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3511 EndLoc);
3512 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003513 case OMPD_master:
3514 assert(ClausesWithImplicit.empty() &&
3515 "No clauses are allowed for 'omp master' directive");
3516 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3517 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003518 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003519 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3520 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003521 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003522 case OMPD_parallel_for:
3523 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3524 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003525 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003526 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003527 case OMPD_parallel_for_simd:
3528 Res = ActOnOpenMPParallelForSimdDirective(
3529 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003530 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003531 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003532 case OMPD_parallel_sections:
3533 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3534 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003535 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003536 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003537 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003538 Res =
3539 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003540 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003541 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003542 case OMPD_taskyield:
3543 assert(ClausesWithImplicit.empty() &&
3544 "No clauses are allowed for 'omp taskyield' directive");
3545 assert(AStmt == nullptr &&
3546 "No associated statement allowed for 'omp taskyield' directive");
3547 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3548 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003549 case OMPD_barrier:
3550 assert(ClausesWithImplicit.empty() &&
3551 "No clauses are allowed for 'omp barrier' directive");
3552 assert(AStmt == nullptr &&
3553 "No associated statement allowed for 'omp barrier' directive");
3554 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3555 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003556 case OMPD_taskwait:
3557 assert(ClausesWithImplicit.empty() &&
3558 "No clauses are allowed for 'omp taskwait' directive");
3559 assert(AStmt == nullptr &&
3560 "No associated statement allowed for 'omp taskwait' directive");
3561 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3562 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003563 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003564 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3565 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003566 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003567 case OMPD_flush:
3568 assert(AStmt == nullptr &&
3569 "No associated statement allowed for 'omp flush' directive");
3570 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3571 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003572 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003573 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3574 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003575 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003576 case OMPD_atomic:
3577 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3578 EndLoc);
3579 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003580 case OMPD_teams:
3581 Res =
3582 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3583 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003584 case OMPD_target:
3585 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3586 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003587 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003588 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003589 case OMPD_target_parallel:
3590 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3591 StartLoc, EndLoc);
3592 AllowedNameModifiers.push_back(OMPD_target);
3593 AllowedNameModifiers.push_back(OMPD_parallel);
3594 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003595 case OMPD_target_parallel_for:
3596 Res = ActOnOpenMPTargetParallelForDirective(
3597 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3598 AllowedNameModifiers.push_back(OMPD_target);
3599 AllowedNameModifiers.push_back(OMPD_parallel);
3600 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003601 case OMPD_cancellation_point:
3602 assert(ClausesWithImplicit.empty() &&
3603 "No clauses are allowed for 'omp cancellation point' directive");
3604 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3605 "cancellation point' directive");
3606 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3607 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003608 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003609 assert(AStmt == nullptr &&
3610 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003611 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3612 CancelRegion);
3613 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003614 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003615 case OMPD_target_data:
3616 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3617 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003618 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003619 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003620 case OMPD_target_enter_data:
3621 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003622 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003623 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3624 break;
Samuel Antao72590762016-01-19 20:04:50 +00003625 case OMPD_target_exit_data:
3626 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003627 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003628 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3629 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003630 case OMPD_taskloop:
3631 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3632 EndLoc, VarsWithInheritedDSA);
3633 AllowedNameModifiers.push_back(OMPD_taskloop);
3634 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003635 case OMPD_taskloop_simd:
3636 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3637 EndLoc, VarsWithInheritedDSA);
3638 AllowedNameModifiers.push_back(OMPD_taskloop);
3639 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003640 case OMPD_distribute:
3641 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3642 EndLoc, VarsWithInheritedDSA);
3643 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003644 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003645 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3646 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003647 AllowedNameModifiers.push_back(OMPD_target_update);
3648 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003649 case OMPD_distribute_parallel_for:
3650 Res = ActOnOpenMPDistributeParallelForDirective(
3651 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3652 AllowedNameModifiers.push_back(OMPD_parallel);
3653 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003654 case OMPD_distribute_parallel_for_simd:
3655 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3656 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3657 AllowedNameModifiers.push_back(OMPD_parallel);
3658 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003659 case OMPD_distribute_simd:
3660 Res = ActOnOpenMPDistributeSimdDirective(
3661 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3662 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003663 case OMPD_target_parallel_for_simd:
3664 Res = ActOnOpenMPTargetParallelForSimdDirective(
3665 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3666 AllowedNameModifiers.push_back(OMPD_target);
3667 AllowedNameModifiers.push_back(OMPD_parallel);
3668 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003669 case OMPD_target_simd:
3670 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3671 EndLoc, VarsWithInheritedDSA);
3672 AllowedNameModifiers.push_back(OMPD_target);
3673 break;
Kelvin Li02532872016-08-05 14:37:37 +00003674 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003675 Res = ActOnOpenMPTeamsDistributeDirective(
3676 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003677 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003678 case OMPD_teams_distribute_simd:
3679 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3680 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3681 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003682 case OMPD_teams_distribute_parallel_for_simd:
3683 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3684 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3685 AllowedNameModifiers.push_back(OMPD_parallel);
3686 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003687 case OMPD_teams_distribute_parallel_for:
3688 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3689 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3690 AllowedNameModifiers.push_back(OMPD_parallel);
3691 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003692 case OMPD_target_teams:
3693 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3694 EndLoc);
3695 AllowedNameModifiers.push_back(OMPD_target);
3696 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003697 case OMPD_target_teams_distribute:
3698 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3699 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3700 AllowedNameModifiers.push_back(OMPD_target);
3701 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003702 case OMPD_target_teams_distribute_parallel_for:
3703 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3704 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3705 AllowedNameModifiers.push_back(OMPD_target);
3706 AllowedNameModifiers.push_back(OMPD_parallel);
3707 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003708 case OMPD_target_teams_distribute_parallel_for_simd:
3709 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3710 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3711 AllowedNameModifiers.push_back(OMPD_target);
3712 AllowedNameModifiers.push_back(OMPD_parallel);
3713 break;
Kelvin Lida681182017-01-10 18:08:18 +00003714 case OMPD_target_teams_distribute_simd:
3715 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3716 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3717 AllowedNameModifiers.push_back(OMPD_target);
3718 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003719 case OMPD_declare_target:
3720 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003721 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003722 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003723 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003724 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003725 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003726 llvm_unreachable("OpenMP Directive is not allowed");
3727 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003728 llvm_unreachable("Unknown OpenMP directive");
3729 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003730
Alexey Bataeve3727102018-04-18 15:57:46 +00003731 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003732 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3733 << P.first << P.second->getSourceRange();
3734 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003735 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3736
3737 if (!AllowedNameModifiers.empty())
3738 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3739 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003740
Alexey Bataeved09d242014-05-28 05:53:51 +00003741 if (ErrorFound)
3742 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003743 return Res;
3744}
3745
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003746Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3747 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003748 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003749 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3750 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003751 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003752 assert(Linears.size() == LinModifiers.size());
3753 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003754 if (!DG || DG.get().isNull())
3755 return DeclGroupPtrTy();
3756
3757 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003758 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003759 return DG;
3760 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003761 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003762 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3763 ADecl = FTD->getTemplatedDecl();
3764
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003765 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3766 if (!FD) {
3767 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003768 return DeclGroupPtrTy();
3769 }
3770
Alexey Bataev2af33e32016-04-07 12:45:37 +00003771 // OpenMP [2.8.2, declare simd construct, Description]
3772 // The parameter of the simdlen clause must be a constant positive integer
3773 // expression.
3774 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003775 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003776 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003777 // OpenMP [2.8.2, declare simd construct, Description]
3778 // The special this pointer can be used as if was one of the arguments to the
3779 // function in any of the linear, aligned, or uniform clauses.
3780 // The uniform clause declares one or more arguments to have an invariant
3781 // value for all concurrent invocations of the function in the execution of a
3782 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003783 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3784 const Expr *UniformedLinearThis = nullptr;
3785 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003786 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003787 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3788 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003789 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3790 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003791 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00003792 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003793 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003794 }
3795 if (isa<CXXThisExpr>(E)) {
3796 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003797 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003798 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003799 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3800 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003801 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003802 // OpenMP [2.8.2, declare simd construct, Description]
3803 // The aligned clause declares that the object to which each list item points
3804 // is aligned to the number of bytes expressed in the optional parameter of
3805 // the aligned clause.
3806 // The special this pointer can be used as if was one of the arguments to the
3807 // function in any of the linear, aligned, or uniform clauses.
3808 // The type of list items appearing in the aligned clause must be array,
3809 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00003810 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3811 const Expr *AlignedThis = nullptr;
3812 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003813 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003814 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3815 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3816 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00003817 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3818 FD->getParamDecl(PVD->getFunctionScopeIndex())
3819 ->getCanonicalDecl() == CanonPVD) {
3820 // OpenMP [2.8.1, simd construct, Restrictions]
3821 // A list-item cannot appear in more than one aligned clause.
3822 if (AlignedArgs.count(CanonPVD) > 0) {
3823 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3824 << 1 << E->getSourceRange();
3825 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3826 diag::note_omp_explicit_dsa)
3827 << getOpenMPClauseName(OMPC_aligned);
3828 continue;
3829 }
3830 AlignedArgs[CanonPVD] = E;
3831 QualType QTy = PVD->getType()
3832 .getNonReferenceType()
3833 .getUnqualifiedType()
3834 .getCanonicalType();
3835 const Type *Ty = QTy.getTypePtrOrNull();
3836 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3837 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3838 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3839 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3840 }
3841 continue;
3842 }
3843 }
3844 if (isa<CXXThisExpr>(E)) {
3845 if (AlignedThis) {
3846 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3847 << 2 << E->getSourceRange();
3848 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3849 << getOpenMPClauseName(OMPC_aligned);
3850 }
3851 AlignedThis = E;
3852 continue;
3853 }
3854 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3855 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3856 }
3857 // The optional parameter of the aligned clause, alignment, must be a constant
3858 // positive integer expression. If no optional parameter is specified,
3859 // implementation-defined default alignments for SIMD instructions on the
3860 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00003861 SmallVector<const Expr *, 4> NewAligns;
3862 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003863 ExprResult Align;
3864 if (E)
3865 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3866 NewAligns.push_back(Align.get());
3867 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003868 // OpenMP [2.8.2, declare simd construct, Description]
3869 // The linear clause declares one or more list items to be private to a SIMD
3870 // lane and to have a linear relationship with respect to the iteration space
3871 // of a loop.
3872 // The special this pointer can be used as if was one of the arguments to the
3873 // function in any of the linear, aligned, or uniform clauses.
3874 // When a linear-step expression is specified in a linear clause it must be
3875 // either a constant integer expression or an integer-typed parameter that is
3876 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00003877 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003878 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3879 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00003880 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003881 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3882 ++MI;
3883 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003884 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3885 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3886 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003887 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3888 FD->getParamDecl(PVD->getFunctionScopeIndex())
3889 ->getCanonicalDecl() == CanonPVD) {
3890 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3891 // A list-item cannot appear in more than one linear clause.
3892 if (LinearArgs.count(CanonPVD) > 0) {
3893 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3894 << getOpenMPClauseName(OMPC_linear)
3895 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3896 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3897 diag::note_omp_explicit_dsa)
3898 << getOpenMPClauseName(OMPC_linear);
3899 continue;
3900 }
3901 // Each argument can appear in at most one uniform or linear clause.
3902 if (UniformedArgs.count(CanonPVD) > 0) {
3903 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3904 << getOpenMPClauseName(OMPC_linear)
3905 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3906 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3907 diag::note_omp_explicit_dsa)
3908 << getOpenMPClauseName(OMPC_uniform);
3909 continue;
3910 }
3911 LinearArgs[CanonPVD] = E;
3912 if (E->isValueDependent() || E->isTypeDependent() ||
3913 E->isInstantiationDependent() ||
3914 E->containsUnexpandedParameterPack())
3915 continue;
3916 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3917 PVD->getOriginalType());
3918 continue;
3919 }
3920 }
3921 if (isa<CXXThisExpr>(E)) {
3922 if (UniformedLinearThis) {
3923 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3924 << getOpenMPClauseName(OMPC_linear)
3925 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3926 << E->getSourceRange();
3927 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3928 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3929 : OMPC_linear);
3930 continue;
3931 }
3932 UniformedLinearThis = E;
3933 if (E->isValueDependent() || E->isTypeDependent() ||
3934 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3935 continue;
3936 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3937 E->getType());
3938 continue;
3939 }
3940 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3941 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3942 }
3943 Expr *Step = nullptr;
3944 Expr *NewStep = nullptr;
3945 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00003946 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003947 // Skip the same step expression, it was checked already.
3948 if (Step == E || !E) {
3949 NewSteps.push_back(E ? NewStep : nullptr);
3950 continue;
3951 }
3952 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00003953 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3954 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3955 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003956 if (UniformedArgs.count(CanonPVD) == 0) {
3957 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3958 << Step->getSourceRange();
3959 } else if (E->isValueDependent() || E->isTypeDependent() ||
3960 E->isInstantiationDependent() ||
3961 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00003962 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003963 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00003964 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003965 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3966 << Step->getSourceRange();
3967 }
3968 continue;
3969 }
3970 NewStep = Step;
3971 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3972 !Step->isInstantiationDependent() &&
3973 !Step->containsUnexpandedParameterPack()) {
3974 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3975 .get();
3976 if (NewStep)
3977 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3978 }
3979 NewSteps.push_back(NewStep);
3980 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003981 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3982 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003983 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003984 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3985 const_cast<Expr **>(Linears.data()), Linears.size(),
3986 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3987 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003988 ADecl->addAttr(NewAttr);
3989 return ConvertDeclToDeclGroup(ADecl);
3990}
3991
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003992StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3993 Stmt *AStmt,
3994 SourceLocation StartLoc,
3995 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003996 if (!AStmt)
3997 return StmtError();
3998
Alexey Bataeve3727102018-04-18 15:57:46 +00003999 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004000 // 1.2.2 OpenMP Language Terminology
4001 // Structured block - An executable statement with a single entry at the
4002 // top and a single exit at the bottom.
4003 // The point of exit cannot be a branch out of the structured block.
4004 // longjmp() and throw() must not violate the entry/exit criteria.
4005 CS->getCapturedDecl()->setNothrow();
4006
Reid Kleckner87a31802018-03-12 21:43:02 +00004007 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004008
Alexey Bataev25e5b442015-09-15 12:52:43 +00004009 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4010 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004011}
4012
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004013namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004014/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004015/// extracting iteration space of each loop in the loop nest, that will be used
4016/// for IR generation.
4017class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004018 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004019 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004020 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004021 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004022 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004023 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004024 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004025 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004026 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004027 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004028 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004029 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004030 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004031 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004032 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004033 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004034 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004035 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004036 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004037 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004038 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004039 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004040 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004041 /// Var < UB
4042 /// Var <= UB
4043 /// UB > Var
4044 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004045 /// This will have no value when the condition is !=
4046 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004047 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004048 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004049 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004050 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004051
4052public:
4053 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004054 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004055 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004056 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004057 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004058 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004059 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004060 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004061 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004062 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004063 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004064 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004065 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004066 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004067 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004068 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004069 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004070 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004071 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004072 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004073 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004074 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004075 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004076 /// True, if the compare operator is strict (<, > or !=).
4077 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004078 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004079 Expr *buildNumIterations(
4080 Scope *S, const bool LimitedType,
4081 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004082 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004083 Expr *
4084 buildPreCond(Scope *S, Expr *Cond,
4085 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004086 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004087 DeclRefExpr *
4088 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4089 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004090 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004091 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004092 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004093 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004094 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004095 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004096 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004097 /// Build loop data with counter value for depend clauses in ordered
4098 /// directives.
4099 Expr *
4100 buildOrderedLoopData(Scope *S, Expr *Counter,
4101 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4102 SourceLocation Loc, Expr *Inc = nullptr,
4103 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004104 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004105 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004106
4107private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004108 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004109 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004110 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004111 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004112 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004113 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004114 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4115 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004116 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004117 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004118};
4119
Alexey Bataeve3727102018-04-18 15:57:46 +00004120bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004121 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004122 assert(!LB && !UB && !Step);
4123 return false;
4124 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004125 return LCDecl->getType()->isDependentType() ||
4126 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4127 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004128}
4129
Alexey Bataeve3727102018-04-18 15:57:46 +00004130bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004131 Expr *NewLCRefExpr,
4132 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004133 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004134 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004135 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004136 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004137 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004138 LCDecl = getCanonicalDecl(NewLCDecl);
4139 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004140 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4141 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004142 if ((Ctor->isCopyOrMoveConstructor() ||
4143 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4144 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004145 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004146 LB = NewLB;
4147 return false;
4148}
4149
Alexey Bataev316ccf62019-01-29 18:51:58 +00004150bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4151 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004152 bool StrictOp, SourceRange SR,
4153 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004154 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004155 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4156 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004157 if (!NewUB)
4158 return true;
4159 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004160 if (LessOp)
4161 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004162 TestIsStrictOp = StrictOp;
4163 ConditionSrcRange = SR;
4164 ConditionLoc = SL;
4165 return false;
4166}
4167
Alexey Bataeve3727102018-04-18 15:57:46 +00004168bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004169 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004170 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004171 if (!NewStep)
4172 return true;
4173 if (!NewStep->isValueDependent()) {
4174 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004175 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004176 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4177 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004178 if (Val.isInvalid())
4179 return true;
4180 NewStep = Val.get();
4181
4182 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4183 // If test-expr is of form var relational-op b and relational-op is < or
4184 // <= then incr-expr must cause var to increase on each iteration of the
4185 // loop. If test-expr is of form var relational-op b and relational-op is
4186 // > or >= then incr-expr must cause var to decrease on each iteration of
4187 // the loop.
4188 // If test-expr is of form b relational-op var and relational-op is < or
4189 // <= then incr-expr must cause var to decrease on each iteration of the
4190 // loop. If test-expr is of form b relational-op var and relational-op is
4191 // > or >= then incr-expr must cause var to increase on each iteration of
4192 // the loop.
4193 llvm::APSInt Result;
4194 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4195 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4196 bool IsConstNeg =
4197 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004198 bool IsConstPos =
4199 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004200 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004201
4202 // != with increment is treated as <; != with decrement is treated as >
4203 if (!TestIsLessOp.hasValue())
4204 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004205 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004206 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004207 (IsConstNeg || (IsUnsigned && Subtract)) :
4208 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004209 SemaRef.Diag(NewStep->getExprLoc(),
4210 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004211 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004212 SemaRef.Diag(ConditionLoc,
4213 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004214 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004215 return true;
4216 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004217 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004218 NewStep =
4219 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4220 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004221 Subtract = !Subtract;
4222 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004223 }
4224
4225 Step = NewStep;
4226 SubtractStep = Subtract;
4227 return false;
4228}
4229
Alexey Bataeve3727102018-04-18 15:57:46 +00004230bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004231 // Check init-expr for canonical loop form and save loop counter
4232 // variable - #Var and its initialization value - #LB.
4233 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4234 // var = lb
4235 // integer-type var = lb
4236 // random-access-iterator-type var = lb
4237 // pointer-type var = lb
4238 //
4239 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004240 if (EmitDiags) {
4241 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4242 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004243 return true;
4244 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004245 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4246 if (!ExprTemp->cleanupsHaveSideEffects())
4247 S = ExprTemp->getSubExpr();
4248
Alexander Musmana5f070a2014-10-01 06:03:56 +00004249 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004250 if (Expr *E = dyn_cast<Expr>(S))
4251 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004252 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004253 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004254 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004255 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4256 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4257 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004258 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4259 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004260 }
4261 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4262 if (ME->isArrow() &&
4263 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004264 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004265 }
4266 }
David Majnemer9d168222016-08-05 17:44:54 +00004267 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004268 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004269 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004270 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004271 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004272 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004273 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004274 diag::ext_omp_loop_not_canonical_init)
4275 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004276 return setLCDeclAndLB(
4277 Var,
4278 buildDeclRefExpr(SemaRef, Var,
4279 Var->getType().getNonReferenceType(),
4280 DS->getBeginLoc()),
4281 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004282 }
4283 }
4284 }
David Majnemer9d168222016-08-05 17:44:54 +00004285 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004286 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004287 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004288 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004289 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4290 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004291 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4292 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004293 }
4294 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4295 if (ME->isArrow() &&
4296 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004297 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004298 }
4299 }
4300 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004301
Alexey Bataeve3727102018-04-18 15:57:46 +00004302 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004303 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004304 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004305 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004306 << S->getSourceRange();
4307 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004308 return true;
4309}
4310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004311/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004312/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004313static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004314 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004315 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004316 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004317 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004318 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004319 if ((Ctor->isCopyOrMoveConstructor() ||
4320 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4321 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004322 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004323 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4324 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004325 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004326 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004327 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004328 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4329 return getCanonicalDecl(ME->getMemberDecl());
4330 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004331}
4332
Alexey Bataeve3727102018-04-18 15:57:46 +00004333bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004334 // Check test-expr for canonical form, save upper-bound UB, flags for
4335 // less/greater and for strict/non-strict comparison.
4336 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4337 // var relational-op b
4338 // b relational-op var
4339 //
4340 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004341 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004342 return true;
4343 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004344 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004345 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004346 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004347 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004348 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4349 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004350 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4351 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4352 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004353 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4354 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004355 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4356 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4357 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004358 } else if (BO->getOpcode() == BO_NE)
4359 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4360 BO->getRHS() : BO->getLHS(),
4361 /*LessOp=*/llvm::None,
4362 /*StrictOp=*/true,
4363 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004364 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004365 if (CE->getNumArgs() == 2) {
4366 auto Op = CE->getOperator();
4367 switch (Op) {
4368 case OO_Greater:
4369 case OO_GreaterEqual:
4370 case OO_Less:
4371 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004372 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4373 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004374 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4375 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004376 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4377 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004378 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4379 CE->getOperatorLoc());
4380 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004381 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004382 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4383 CE->getArg(1) : CE->getArg(0),
4384 /*LessOp=*/llvm::None,
4385 /*StrictOp=*/true,
4386 CE->getSourceRange(),
4387 CE->getOperatorLoc());
4388 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004389 default:
4390 break;
4391 }
4392 }
4393 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004394 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004395 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004396 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004397 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004398 return true;
4399}
4400
Alexey Bataeve3727102018-04-18 15:57:46 +00004401bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004402 // RHS of canonical loop form increment can be:
4403 // var + incr
4404 // incr + var
4405 // var - incr
4406 //
4407 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004408 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004409 if (BO->isAdditiveOp()) {
4410 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004411 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4412 return setStep(BO->getRHS(), !IsAdd);
4413 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4414 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004415 }
David Majnemer9d168222016-08-05 17:44:54 +00004416 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004417 bool IsAdd = CE->getOperator() == OO_Plus;
4418 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004419 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4420 return setStep(CE->getArg(1), !IsAdd);
4421 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4422 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004423 }
4424 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004425 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004426 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004427 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004428 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004429 return true;
4430}
4431
Alexey Bataeve3727102018-04-18 15:57:46 +00004432bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004433 // Check incr-expr for canonical loop form and return true if it
4434 // does not conform.
4435 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4436 // ++var
4437 // var++
4438 // --var
4439 // var--
4440 // var += incr
4441 // var -= incr
4442 // var = var + incr
4443 // var = incr + var
4444 // var = var - incr
4445 //
4446 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004447 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004448 return true;
4449 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004450 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4451 if (!ExprTemp->cleanupsHaveSideEffects())
4452 S = ExprTemp->getSubExpr();
4453
Alexander Musmana5f070a2014-10-01 06:03:56 +00004454 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004455 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004456 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004457 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004458 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4459 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004460 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004461 (UO->isDecrementOp() ? -1 : 1))
4462 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004463 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004464 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004465 switch (BO->getOpcode()) {
4466 case BO_AddAssign:
4467 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004468 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4469 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004470 break;
4471 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004472 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4473 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004474 break;
4475 default:
4476 break;
4477 }
David Majnemer9d168222016-08-05 17:44:54 +00004478 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004479 switch (CE->getOperator()) {
4480 case OO_PlusPlus:
4481 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004482 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4483 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004484 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004485 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004486 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4487 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004488 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004489 break;
4490 case OO_PlusEqual:
4491 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004492 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4493 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004494 break;
4495 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004496 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4497 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004498 break;
4499 default:
4500 break;
4501 }
4502 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004503 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004504 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004505 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004506 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004507 return true;
4508}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004509
Alexey Bataev5a3af132016-03-29 08:58:54 +00004510static ExprResult
4511tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004512 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004513 if (SemaRef.CurContext->isDependentContext())
4514 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004515 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4516 return SemaRef.PerformImplicitConversion(
4517 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4518 /*AllowExplicit=*/true);
4519 auto I = Captures.find(Capture);
4520 if (I != Captures.end())
4521 return buildCapture(SemaRef, Capture, I->second);
4522 DeclRefExpr *Ref = nullptr;
4523 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4524 Captures[Capture] = Ref;
4525 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004526}
4527
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004528/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004529Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004530 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004531 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004532 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004533 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004534 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004535 SemaRef.getLangOpts().CPlusPlus) {
4536 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004537 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4538 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004539 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4540 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004541 if (!Upper || !Lower)
4542 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004543
4544 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4545
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004546 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004547 // BuildBinOp already emitted error, this one is to point user to upper
4548 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004549 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004550 << Upper->getSourceRange() << Lower->getSourceRange();
4551 return nullptr;
4552 }
4553 }
4554
4555 if (!Diff.isUsable())
4556 return nullptr;
4557
4558 // Upper - Lower [- 1]
4559 if (TestIsStrictOp)
4560 Diff = SemaRef.BuildBinOp(
4561 S, DefaultLoc, BO_Sub, Diff.get(),
4562 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4563 if (!Diff.isUsable())
4564 return nullptr;
4565
4566 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004567 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004568 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004569 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004570 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004571 if (!Diff.isUsable())
4572 return nullptr;
4573
4574 // Parentheses (for dumping/debugging purposes only).
4575 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4576 if (!Diff.isUsable())
4577 return nullptr;
4578
4579 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004580 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004581 if (!Diff.isUsable())
4582 return nullptr;
4583
Alexander Musman174b3ca2014-10-06 11:16:29 +00004584 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004585 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004586 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004587 bool UseVarType = VarType->hasIntegerRepresentation() &&
4588 C.getTypeSize(Type) > C.getTypeSize(VarType);
4589 if (!Type->isIntegerType() || UseVarType) {
4590 unsigned NewSize =
4591 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4592 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4593 : Type->hasSignedIntegerRepresentation();
4594 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004595 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4596 Diff = SemaRef.PerformImplicitConversion(
4597 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4598 if (!Diff.isUsable())
4599 return nullptr;
4600 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004601 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004602 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004603 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4604 if (NewSize != C.getTypeSize(Type)) {
4605 if (NewSize < C.getTypeSize(Type)) {
4606 assert(NewSize == 64 && "incorrect loop var size");
4607 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4608 << InitSrcRange << ConditionSrcRange;
4609 }
4610 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004611 NewSize, Type->hasSignedIntegerRepresentation() ||
4612 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004613 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4614 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4615 Sema::AA_Converting, true);
4616 if (!Diff.isUsable())
4617 return nullptr;
4618 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004619 }
4620 }
4621
Alexander Musmana5f070a2014-10-01 06:03:56 +00004622 return Diff.get();
4623}
4624
Alexey Bataeve3727102018-04-18 15:57:46 +00004625Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004626 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004627 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004628 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4629 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4630 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004631
Alexey Bataeve3727102018-04-18 15:57:46 +00004632 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4633 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004634 if (!NewLB.isUsable() || !NewUB.isUsable())
4635 return nullptr;
4636
Alexey Bataeve3727102018-04-18 15:57:46 +00004637 ExprResult CondExpr =
4638 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004639 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004640 (TestIsStrictOp ? BO_LT : BO_LE) :
4641 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004642 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004643 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004644 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4645 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004646 CondExpr = SemaRef.PerformImplicitConversion(
4647 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4648 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004649 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004650 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004651 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004652 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4653}
4654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004655/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004656DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004657 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4658 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004659 auto *VD = dyn_cast<VarDecl>(LCDecl);
4660 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004661 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4662 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004663 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004664 const DSAStackTy::DSAVarData Data =
4665 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004666 // If the loop control decl is explicitly marked as private, do not mark it
4667 // as captured again.
4668 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4669 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004670 return Ref;
4671 }
4672 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004673 DefaultLoc);
4674}
4675
Alexey Bataeve3727102018-04-18 15:57:46 +00004676Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004677 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004678 QualType Type = LCDecl->getType().getNonReferenceType();
4679 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004680 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4681 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4682 isa<VarDecl>(LCDecl)
4683 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4684 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004685 if (PrivateVar->isInvalidDecl())
4686 return nullptr;
4687 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4688 }
4689 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004690}
4691
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004692/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004693Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004694
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004695/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004696Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004697
Alexey Bataevf138fda2018-08-13 19:04:24 +00004698Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4699 Scope *S, Expr *Counter,
4700 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4701 Expr *Inc, OverloadedOperatorKind OOK) {
4702 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4703 if (!Cnt)
4704 return nullptr;
4705 if (Inc) {
4706 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4707 "Expected only + or - operations for depend clauses.");
4708 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4709 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4710 if (!Cnt)
4711 return nullptr;
4712 }
4713 ExprResult Diff;
4714 QualType VarType = LCDecl->getType().getNonReferenceType();
4715 if (VarType->isIntegerType() || VarType->isPointerType() ||
4716 SemaRef.getLangOpts().CPlusPlus) {
4717 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004718 Expr *Upper = TestIsLessOp.getValue()
4719 ? Cnt
4720 : tryBuildCapture(SemaRef, UB, Captures).get();
4721 Expr *Lower = TestIsLessOp.getValue()
4722 ? tryBuildCapture(SemaRef, LB, Captures).get()
4723 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004724 if (!Upper || !Lower)
4725 return nullptr;
4726
4727 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4728
4729 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4730 // BuildBinOp already emitted error, this one is to point user to upper
4731 // and lower bound, and to tell what is passed to 'operator-'.
4732 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4733 << Upper->getSourceRange() << Lower->getSourceRange();
4734 return nullptr;
4735 }
4736 }
4737
4738 if (!Diff.isUsable())
4739 return nullptr;
4740
4741 // Parentheses (for dumping/debugging purposes only).
4742 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4743 if (!Diff.isUsable())
4744 return nullptr;
4745
4746 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4747 if (!NewStep.isUsable())
4748 return nullptr;
4749 // (Upper - Lower) / Step
4750 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4751 if (!Diff.isUsable())
4752 return nullptr;
4753
4754 return Diff.get();
4755}
4756
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004757/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004758struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004759 /// True if the condition operator is the strict compare operator (<, > or
4760 /// !=).
4761 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004762 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004763 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004764 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004765 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004766 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004767 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004768 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004769 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004770 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004771 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004772 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004773 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004774 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004775 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004776 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004777 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004778 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004779 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004780 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004781 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004782 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004783 SourceRange IncSrcRange;
4784};
4785
Alexey Bataev23b69422014-06-18 07:08:49 +00004786} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004787
Alexey Bataev9c821032015-04-30 04:23:23 +00004788void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4789 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4790 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004791 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4792 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004793 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00004794 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00004795 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004796 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4797 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004798 auto *VD = dyn_cast<VarDecl>(D);
4799 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004800 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004801 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00004802 } else {
4803 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4804 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004805 VD = cast<VarDecl>(Ref->getDecl());
4806 }
4807 }
4808 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00004809 const Decl *LD = DSAStack->getPossiblyLoopCunter();
4810 if (LD != D->getCanonicalDecl()) {
4811 DSAStack->resetPossibleLoopCounter();
4812 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4813 MarkDeclarationsReferencedInExpr(
4814 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4815 Var->getType().getNonLValueExprType(Context),
4816 ForLoc, /*RefersToCapture=*/true));
4817 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004818 }
4819 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004820 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004821 }
4822}
4823
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004824/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004825/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00004826static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00004827 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4828 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00004829 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4830 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00004831 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004832 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00004833 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004834 // OpenMP [2.6, Canonical Loop Form]
4835 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004836 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004837 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004838 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004839 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00004840 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00004841 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004842 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00004843 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4844 SemaRef.Diag(DSA.getConstructLoc(),
4845 diag::note_omp_collapse_ordered_expr)
4846 << 2 << CollapseLoopCountExpr->getSourceRange()
4847 << OrderedLoopCountExpr->getSourceRange();
4848 else if (CollapseLoopCountExpr)
4849 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4850 diag::note_omp_collapse_ordered_expr)
4851 << 0 << CollapseLoopCountExpr->getSourceRange();
4852 else
4853 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4854 diag::note_omp_collapse_ordered_expr)
4855 << 1 << OrderedLoopCountExpr->getSourceRange();
4856 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004857 return true;
4858 }
4859 assert(For->getBody());
4860
4861 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4862
4863 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004864 Stmt *Init = For->getInit();
4865 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004866 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004867
4868 bool HasErrors = false;
4869
4870 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004871 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4872 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004873
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004874 // OpenMP [2.6, Canonical Loop Form]
4875 // Var is one of the following:
4876 // A variable of signed or unsigned integer type.
4877 // For C++, a variable of a random access iterator type.
4878 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004879 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004880 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4881 !VarType->isPointerType() &&
4882 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004883 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004884 << SemaRef.getLangOpts().CPlusPlus;
4885 HasErrors = true;
4886 }
4887
4888 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4889 // a Construct
4890 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4891 // parallel for construct is (are) private.
4892 // The loop iteration variable in the associated for-loop of a simd
4893 // construct with just one associated for-loop is linear with a
4894 // constant-linear-step that is the increment of the associated for-loop.
4895 // Exclude loop var from the list of variables with implicitly defined data
4896 // sharing attributes.
4897 VarsWithImplicitDSA.erase(LCDecl);
4898
4899 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4900 // in a Construct, C/C++].
4901 // The loop iteration variable in the associated for-loop of a simd
4902 // construct with just one associated for-loop may be listed in a linear
4903 // clause with a constant-linear-step that is the increment of the
4904 // associated for-loop.
4905 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4906 // parallel for construct may be listed in a private or lastprivate clause.
4907 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4908 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4909 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00004910 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004911 isOpenMPSimdDirective(DKind)
4912 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4913 : OMPC_private;
4914 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4915 DVar.CKind != PredeterminedCKind) ||
4916 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4917 isOpenMPDistributeDirective(DKind)) &&
4918 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4919 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4920 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004921 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004922 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4923 << getOpenMPClauseName(PredeterminedCKind);
4924 if (DVar.RefExpr == nullptr)
4925 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00004926 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004927 HasErrors = true;
4928 } else if (LoopDeclRefExpr != nullptr) {
4929 // Make the loop iteration variable private (for worksharing constructs),
4930 // linear (for simd directives with the only one associated loop) or
4931 // lastprivate (for simd directives with several collapsed or ordered
4932 // loops).
4933 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00004934 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004935 }
4936
4937 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4938
4939 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004940 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004941
4942 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004943 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004944 }
4945
Alexey Bataeve3727102018-04-18 15:57:46 +00004946 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004947 return HasErrors;
4948
Alexander Musmana5f070a2014-10-01 06:03:56 +00004949 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004950 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00004951 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4952 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004953 DSA.getCurScope(),
4954 (isOpenMPWorksharingDirective(DKind) ||
4955 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4956 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00004957 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4958 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4959 ResultIterSpace.CounterInit = ISC.buildCounterInit();
4960 ResultIterSpace.CounterStep = ISC.buildCounterStep();
4961 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4962 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4963 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4964 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00004965 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004966
Alexey Bataev62dbb972015-04-22 11:59:37 +00004967 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4968 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004969 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004970 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004971 ResultIterSpace.CounterInit == nullptr ||
4972 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00004973 if (!HasErrors && DSA.isOrderedRegion()) {
4974 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4975 if (CurrentNestedLoopCount <
4976 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4977 DSA.getOrderedRegionParam().second->setLoopNumIterations(
4978 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4979 DSA.getOrderedRegionParam().second->setLoopCounter(
4980 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4981 }
4982 }
4983 for (auto &Pair : DSA.getDoacrossDependClauses()) {
4984 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4985 // Erroneous case - clause has some problems.
4986 continue;
4987 }
4988 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4989 Pair.second.size() <= CurrentNestedLoopCount) {
4990 // Erroneous case - clause has some problems.
4991 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4992 continue;
4993 }
4994 Expr *CntValue;
4995 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4996 CntValue = ISC.buildOrderedLoopData(
4997 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4998 Pair.first->getDependencyLoc());
4999 else
5000 CntValue = ISC.buildOrderedLoopData(
5001 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5002 Pair.first->getDependencyLoc(),
5003 Pair.second[CurrentNestedLoopCount].first,
5004 Pair.second[CurrentNestedLoopCount].second);
5005 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5006 }
5007 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005008
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005009 return HasErrors;
5010}
5011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005012/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005013static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005014buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005015 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005016 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005017 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005018 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005019 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005020 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005021 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005022 VarRef.get()->getType())) {
5023 NewStart = SemaRef.PerformImplicitConversion(
5024 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5025 /*AllowExplicit=*/true);
5026 if (!NewStart.isUsable())
5027 return ExprError();
5028 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005029
Alexey Bataeve3727102018-04-18 15:57:46 +00005030 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005031 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5032 return Init;
5033}
5034
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005035/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005036static ExprResult buildCounterUpdate(
5037 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5038 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5039 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005040 // Add parentheses (for debugging purposes only).
5041 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5042 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5043 !Step.isUsable())
5044 return ExprError();
5045
Alexey Bataev5a3af132016-03-29 08:58:54 +00005046 ExprResult NewStep = Step;
5047 if (Captures)
5048 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005049 if (NewStep.isInvalid())
5050 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005051 ExprResult Update =
5052 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005053 if (!Update.isUsable())
5054 return ExprError();
5055
Alexey Bataevc0214e02016-02-16 12:13:49 +00005056 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5057 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005058 ExprResult NewStart = Start;
5059 if (Captures)
5060 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005061 if (NewStart.isInvalid())
5062 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005063
Alexey Bataevc0214e02016-02-16 12:13:49 +00005064 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5065 ExprResult SavedUpdate = Update;
5066 ExprResult UpdateVal;
5067 if (VarRef.get()->getType()->isOverloadableType() ||
5068 NewStart.get()->getType()->isOverloadableType() ||
5069 Update.get()->getType()->isOverloadableType()) {
5070 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5071 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5072 Update =
5073 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5074 if (Update.isUsable()) {
5075 UpdateVal =
5076 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5077 VarRef.get(), SavedUpdate.get());
5078 if (UpdateVal.isUsable()) {
5079 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5080 UpdateVal.get());
5081 }
5082 }
5083 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5084 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005085
Alexey Bataevc0214e02016-02-16 12:13:49 +00005086 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5087 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5088 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5089 NewStart.get(), SavedUpdate.get());
5090 if (!Update.isUsable())
5091 return ExprError();
5092
Alexey Bataev11481f52016-02-17 10:29:05 +00005093 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5094 VarRef.get()->getType())) {
5095 Update = SemaRef.PerformImplicitConversion(
5096 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5097 if (!Update.isUsable())
5098 return ExprError();
5099 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005100
5101 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5102 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005103 return Update;
5104}
5105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005106/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005107/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005108static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005109 if (E == nullptr)
5110 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005111 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005112 QualType OldType = E->getType();
5113 unsigned HasBits = C.getTypeSize(OldType);
5114 if (HasBits >= Bits)
5115 return ExprResult(E);
5116 // OK to convert to signed, because new type has more bits than old.
5117 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5118 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5119 true);
5120}
5121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005122/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005123/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005124static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005125 if (E == nullptr)
5126 return false;
5127 llvm::APSInt Result;
5128 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5129 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5130 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005131}
5132
Alexey Bataev5a3af132016-03-29 08:58:54 +00005133/// Build preinits statement for the given declarations.
5134static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005135 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005136 if (!PreInits.empty()) {
5137 return new (Context) DeclStmt(
5138 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5139 SourceLocation(), SourceLocation());
5140 }
5141 return nullptr;
5142}
5143
5144/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005145static Stmt *
5146buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005147 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005148 if (!Captures.empty()) {
5149 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005150 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005151 PreInits.push_back(Pair.second->getDecl());
5152 return buildPreInits(Context, PreInits);
5153 }
5154 return nullptr;
5155}
5156
5157/// Build postupdate expression for the given list of postupdates expressions.
5158static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5159 Expr *PostUpdate = nullptr;
5160 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005161 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005162 Expr *ConvE = S.BuildCStyleCastExpr(
5163 E->getExprLoc(),
5164 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5165 E->getExprLoc(), E)
5166 .get();
5167 PostUpdate = PostUpdate
5168 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5169 PostUpdate, ConvE)
5170 .get()
5171 : ConvE;
5172 }
5173 }
5174 return PostUpdate;
5175}
5176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005177/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005178/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5179/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005180static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005181checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005182 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5183 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005184 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005185 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005186 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005187 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005188 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005189 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005190 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005191 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005192 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005193 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005194 if (OrderedLoopCountExpr) {
5195 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005196 Expr::EvalResult EVResult;
5197 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5198 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005199 if (Result.getLimitedValue() < NestedLoopCount) {
5200 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5201 diag::err_omp_wrong_ordered_loop_count)
5202 << OrderedLoopCountExpr->getSourceRange();
5203 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5204 diag::note_collapse_loop_count)
5205 << CollapseLoopCountExpr->getSourceRange();
5206 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005207 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005208 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005209 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005210 // This is helper routine for loop directives (e.g., 'for', 'simd',
5211 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005212 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005213 SmallVector<LoopIterationSpace, 4> IterSpaces(
5214 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005215 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005216 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005217 if (checkOpenMPIterationSpace(
5218 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5219 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5220 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5221 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005222 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005223 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005224 // OpenMP [2.8.1, simd construct, Restrictions]
5225 // All loops associated with the construct must be perfectly nested; that
5226 // is, there must be no intervening code nor any OpenMP directive between
5227 // any two loops.
5228 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005229 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005230 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5231 if (checkOpenMPIterationSpace(
5232 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5233 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5234 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5235 Captures))
5236 return 0;
5237 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5238 // Handle initialization of captured loop iterator variables.
5239 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5240 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5241 Captures[DRE] = DRE;
5242 }
5243 }
5244 // Move on to the next nested for loop, or to the loop body.
5245 // OpenMP [2.8.1, simd construct, Restrictions]
5246 // All loops associated with the construct must be perfectly nested; that
5247 // is, there must be no intervening code nor any OpenMP directive between
5248 // any two loops.
5249 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5250 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005251
Alexander Musmana5f070a2014-10-01 06:03:56 +00005252 Built.clear(/* size */ NestedLoopCount);
5253
5254 if (SemaRef.CurContext->isDependentContext())
5255 return NestedLoopCount;
5256
5257 // An example of what is generated for the following code:
5258 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005259 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005260 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005261 // for (k = 0; k < NK; ++k)
5262 // for (j = J0; j < NJ; j+=2) {
5263 // <loop body>
5264 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005265 //
5266 // We generate the code below.
5267 // Note: the loop body may be outlined in CodeGen.
5268 // Note: some counters may be C++ classes, operator- is used to find number of
5269 // iterations and operator+= to calculate counter value.
5270 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5271 // or i64 is currently supported).
5272 //
5273 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5274 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5275 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5276 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5277 // // similar updates for vars in clauses (e.g. 'linear')
5278 // <loop body (using local i and j)>
5279 // }
5280 // i = NI; // assign final values of counters
5281 // j = NJ;
5282 //
5283
5284 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5285 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005286 // Precondition tests if there is at least one iteration (all conditions are
5287 // true).
5288 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005289 Expr *N0 = IterSpaces[0].NumIterations;
5290 ExprResult LastIteration32 =
5291 widenIterationCount(/*Bits=*/32,
5292 SemaRef
5293 .PerformImplicitConversion(
5294 N0->IgnoreImpCasts(), N0->getType(),
5295 Sema::AA_Converting, /*AllowExplicit=*/true)
5296 .get(),
5297 SemaRef);
5298 ExprResult LastIteration64 = widenIterationCount(
5299 /*Bits=*/64,
5300 SemaRef
5301 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5302 Sema::AA_Converting,
5303 /*AllowExplicit=*/true)
5304 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005305 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005306
5307 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5308 return NestedLoopCount;
5309
Alexey Bataeve3727102018-04-18 15:57:46 +00005310 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005311 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5312
5313 Scope *CurScope = DSA.getCurScope();
5314 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005315 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005316 PreCond =
5317 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5318 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005319 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005320 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005321 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005322 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5323 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005324 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005325 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005326 SemaRef
5327 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5328 Sema::AA_Converting,
5329 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005330 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005331 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005332 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005333 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005334 SemaRef
5335 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5336 Sema::AA_Converting,
5337 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005338 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005339 }
5340
5341 // Choose either the 32-bit or 64-bit version.
5342 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005343 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5344 (LastIteration32.isUsable() &&
5345 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5346 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5347 fitsInto(
5348 /*Bits=*/32,
5349 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5350 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005351 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005352 QualType VType = LastIteration.get()->getType();
5353 QualType RealVType = VType;
5354 QualType StrideVType = VType;
5355 if (isOpenMPTaskLoopDirective(DKind)) {
5356 VType =
5357 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5358 StrideVType =
5359 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5360 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005361
5362 if (!LastIteration.isUsable())
5363 return 0;
5364
5365 // Save the number of iterations.
5366 ExprResult NumIterations = LastIteration;
5367 {
5368 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005369 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5370 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005371 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5372 if (!LastIteration.isUsable())
5373 return 0;
5374 }
5375
5376 // Calculate the last iteration number beforehand instead of doing this on
5377 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5378 llvm::APSInt Result;
5379 bool IsConstant =
5380 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5381 ExprResult CalcLastIteration;
5382 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005383 ExprResult SaveRef =
5384 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005385 LastIteration = SaveRef;
5386
5387 // Prepare SaveRef + 1.
5388 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005389 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005390 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5391 if (!NumIterations.isUsable())
5392 return 0;
5393 }
5394
5395 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5396
David Majnemer9d168222016-08-05 17:44:54 +00005397 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005398 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005399 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5400 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005401 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005402 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5403 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005404 SemaRef.AddInitializerToDecl(LBDecl,
5405 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5406 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005407
5408 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005409 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5410 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005411 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005412 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005413
5414 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5415 // This will be used to implement clause 'lastprivate'.
5416 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005417 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5418 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005419 SemaRef.AddInitializerToDecl(ILDecl,
5420 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5421 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005422
5423 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005424 VarDecl *STDecl =
5425 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5426 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005427 SemaRef.AddInitializerToDecl(STDecl,
5428 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5429 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005430
5431 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005432 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005433 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5434 UB.get(), LastIteration.get());
5435 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005436 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5437 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005438 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5439 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005440 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005441
5442 // If we have a combined directive that combines 'distribute', 'for' or
5443 // 'simd' we need to be able to access the bounds of the schedule of the
5444 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5445 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5446 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005447 // Lower bound variable, initialized with zero.
5448 VarDecl *CombLBDecl =
5449 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5450 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5451 SemaRef.AddInitializerToDecl(
5452 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5453 /*DirectInit*/ false);
5454
5455 // Upper bound variable, initialized with last iteration number.
5456 VarDecl *CombUBDecl =
5457 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5458 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5459 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5460 /*DirectInit*/ false);
5461
5462 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5463 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5464 ExprResult CombCondOp =
5465 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5466 LastIteration.get(), CombUB.get());
5467 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5468 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005469 CombEUB =
5470 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005471
Alexey Bataeve3727102018-04-18 15:57:46 +00005472 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005473 // We expect to have at least 2 more parameters than the 'parallel'
5474 // directive does - the lower and upper bounds of the previous schedule.
5475 assert(CD->getNumParams() >= 4 &&
5476 "Unexpected number of parameters in loop combined directive");
5477
5478 // Set the proper type for the bounds given what we learned from the
5479 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005480 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5481 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005482
5483 // Previous lower and upper bounds are obtained from the region
5484 // parameters.
5485 PrevLB =
5486 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5487 PrevUB =
5488 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5489 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005490 }
5491
5492 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005493 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005494 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005495 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005496 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5497 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005498 Expr *RHS =
5499 (isOpenMPWorksharingDirective(DKind) ||
5500 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5501 ? LB.get()
5502 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005503 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005504 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005505
5506 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5507 Expr *CombRHS =
5508 (isOpenMPWorksharingDirective(DKind) ||
5509 isOpenMPTaskLoopDirective(DKind) ||
5510 isOpenMPDistributeDirective(DKind))
5511 ? CombLB.get()
5512 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5513 CombInit =
5514 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005515 CombInit =
5516 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005517 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005518 }
5519
Alexey Bataev316ccf62019-01-29 18:51:58 +00005520 bool UseStrictCompare =
5521 RealVType->hasUnsignedIntegerRepresentation() &&
5522 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5523 return LIS.IsStrictCompare;
5524 });
5525 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5526 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005527 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005528 Expr *BoundUB = UB.get();
5529 if (UseStrictCompare) {
5530 BoundUB =
5531 SemaRef
5532 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5533 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5534 .get();
5535 BoundUB =
5536 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5537 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005538 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005539 (isOpenMPWorksharingDirective(DKind) ||
5540 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005541 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5542 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5543 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005544 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5545 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005546 ExprResult CombDistCond;
5547 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005548 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5549 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005550 }
5551
Carlo Bertolliffafe102017-04-20 00:39:39 +00005552 ExprResult CombCond;
5553 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005554 Expr *BoundCombUB = CombUB.get();
5555 if (UseStrictCompare) {
5556 BoundCombUB =
5557 SemaRef
5558 .BuildBinOp(
5559 CurScope, CondLoc, BO_Add, BoundCombUB,
5560 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5561 .get();
5562 BoundCombUB =
5563 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5564 .get();
5565 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005566 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005567 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5568 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005569 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005570 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005571 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005572 ExprResult Inc =
5573 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5574 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5575 if (!Inc.isUsable())
5576 return 0;
5577 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005578 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005579 if (!Inc.isUsable())
5580 return 0;
5581
5582 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5583 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005584 // In combined construct, add combined version that use CombLB and CombUB
5585 // base variables for the update
5586 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005587 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5588 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005589 // LB + ST
5590 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5591 if (!NextLB.isUsable())
5592 return 0;
5593 // LB = LB + ST
5594 NextLB =
5595 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005596 NextLB =
5597 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005598 if (!NextLB.isUsable())
5599 return 0;
5600 // UB + ST
5601 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5602 if (!NextUB.isUsable())
5603 return 0;
5604 // UB = UB + ST
5605 NextUB =
5606 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005607 NextUB =
5608 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005609 if (!NextUB.isUsable())
5610 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005611 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5612 CombNextLB =
5613 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5614 if (!NextLB.isUsable())
5615 return 0;
5616 // LB = LB + ST
5617 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5618 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005619 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5620 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005621 if (!CombNextLB.isUsable())
5622 return 0;
5623 // UB + ST
5624 CombNextUB =
5625 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5626 if (!CombNextUB.isUsable())
5627 return 0;
5628 // UB = UB + ST
5629 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5630 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005631 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5632 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005633 if (!CombNextUB.isUsable())
5634 return 0;
5635 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005636 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005637
Carlo Bertolliffafe102017-04-20 00:39:39 +00005638 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005639 // directive with for as IV = IV + ST; ensure upper bound expression based
5640 // on PrevUB instead of NumIterations - used to implement 'for' when found
5641 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005642 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005643 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005644 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005645 DistCond = SemaRef.BuildBinOp(
5646 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005647 assert(DistCond.isUsable() && "distribute cond expr was not built");
5648
5649 DistInc =
5650 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5651 assert(DistInc.isUsable() && "distribute inc expr was not built");
5652 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5653 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005654 DistInc =
5655 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005656 assert(DistInc.isUsable() && "distribute inc expr was not built");
5657
5658 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5659 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005660 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005661 ExprResult IsUBGreater =
5662 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5663 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5664 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5665 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5666 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005667 PrevEUB =
5668 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005669
Alexey Bataev316ccf62019-01-29 18:51:58 +00005670 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5671 // parallel for is in combination with a distribute directive with
5672 // schedule(static, 1)
5673 Expr *BoundPrevUB = PrevUB.get();
5674 if (UseStrictCompare) {
5675 BoundPrevUB =
5676 SemaRef
5677 .BuildBinOp(
5678 CurScope, CondLoc, BO_Add, BoundPrevUB,
5679 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5680 .get();
5681 BoundPrevUB =
5682 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5683 .get();
5684 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005685 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005686 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5687 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005688 }
5689
Alexander Musmana5f070a2014-10-01 06:03:56 +00005690 // Build updates and final values of the loop counters.
5691 bool HasErrors = false;
5692 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005693 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005694 Built.Updates.resize(NestedLoopCount);
5695 Built.Finals.resize(NestedLoopCount);
5696 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005697 // We implement the following algorithm for obtaining the
5698 // original loop iteration variable values based on the
5699 // value of the collapsed loop iteration variable IV.
5700 //
5701 // Let n+1 be the number of collapsed loops in the nest.
5702 // Iteration variables (I0, I1, .... In)
5703 // Iteration counts (N0, N1, ... Nn)
5704 //
5705 // Acc = IV;
5706 //
5707 // To compute Ik for loop k, 0 <= k <= n, generate:
5708 // Prod = N(k+1) * N(k+2) * ... * Nn;
5709 // Ik = Acc / Prod;
5710 // Acc -= Ik * Prod;
5711 //
5712 ExprResult Acc = IV;
5713 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005714 LoopIterationSpace &IS = IterSpaces[Cnt];
5715 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005716 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005717
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005718 // Compute prod
5719 ExprResult Prod =
5720 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5721 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5722 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5723 IterSpaces[K].NumIterations);
5724
5725 // Iter = Acc / Prod
5726 // If there is at least one more inner loop to avoid
5727 // multiplication by 1.
5728 if (Cnt + 1 < NestedLoopCount)
5729 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5730 Acc.get(), Prod.get());
5731 else
5732 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005733 if (!Iter.isUsable()) {
5734 HasErrors = true;
5735 break;
5736 }
5737
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005738 // Update Acc:
5739 // Acc -= Iter * Prod
5740 // Check if there is at least one more inner loop to avoid
5741 // multiplication by 1.
5742 if (Cnt + 1 < NestedLoopCount)
5743 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5744 Iter.get(), Prod.get());
5745 else
5746 Prod = Iter;
5747 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5748 Acc.get(), Prod.get());
5749
Alexey Bataev39f915b82015-05-08 10:41:21 +00005750 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005751 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005752 DeclRefExpr *CounterVar = buildDeclRefExpr(
5753 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5754 /*RefersToCapture=*/true);
5755 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005756 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005757 if (!Init.isUsable()) {
5758 HasErrors = true;
5759 break;
5760 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005761 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005762 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5763 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005764 if (!Update.isUsable()) {
5765 HasErrors = true;
5766 break;
5767 }
5768
5769 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005770 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005771 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005772 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005773 if (!Final.isUsable()) {
5774 HasErrors = true;
5775 break;
5776 }
5777
Alexander Musmana5f070a2014-10-01 06:03:56 +00005778 if (!Update.isUsable() || !Final.isUsable()) {
5779 HasErrors = true;
5780 break;
5781 }
5782 // Save results
5783 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005784 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005785 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005786 Built.Updates[Cnt] = Update.get();
5787 Built.Finals[Cnt] = Final.get();
5788 }
5789 }
5790
5791 if (HasErrors)
5792 return 0;
5793
5794 // Save results
5795 Built.IterationVarRef = IV.get();
5796 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005797 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005798 Built.CalcLastIteration = SemaRef
5799 .ActOnFinishFullExpr(CalcLastIteration.get(),
5800 /*DiscardedValue*/ false)
5801 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005802 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005803 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005804 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005805 Built.Init = Init.get();
5806 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005807 Built.LB = LB.get();
5808 Built.UB = UB.get();
5809 Built.IL = IL.get();
5810 Built.ST = ST.get();
5811 Built.EUB = EUB.get();
5812 Built.NLB = NextLB.get();
5813 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005814 Built.PrevLB = PrevLB.get();
5815 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005816 Built.DistInc = DistInc.get();
5817 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005818 Built.DistCombinedFields.LB = CombLB.get();
5819 Built.DistCombinedFields.UB = CombUB.get();
5820 Built.DistCombinedFields.EUB = CombEUB.get();
5821 Built.DistCombinedFields.Init = CombInit.get();
5822 Built.DistCombinedFields.Cond = CombCond.get();
5823 Built.DistCombinedFields.NLB = CombNextLB.get();
5824 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005825 Built.DistCombinedFields.DistCond = CombDistCond.get();
5826 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005827
Alexey Bataevabfc0692014-06-25 06:52:00 +00005828 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005829}
5830
Alexey Bataev10e775f2015-07-30 11:36:16 +00005831static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005832 auto CollapseClauses =
5833 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5834 if (CollapseClauses.begin() != CollapseClauses.end())
5835 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005836 return nullptr;
5837}
5838
Alexey Bataev10e775f2015-07-30 11:36:16 +00005839static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005840 auto OrderedClauses =
5841 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5842 if (OrderedClauses.begin() != OrderedClauses.end())
5843 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005844 return nullptr;
5845}
5846
Kelvin Lic5609492016-07-15 04:39:07 +00005847static bool checkSimdlenSafelenSpecified(Sema &S,
5848 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005849 const OMPSafelenClause *Safelen = nullptr;
5850 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00005851
Alexey Bataeve3727102018-04-18 15:57:46 +00005852 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00005853 if (Clause->getClauseKind() == OMPC_safelen)
5854 Safelen = cast<OMPSafelenClause>(Clause);
5855 else if (Clause->getClauseKind() == OMPC_simdlen)
5856 Simdlen = cast<OMPSimdlenClause>(Clause);
5857 if (Safelen && Simdlen)
5858 break;
5859 }
5860
5861 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005862 const Expr *SimdlenLength = Simdlen->getSimdlen();
5863 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00005864 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5865 SimdlenLength->isInstantiationDependent() ||
5866 SimdlenLength->containsUnexpandedParameterPack())
5867 return false;
5868 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5869 SafelenLength->isInstantiationDependent() ||
5870 SafelenLength->containsUnexpandedParameterPack())
5871 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005872 Expr::EvalResult SimdlenResult, SafelenResult;
5873 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5874 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5875 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5876 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00005877 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5878 // If both simdlen and safelen clauses are specified, the value of the
5879 // simdlen parameter must be less than or equal to the value of the safelen
5880 // parameter.
5881 if (SimdlenRes > SafelenRes) {
5882 S.Diag(SimdlenLength->getExprLoc(),
5883 diag::err_omp_wrong_simdlen_safelen_values)
5884 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5885 return true;
5886 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005887 }
5888 return false;
5889}
5890
Alexey Bataeve3727102018-04-18 15:57:46 +00005891StmtResult
5892Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5893 SourceLocation StartLoc, SourceLocation EndLoc,
5894 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005895 if (!AStmt)
5896 return StmtError();
5897
5898 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005899 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005900 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5901 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005902 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005903 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5904 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005905 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005906 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005907
Alexander Musmana5f070a2014-10-01 06:03:56 +00005908 assert((CurContext->isDependentContext() || B.builtAll()) &&
5909 "omp simd loop exprs were not built");
5910
Alexander Musman3276a272015-03-21 10:12:56 +00005911 if (!CurContext->isDependentContext()) {
5912 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005913 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005914 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005915 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005916 B.NumIterations, *this, CurScope,
5917 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005918 return StmtError();
5919 }
5920 }
5921
Kelvin Lic5609492016-07-15 04:39:07 +00005922 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005923 return StmtError();
5924
Reid Kleckner87a31802018-03-12 21:43:02 +00005925 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005926 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5927 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005928}
5929
Alexey Bataeve3727102018-04-18 15:57:46 +00005930StmtResult
5931Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5932 SourceLocation StartLoc, SourceLocation EndLoc,
5933 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005934 if (!AStmt)
5935 return StmtError();
5936
5937 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005938 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005939 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5940 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005941 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005942 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5943 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005944 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005945 return StmtError();
5946
Alexander Musmana5f070a2014-10-01 06:03:56 +00005947 assert((CurContext->isDependentContext() || B.builtAll()) &&
5948 "omp for loop exprs were not built");
5949
Alexey Bataev54acd402015-08-04 11:18:19 +00005950 if (!CurContext->isDependentContext()) {
5951 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005952 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005953 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005954 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005955 B.NumIterations, *this, CurScope,
5956 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005957 return StmtError();
5958 }
5959 }
5960
Reid Kleckner87a31802018-03-12 21:43:02 +00005961 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005962 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005963 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005964}
5965
Alexander Musmanf82886e2014-09-18 05:12:34 +00005966StmtResult Sema::ActOnOpenMPForSimdDirective(
5967 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00005968 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005969 if (!AStmt)
5970 return StmtError();
5971
5972 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005973 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005974 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5975 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005976 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00005977 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00005978 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5979 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005980 if (NestedLoopCount == 0)
5981 return StmtError();
5982
Alexander Musmanc6388682014-12-15 07:07:06 +00005983 assert((CurContext->isDependentContext() || B.builtAll()) &&
5984 "omp for simd loop exprs were not built");
5985
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005986 if (!CurContext->isDependentContext()) {
5987 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005988 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005989 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005990 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005991 B.NumIterations, *this, CurScope,
5992 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005993 return StmtError();
5994 }
5995 }
5996
Kelvin Lic5609492016-07-15 04:39:07 +00005997 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005998 return StmtError();
5999
Reid Kleckner87a31802018-03-12 21:43:02 +00006000 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006001 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6002 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006003}
6004
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006005StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6006 Stmt *AStmt,
6007 SourceLocation StartLoc,
6008 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006009 if (!AStmt)
6010 return StmtError();
6011
6012 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006013 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006014 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006015 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006016 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006017 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006018 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006019 return StmtError();
6020 // All associated statements must be '#pragma omp section' except for
6021 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006022 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006023 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6024 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006025 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006026 diag::err_omp_sections_substmt_not_section);
6027 return StmtError();
6028 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006029 cast<OMPSectionDirective>(SectionStmt)
6030 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006031 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006032 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006033 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006034 return StmtError();
6035 }
6036
Reid Kleckner87a31802018-03-12 21:43:02 +00006037 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006038
Alexey Bataev25e5b442015-09-15 12:52:43 +00006039 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6040 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006041}
6042
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006043StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6044 SourceLocation StartLoc,
6045 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006046 if (!AStmt)
6047 return StmtError();
6048
6049 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006050
Reid Kleckner87a31802018-03-12 21:43:02 +00006051 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006052 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006053
Alexey Bataev25e5b442015-09-15 12:52:43 +00006054 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6055 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006056}
6057
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006058StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6059 Stmt *AStmt,
6060 SourceLocation StartLoc,
6061 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006062 if (!AStmt)
6063 return StmtError();
6064
6065 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006066
Reid Kleckner87a31802018-03-12 21:43:02 +00006067 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006068
Alexey Bataev3255bf32015-01-19 05:20:46 +00006069 // OpenMP [2.7.3, single Construct, Restrictions]
6070 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006071 const OMPClause *Nowait = nullptr;
6072 const OMPClause *Copyprivate = nullptr;
6073 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006074 if (Clause->getClauseKind() == OMPC_nowait)
6075 Nowait = Clause;
6076 else if (Clause->getClauseKind() == OMPC_copyprivate)
6077 Copyprivate = Clause;
6078 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006079 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006080 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006081 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006082 return StmtError();
6083 }
6084 }
6085
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006086 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6087}
6088
Alexander Musman80c22892014-07-17 08:54:58 +00006089StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6090 SourceLocation StartLoc,
6091 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006092 if (!AStmt)
6093 return StmtError();
6094
6095 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006096
Reid Kleckner87a31802018-03-12 21:43:02 +00006097 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006098
6099 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6100}
6101
Alexey Bataev28c75412015-12-15 08:19:24 +00006102StmtResult Sema::ActOnOpenMPCriticalDirective(
6103 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6104 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006105 if (!AStmt)
6106 return StmtError();
6107
6108 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006109
Alexey Bataev28c75412015-12-15 08:19:24 +00006110 bool ErrorFound = false;
6111 llvm::APSInt Hint;
6112 SourceLocation HintLoc;
6113 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006114 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006115 if (C->getClauseKind() == OMPC_hint) {
6116 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006117 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006118 ErrorFound = true;
6119 }
6120 Expr *E = cast<OMPHintClause>(C)->getHint();
6121 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006122 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006123 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006124 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006125 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006126 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006127 }
6128 }
6129 }
6130 if (ErrorFound)
6131 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006132 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006133 if (Pair.first && DirName.getName() && !DependentHint) {
6134 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6135 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006136 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006137 Diag(HintLoc, diag::note_omp_critical_hint_here)
6138 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006139 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006140 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006141 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006142 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006143 << 1
6144 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6145 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006146 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006147 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006148 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006149 }
6150 }
6151
Reid Kleckner87a31802018-03-12 21:43:02 +00006152 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006153
Alexey Bataev28c75412015-12-15 08:19:24 +00006154 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6155 Clauses, AStmt);
6156 if (!Pair.first && DirName.getName() && !DependentHint)
6157 DSAStack->addCriticalWithHint(Dir, Hint);
6158 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006159}
6160
Alexey Bataev4acb8592014-07-07 13:01:15 +00006161StmtResult Sema::ActOnOpenMPParallelForDirective(
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
Alexey Bataeve3727102018-04-18 15:57:46 +00006167 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006168 // 1.2.2 OpenMP Language Terminology
6169 // Structured block - An executable statement with a single entry at the
6170 // top and a single exit at the bottom.
6171 // The point of exit cannot be a branch out of the structured block.
6172 // longjmp() and throw() must not violate the entry/exit criteria.
6173 CS->getCapturedDecl()->setNothrow();
6174
Alexander Musmanc6388682014-12-15 07:07:06 +00006175 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006176 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6177 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006178 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006179 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006180 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6181 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006182 if (NestedLoopCount == 0)
6183 return StmtError();
6184
Alexander Musmana5f070a2014-10-01 06:03:56 +00006185 assert((CurContext->isDependentContext() || B.builtAll()) &&
6186 "omp parallel for loop exprs were not built");
6187
Alexey Bataev54acd402015-08-04 11:18:19 +00006188 if (!CurContext->isDependentContext()) {
6189 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006190 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006191 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006192 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006193 B.NumIterations, *this, CurScope,
6194 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006195 return StmtError();
6196 }
6197 }
6198
Reid Kleckner87a31802018-03-12 21:43:02 +00006199 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006200 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006201 NestedLoopCount, Clauses, AStmt, B,
6202 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006203}
6204
Alexander Musmane4e893b2014-09-23 09:33:00 +00006205StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6206 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006207 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006208 if (!AStmt)
6209 return StmtError();
6210
Alexey Bataeve3727102018-04-18 15:57:46 +00006211 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006212 // 1.2.2 OpenMP Language Terminology
6213 // Structured block - An executable statement with a single entry at the
6214 // top and a single exit at the bottom.
6215 // The point of exit cannot be a branch out of the structured block.
6216 // longjmp() and throw() must not violate the entry/exit criteria.
6217 CS->getCapturedDecl()->setNothrow();
6218
Alexander Musmanc6388682014-12-15 07:07:06 +00006219 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006220 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6221 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006222 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006223 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006224 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6225 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006226 if (NestedLoopCount == 0)
6227 return StmtError();
6228
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006229 if (!CurContext->isDependentContext()) {
6230 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006231 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006232 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006233 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006234 B.NumIterations, *this, CurScope,
6235 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006236 return StmtError();
6237 }
6238 }
6239
Kelvin Lic5609492016-07-15 04:39:07 +00006240 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006241 return StmtError();
6242
Reid Kleckner87a31802018-03-12 21:43:02 +00006243 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006244 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006245 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006246}
6247
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006248StmtResult
6249Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6250 Stmt *AStmt, SourceLocation StartLoc,
6251 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006252 if (!AStmt)
6253 return StmtError();
6254
6255 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006256 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006257 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006258 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006259 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006260 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006261 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006262 return StmtError();
6263 // All associated statements must be '#pragma omp section' except for
6264 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006265 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006266 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6267 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006268 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006269 diag::err_omp_parallel_sections_substmt_not_section);
6270 return StmtError();
6271 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006272 cast<OMPSectionDirective>(SectionStmt)
6273 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006274 }
6275 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006276 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006277 diag::err_omp_parallel_sections_not_compound_stmt);
6278 return StmtError();
6279 }
6280
Reid Kleckner87a31802018-03-12 21:43:02 +00006281 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006282
Alexey Bataev25e5b442015-09-15 12:52:43 +00006283 return OMPParallelSectionsDirective::Create(
6284 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006285}
6286
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006287StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6288 Stmt *AStmt, SourceLocation StartLoc,
6289 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006290 if (!AStmt)
6291 return StmtError();
6292
David Majnemer9d168222016-08-05 17:44:54 +00006293 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006294 // 1.2.2 OpenMP Language Terminology
6295 // Structured block - An executable statement with a single entry at the
6296 // top and a single exit at the bottom.
6297 // The point of exit cannot be a branch out of the structured block.
6298 // longjmp() and throw() must not violate the entry/exit criteria.
6299 CS->getCapturedDecl()->setNothrow();
6300
Reid Kleckner87a31802018-03-12 21:43:02 +00006301 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006302
Alexey Bataev25e5b442015-09-15 12:52:43 +00006303 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6304 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006305}
6306
Alexey Bataev68446b72014-07-18 07:47:19 +00006307StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6308 SourceLocation EndLoc) {
6309 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6310}
6311
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006312StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6313 SourceLocation EndLoc) {
6314 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6315}
6316
Alexey Bataev2df347a2014-07-18 10:17:07 +00006317StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6318 SourceLocation EndLoc) {
6319 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6320}
6321
Alexey Bataev169d96a2017-07-18 20:17:46 +00006322StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6323 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006324 SourceLocation StartLoc,
6325 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006326 if (!AStmt)
6327 return StmtError();
6328
6329 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006330
Reid Kleckner87a31802018-03-12 21:43:02 +00006331 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006332
Alexey Bataev169d96a2017-07-18 20:17:46 +00006333 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006334 AStmt,
6335 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006336}
6337
Alexey Bataev6125da92014-07-21 11:26:11 +00006338StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6339 SourceLocation StartLoc,
6340 SourceLocation EndLoc) {
6341 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6342 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6343}
6344
Alexey Bataev346265e2015-09-25 10:37:12 +00006345StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6346 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006347 SourceLocation StartLoc,
6348 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006349 const OMPClause *DependFound = nullptr;
6350 const OMPClause *DependSourceClause = nullptr;
6351 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006352 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006353 const OMPThreadsClause *TC = nullptr;
6354 const OMPSIMDClause *SC = nullptr;
6355 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006356 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6357 DependFound = C;
6358 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6359 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006360 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006361 << getOpenMPDirectiveName(OMPD_ordered)
6362 << getOpenMPClauseName(OMPC_depend) << 2;
6363 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006364 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006365 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006366 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006367 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006368 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006369 << 0;
6370 ErrorFound = true;
6371 }
6372 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6373 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006374 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006375 << 1;
6376 ErrorFound = true;
6377 }
6378 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006379 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006380 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006381 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006382 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006383 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006384 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006385 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006386 if (!ErrorFound && !SC &&
6387 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006388 // OpenMP [2.8.1,simd Construct, Restrictions]
6389 // An ordered construct with the simd clause is the only OpenMP construct
6390 // that can appear in the simd region.
6391 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006392 ErrorFound = true;
6393 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006394 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006395 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6396 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006397 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006398 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006399 diag::err_omp_ordered_directive_without_param);
6400 ErrorFound = true;
6401 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006402 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006403 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006404 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6405 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006406 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006407 ErrorFound = true;
6408 }
6409 }
6410 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006411 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006412
6413 if (AStmt) {
6414 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6415
Reid Kleckner87a31802018-03-12 21:43:02 +00006416 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006417 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006418
6419 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006420}
6421
Alexey Bataev1d160b12015-03-13 12:27:31 +00006422namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006423/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006424/// construct.
6425class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006426 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006427 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006428 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006429 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006430 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006431 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006432 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006433 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006434 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006435 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006436 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006437 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006438 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006439 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006440 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006441 /// expression.
6442 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006443 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006444 /// part.
6445 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006446 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006447 NoError
6448 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006449 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006450 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006451 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006452 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006453 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006454 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006455 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006456 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006457 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006458 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6459 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6460 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006461 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006462 /// important for non-associative operations.
6463 bool IsXLHSInRHSPart;
6464 BinaryOperatorKind Op;
6465 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006466 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006467 /// if it is a prefix unary operation.
6468 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006469
6470public:
6471 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006472 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006473 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006474 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006475 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006476 /// expression. If DiagId and NoteId == 0, then only check is performed
6477 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006478 /// \param DiagId Diagnostic which should be emitted if error is found.
6479 /// \param NoteId Diagnostic note for the main error message.
6480 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006481 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006482 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006483 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006484 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006485 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006486 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006487 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6488 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6489 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006490 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006491 /// false otherwise.
6492 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6493
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006494 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006495 /// if it is a prefix unary operation.
6496 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6497
Alexey Bataev1d160b12015-03-13 12:27:31 +00006498private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006499 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6500 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006501};
6502} // namespace
6503
6504bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6505 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6506 ExprAnalysisErrorCode ErrorFound = NoError;
6507 SourceLocation ErrorLoc, NoteLoc;
6508 SourceRange ErrorRange, NoteRange;
6509 // Allowed constructs are:
6510 // x = x binop expr;
6511 // x = expr binop x;
6512 if (AtomicBinOp->getOpcode() == BO_Assign) {
6513 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006514 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006515 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6516 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6517 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6518 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006519 Op = AtomicInnerBinOp->getOpcode();
6520 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006521 Expr *LHS = AtomicInnerBinOp->getLHS();
6522 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006523 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6524 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6525 /*Canonical=*/true);
6526 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6527 /*Canonical=*/true);
6528 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6529 /*Canonical=*/true);
6530 if (XId == LHSId) {
6531 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006532 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006533 } else if (XId == RHSId) {
6534 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006535 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006536 } else {
6537 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6538 ErrorRange = AtomicInnerBinOp->getSourceRange();
6539 NoteLoc = X->getExprLoc();
6540 NoteRange = X->getSourceRange();
6541 ErrorFound = NotAnUpdateExpression;
6542 }
6543 } else {
6544 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6545 ErrorRange = AtomicInnerBinOp->getSourceRange();
6546 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6547 NoteRange = SourceRange(NoteLoc, NoteLoc);
6548 ErrorFound = NotABinaryOperator;
6549 }
6550 } else {
6551 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6552 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6553 ErrorFound = NotABinaryExpression;
6554 }
6555 } else {
6556 ErrorLoc = AtomicBinOp->getExprLoc();
6557 ErrorRange = AtomicBinOp->getSourceRange();
6558 NoteLoc = AtomicBinOp->getOperatorLoc();
6559 NoteRange = SourceRange(NoteLoc, NoteLoc);
6560 ErrorFound = NotAnAssignmentOp;
6561 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006562 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006563 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6564 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6565 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006566 }
6567 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006568 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006569 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006570}
6571
6572bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6573 unsigned NoteId) {
6574 ExprAnalysisErrorCode ErrorFound = NoError;
6575 SourceLocation ErrorLoc, NoteLoc;
6576 SourceRange ErrorRange, NoteRange;
6577 // Allowed constructs are:
6578 // x++;
6579 // x--;
6580 // ++x;
6581 // --x;
6582 // x binop= expr;
6583 // x = x binop expr;
6584 // x = expr binop x;
6585 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6586 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6587 if (AtomicBody->getType()->isScalarType() ||
6588 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006589 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006590 AtomicBody->IgnoreParenImpCasts())) {
6591 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006592 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006593 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006594 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006595 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006596 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006597 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006598 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6599 AtomicBody->IgnoreParenImpCasts())) {
6600 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006601 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006602 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006603 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006604 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006605 // Check for Unary Operation
6606 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006607 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006608 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6609 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006610 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006611 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6612 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006613 } else {
6614 ErrorFound = NotAnUnaryIncDecExpression;
6615 ErrorLoc = AtomicUnaryOp->getExprLoc();
6616 ErrorRange = AtomicUnaryOp->getSourceRange();
6617 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6618 NoteRange = SourceRange(NoteLoc, NoteLoc);
6619 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006620 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006621 ErrorFound = NotABinaryOrUnaryExpression;
6622 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6623 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6624 }
6625 } else {
6626 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006627 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006628 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6629 }
6630 } else {
6631 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006632 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006633 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6634 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006635 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006636 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6637 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6638 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006639 }
6640 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006641 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006642 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006643 // Build an update expression of form 'OpaqueValueExpr(x) binop
6644 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6645 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6646 auto *OVEX = new (SemaRef.getASTContext())
6647 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6648 auto *OVEExpr = new (SemaRef.getASTContext())
6649 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006650 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006651 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6652 IsXLHSInRHSPart ? OVEExpr : OVEX);
6653 if (Update.isInvalid())
6654 return true;
6655 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6656 Sema::AA_Casting);
6657 if (Update.isInvalid())
6658 return true;
6659 UpdateExpr = Update.get();
6660 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006661 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006662}
6663
Alexey Bataev0162e452014-07-22 10:10:35 +00006664StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6665 Stmt *AStmt,
6666 SourceLocation StartLoc,
6667 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006668 if (!AStmt)
6669 return StmtError();
6670
David Majnemer9d168222016-08-05 17:44:54 +00006671 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006672 // 1.2.2 OpenMP Language Terminology
6673 // Structured block - An executable statement with a single entry at the
6674 // top and a single exit at the bottom.
6675 // The point of exit cannot be a branch out of the structured block.
6676 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006677 OpenMPClauseKind AtomicKind = OMPC_unknown;
6678 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006679 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006680 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006681 C->getClauseKind() == OMPC_update ||
6682 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006683 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006684 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006685 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006686 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6687 << getOpenMPClauseName(AtomicKind);
6688 } else {
6689 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006690 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006691 }
6692 }
6693 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006694
Alexey Bataeve3727102018-04-18 15:57:46 +00006695 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006696 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6697 Body = EWC->getSubExpr();
6698
Alexey Bataev62cec442014-11-18 10:14:22 +00006699 Expr *X = nullptr;
6700 Expr *V = nullptr;
6701 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006702 Expr *UE = nullptr;
6703 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006704 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006705 // OpenMP [2.12.6, atomic Construct]
6706 // In the next expressions:
6707 // * x and v (as applicable) are both l-value expressions with scalar type.
6708 // * During the execution of an atomic region, multiple syntactic
6709 // occurrences of x must designate the same storage location.
6710 // * Neither of v and expr (as applicable) may access the storage location
6711 // designated by x.
6712 // * Neither of x and expr (as applicable) may access the storage location
6713 // designated by v.
6714 // * expr is an expression with scalar type.
6715 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6716 // * binop, binop=, ++, and -- are not overloaded operators.
6717 // * The expression x binop expr must be numerically equivalent to x binop
6718 // (expr). This requirement is satisfied if the operators in expr have
6719 // precedence greater than binop, or by using parentheses around expr or
6720 // subexpressions of expr.
6721 // * The expression expr binop x must be numerically equivalent to (expr)
6722 // binop x. This requirement is satisfied if the operators in expr have
6723 // precedence equal to or greater than binop, or by using parentheses around
6724 // expr or subexpressions of expr.
6725 // * For forms that allow multiple occurrences of x, the number of times
6726 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006727 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006728 enum {
6729 NotAnExpression,
6730 NotAnAssignmentOp,
6731 NotAScalarType,
6732 NotAnLValue,
6733 NoError
6734 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006735 SourceLocation ErrorLoc, NoteLoc;
6736 SourceRange ErrorRange, NoteRange;
6737 // If clause is read:
6738 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006739 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6740 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006741 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6742 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6743 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6744 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6745 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6746 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6747 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006748 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006749 ErrorFound = NotAnLValue;
6750 ErrorLoc = AtomicBinOp->getExprLoc();
6751 ErrorRange = AtomicBinOp->getSourceRange();
6752 NoteLoc = NotLValueExpr->getExprLoc();
6753 NoteRange = NotLValueExpr->getSourceRange();
6754 }
6755 } else if (!X->isInstantiationDependent() ||
6756 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006757 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006758 (X->isInstantiationDependent() || X->getType()->isScalarType())
6759 ? V
6760 : X;
6761 ErrorFound = NotAScalarType;
6762 ErrorLoc = AtomicBinOp->getExprLoc();
6763 ErrorRange = AtomicBinOp->getSourceRange();
6764 NoteLoc = NotScalarExpr->getExprLoc();
6765 NoteRange = NotScalarExpr->getSourceRange();
6766 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006767 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006768 ErrorFound = NotAnAssignmentOp;
6769 ErrorLoc = AtomicBody->getExprLoc();
6770 ErrorRange = AtomicBody->getSourceRange();
6771 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6772 : AtomicBody->getExprLoc();
6773 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6774 : AtomicBody->getSourceRange();
6775 }
6776 } else {
6777 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006778 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006779 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006780 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006781 if (ErrorFound != NoError) {
6782 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6783 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006784 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6785 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006786 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006787 }
6788 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00006789 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006790 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006791 enum {
6792 NotAnExpression,
6793 NotAnAssignmentOp,
6794 NotAScalarType,
6795 NotAnLValue,
6796 NoError
6797 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006798 SourceLocation ErrorLoc, NoteLoc;
6799 SourceRange ErrorRange, NoteRange;
6800 // If clause is write:
6801 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00006802 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6803 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006804 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6805 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006806 X = AtomicBinOp->getLHS();
6807 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006808 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6809 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6810 if (!X->isLValue()) {
6811 ErrorFound = NotAnLValue;
6812 ErrorLoc = AtomicBinOp->getExprLoc();
6813 ErrorRange = AtomicBinOp->getSourceRange();
6814 NoteLoc = X->getExprLoc();
6815 NoteRange = X->getSourceRange();
6816 }
6817 } else if (!X->isInstantiationDependent() ||
6818 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006819 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006820 (X->isInstantiationDependent() || X->getType()->isScalarType())
6821 ? E
6822 : X;
6823 ErrorFound = NotAScalarType;
6824 ErrorLoc = AtomicBinOp->getExprLoc();
6825 ErrorRange = AtomicBinOp->getSourceRange();
6826 NoteLoc = NotScalarExpr->getExprLoc();
6827 NoteRange = NotScalarExpr->getSourceRange();
6828 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006829 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006830 ErrorFound = NotAnAssignmentOp;
6831 ErrorLoc = AtomicBody->getExprLoc();
6832 ErrorRange = AtomicBody->getSourceRange();
6833 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6834 : AtomicBody->getExprLoc();
6835 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6836 : AtomicBody->getSourceRange();
6837 }
6838 } else {
6839 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006840 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006841 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006842 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006843 if (ErrorFound != NoError) {
6844 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6845 << ErrorRange;
6846 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6847 << NoteRange;
6848 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006849 }
6850 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00006851 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006852 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006853 // If clause is update:
6854 // x++;
6855 // x--;
6856 // ++x;
6857 // --x;
6858 // x binop= expr;
6859 // x = x binop expr;
6860 // x = expr binop x;
6861 OpenMPAtomicUpdateChecker Checker(*this);
6862 if (Checker.checkStatement(
6863 Body, (AtomicKind == OMPC_update)
6864 ? diag::err_omp_atomic_update_not_expression_statement
6865 : diag::err_omp_atomic_not_expression_statement,
6866 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006867 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006868 if (!CurContext->isDependentContext()) {
6869 E = Checker.getExpr();
6870 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006871 UE = Checker.getUpdateExpr();
6872 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006873 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006874 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006875 enum {
6876 NotAnAssignmentOp,
6877 NotACompoundStatement,
6878 NotTwoSubstatements,
6879 NotASpecificExpression,
6880 NoError
6881 } ErrorFound = NoError;
6882 SourceLocation ErrorLoc, NoteLoc;
6883 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00006884 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006885 // If clause is a capture:
6886 // v = x++;
6887 // v = x--;
6888 // v = ++x;
6889 // v = --x;
6890 // v = x binop= expr;
6891 // v = x = x binop expr;
6892 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006893 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00006894 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6895 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6896 V = AtomicBinOp->getLHS();
6897 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6898 OpenMPAtomicUpdateChecker Checker(*this);
6899 if (Checker.checkStatement(
6900 Body, diag::err_omp_atomic_capture_not_expression_statement,
6901 diag::note_omp_atomic_update))
6902 return StmtError();
6903 E = Checker.getExpr();
6904 X = Checker.getX();
6905 UE = Checker.getUpdateExpr();
6906 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6907 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006908 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006909 ErrorLoc = AtomicBody->getExprLoc();
6910 ErrorRange = AtomicBody->getSourceRange();
6911 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6912 : AtomicBody->getExprLoc();
6913 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6914 : AtomicBody->getSourceRange();
6915 ErrorFound = NotAnAssignmentOp;
6916 }
6917 if (ErrorFound != NoError) {
6918 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6919 << ErrorRange;
6920 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6921 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006922 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006923 if (CurContext->isDependentContext())
6924 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006925 } else {
6926 // If clause is a capture:
6927 // { v = x; x = expr; }
6928 // { v = x; x++; }
6929 // { v = x; x--; }
6930 // { v = x; ++x; }
6931 // { v = x; --x; }
6932 // { v = x; x binop= expr; }
6933 // { v = x; x = x binop expr; }
6934 // { v = x; x = expr binop x; }
6935 // { x++; v = x; }
6936 // { x--; v = x; }
6937 // { ++x; v = x; }
6938 // { --x; v = x; }
6939 // { x binop= expr; v = x; }
6940 // { x = x binop expr; v = x; }
6941 // { x = expr binop x; v = x; }
6942 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6943 // Check that this is { expr1; expr2; }
6944 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006945 Stmt *First = CS->body_front();
6946 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006947 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6948 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6949 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6950 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6951 // Need to find what subexpression is 'v' and what is 'x'.
6952 OpenMPAtomicUpdateChecker Checker(*this);
6953 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6954 BinaryOperator *BinOp = nullptr;
6955 if (IsUpdateExprFound) {
6956 BinOp = dyn_cast<BinaryOperator>(First);
6957 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6958 }
6959 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6960 // { v = x; x++; }
6961 // { v = x; x--; }
6962 // { v = x; ++x; }
6963 // { v = x; --x; }
6964 // { v = x; x binop= expr; }
6965 // { v = x; x = x binop expr; }
6966 // { v = x; x = expr binop x; }
6967 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006968 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006969 llvm::FoldingSetNodeID XId, PossibleXId;
6970 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6971 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6972 IsUpdateExprFound = XId == PossibleXId;
6973 if (IsUpdateExprFound) {
6974 V = BinOp->getLHS();
6975 X = Checker.getX();
6976 E = Checker.getExpr();
6977 UE = Checker.getUpdateExpr();
6978 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006979 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006980 }
6981 }
6982 if (!IsUpdateExprFound) {
6983 IsUpdateExprFound = !Checker.checkStatement(First);
6984 BinOp = nullptr;
6985 if (IsUpdateExprFound) {
6986 BinOp = dyn_cast<BinaryOperator>(Second);
6987 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6988 }
6989 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6990 // { x++; v = x; }
6991 // { x--; v = x; }
6992 // { ++x; v = x; }
6993 // { --x; v = x; }
6994 // { x binop= expr; v = x; }
6995 // { x = x binop expr; v = x; }
6996 // { x = expr binop x; v = x; }
6997 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006998 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006999 llvm::FoldingSetNodeID XId, PossibleXId;
7000 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7001 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7002 IsUpdateExprFound = XId == PossibleXId;
7003 if (IsUpdateExprFound) {
7004 V = BinOp->getLHS();
7005 X = Checker.getX();
7006 E = Checker.getExpr();
7007 UE = Checker.getUpdateExpr();
7008 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007009 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007010 }
7011 }
7012 }
7013 if (!IsUpdateExprFound) {
7014 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007015 auto *FirstExpr = dyn_cast<Expr>(First);
7016 auto *SecondExpr = dyn_cast<Expr>(Second);
7017 if (!FirstExpr || !SecondExpr ||
7018 !(FirstExpr->isInstantiationDependent() ||
7019 SecondExpr->isInstantiationDependent())) {
7020 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7021 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007022 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007023 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007024 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007025 NoteRange = ErrorRange = FirstBinOp
7026 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007027 : SourceRange(ErrorLoc, ErrorLoc);
7028 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007029 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7030 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7031 ErrorFound = NotAnAssignmentOp;
7032 NoteLoc = ErrorLoc = SecondBinOp
7033 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007034 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007035 NoteRange = ErrorRange =
7036 SecondBinOp ? SecondBinOp->getSourceRange()
7037 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007038 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007039 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007040 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007041 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007042 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7043 llvm::FoldingSetNodeID X1Id, X2Id;
7044 PossibleXRHSInFirst->Profile(X1Id, Context,
7045 /*Canonical=*/true);
7046 PossibleXLHSInSecond->Profile(X2Id, Context,
7047 /*Canonical=*/true);
7048 IsUpdateExprFound = X1Id == X2Id;
7049 if (IsUpdateExprFound) {
7050 V = FirstBinOp->getLHS();
7051 X = SecondBinOp->getLHS();
7052 E = SecondBinOp->getRHS();
7053 UE = nullptr;
7054 IsXLHSInRHSPart = false;
7055 IsPostfixUpdate = true;
7056 } else {
7057 ErrorFound = NotASpecificExpression;
7058 ErrorLoc = FirstBinOp->getExprLoc();
7059 ErrorRange = FirstBinOp->getSourceRange();
7060 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7061 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7062 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007063 }
7064 }
7065 }
7066 }
7067 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007068 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007069 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007070 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007071 ErrorFound = NotTwoSubstatements;
7072 }
7073 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007074 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007075 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007076 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007077 ErrorFound = NotACompoundStatement;
7078 }
7079 if (ErrorFound != NoError) {
7080 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7081 << ErrorRange;
7082 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7083 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007084 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007085 if (CurContext->isDependentContext())
7086 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007087 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007088 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007089
Reid Kleckner87a31802018-03-12 21:43:02 +00007090 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007091
Alexey Bataev62cec442014-11-18 10:14:22 +00007092 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007093 X, V, E, UE, IsXLHSInRHSPart,
7094 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007095}
7096
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007097StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7098 Stmt *AStmt,
7099 SourceLocation StartLoc,
7100 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007101 if (!AStmt)
7102 return StmtError();
7103
Alexey Bataeve3727102018-04-18 15:57:46 +00007104 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007105 // 1.2.2 OpenMP Language Terminology
7106 // Structured block - An executable statement with a single entry at the
7107 // top and a single exit at the bottom.
7108 // The point of exit cannot be a branch out of the structured block.
7109 // longjmp() and throw() must not violate the entry/exit criteria.
7110 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007111 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7112 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7113 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7114 // 1.2.2 OpenMP Language Terminology
7115 // Structured block - An executable statement with a single entry at the
7116 // top and a single exit at the bottom.
7117 // The point of exit cannot be a branch out of the structured block.
7118 // longjmp() and throw() must not violate the entry/exit criteria.
7119 CS->getCapturedDecl()->setNothrow();
7120 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007121
Alexey Bataev13314bf2014-10-09 04:18:56 +00007122 // OpenMP [2.16, Nesting of Regions]
7123 // If specified, a teams construct must be contained within a target
7124 // construct. That target construct must contain no statements or directives
7125 // outside of the teams construct.
7126 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007127 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007128 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007129 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007130 auto I = CS->body_begin();
7131 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007132 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007133 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7134 OMPTeamsFound) {
7135
Alexey Bataev13314bf2014-10-09 04:18:56 +00007136 OMPTeamsFound = false;
7137 break;
7138 }
7139 ++I;
7140 }
7141 assert(I != CS->body_end() && "Not found statement");
7142 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007143 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007144 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007145 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007146 }
7147 if (!OMPTeamsFound) {
7148 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7149 Diag(DSAStack->getInnerTeamsRegionLoc(),
7150 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007151 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007152 << isa<OMPExecutableDirective>(S);
7153 return StmtError();
7154 }
7155 }
7156
Reid Kleckner87a31802018-03-12 21:43:02 +00007157 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007158
7159 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7160}
7161
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007162StmtResult
7163Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7164 Stmt *AStmt, SourceLocation StartLoc,
7165 SourceLocation EndLoc) {
7166 if (!AStmt)
7167 return StmtError();
7168
Alexey Bataeve3727102018-04-18 15:57:46 +00007169 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007170 // 1.2.2 OpenMP Language Terminology
7171 // Structured block - An executable statement with a single entry at the
7172 // top and a single exit at the bottom.
7173 // The point of exit cannot be a branch out of the structured block.
7174 // longjmp() and throw() must not violate the entry/exit criteria.
7175 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007176 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7177 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7178 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7179 // 1.2.2 OpenMP Language Terminology
7180 // Structured block - An executable statement with a single entry at the
7181 // top and a single exit at the bottom.
7182 // The point of exit cannot be a branch out of the structured block.
7183 // longjmp() and throw() must not violate the entry/exit criteria.
7184 CS->getCapturedDecl()->setNothrow();
7185 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007186
Reid Kleckner87a31802018-03-12 21:43:02 +00007187 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007188
7189 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7190 AStmt);
7191}
7192
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007193StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007195 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007196 if (!AStmt)
7197 return StmtError();
7198
Alexey Bataeve3727102018-04-18 15:57:46 +00007199 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007200 // 1.2.2 OpenMP Language Terminology
7201 // Structured block - An executable statement with a single entry at the
7202 // top and a single exit at the bottom.
7203 // The point of exit cannot be a branch out of the structured block.
7204 // longjmp() and throw() must not violate the entry/exit criteria.
7205 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007206 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7207 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7208 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7209 // 1.2.2 OpenMP Language Terminology
7210 // Structured block - An executable statement with a single entry at the
7211 // top and a single exit at the bottom.
7212 // The point of exit cannot be a branch out of the structured block.
7213 // longjmp() and throw() must not violate the entry/exit criteria.
7214 CS->getCapturedDecl()->setNothrow();
7215 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007216
7217 OMPLoopDirective::HelperExprs B;
7218 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7219 // define the nested loops number.
7220 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007221 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007222 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007223 VarsWithImplicitDSA, B);
7224 if (NestedLoopCount == 0)
7225 return StmtError();
7226
7227 assert((CurContext->isDependentContext() || B.builtAll()) &&
7228 "omp target parallel for loop exprs were not built");
7229
7230 if (!CurContext->isDependentContext()) {
7231 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007232 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007233 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007234 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007235 B.NumIterations, *this, CurScope,
7236 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007237 return StmtError();
7238 }
7239 }
7240
Reid Kleckner87a31802018-03-12 21:43:02 +00007241 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007242 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7243 NestedLoopCount, Clauses, AStmt,
7244 B, DSAStack->isCancelRegion());
7245}
7246
Alexey Bataev95b64a92017-05-30 16:00:04 +00007247/// Check for existence of a map clause in the list of clauses.
7248static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7249 const OpenMPClauseKind K) {
7250 return llvm::any_of(
7251 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7252}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007253
Alexey Bataev95b64a92017-05-30 16:00:04 +00007254template <typename... Params>
7255static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7256 const Params... ClauseTypes) {
7257 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007258}
7259
Michael Wong65f367f2015-07-21 13:44:28 +00007260StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7261 Stmt *AStmt,
7262 SourceLocation StartLoc,
7263 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007264 if (!AStmt)
7265 return StmtError();
7266
7267 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7268
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007269 // OpenMP [2.10.1, Restrictions, p. 97]
7270 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007271 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7272 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7273 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007274 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007275 return StmtError();
7276 }
7277
Reid Kleckner87a31802018-03-12 21:43:02 +00007278 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007279
7280 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7281 AStmt);
7282}
7283
Samuel Antaodf67fc42016-01-19 19:15:56 +00007284StmtResult
7285Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7286 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007287 SourceLocation EndLoc, Stmt *AStmt) {
7288 if (!AStmt)
7289 return StmtError();
7290
Alexey Bataeve3727102018-04-18 15:57:46 +00007291 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007292 // 1.2.2 OpenMP Language Terminology
7293 // Structured block - An executable statement with a single entry at the
7294 // top and a single exit at the bottom.
7295 // The point of exit cannot be a branch out of the structured block.
7296 // longjmp() and throw() must not violate the entry/exit criteria.
7297 CS->getCapturedDecl()->setNothrow();
7298 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7299 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7300 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7301 // 1.2.2 OpenMP Language Terminology
7302 // Structured block - An executable statement with a single entry at the
7303 // top and a single exit at the bottom.
7304 // The point of exit cannot be a branch out of the structured block.
7305 // longjmp() and throw() must not violate the entry/exit criteria.
7306 CS->getCapturedDecl()->setNothrow();
7307 }
7308
Samuel Antaodf67fc42016-01-19 19:15:56 +00007309 // OpenMP [2.10.2, Restrictions, p. 99]
7310 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007311 if (!hasClauses(Clauses, OMPC_map)) {
7312 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7313 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007314 return StmtError();
7315 }
7316
Alexey Bataev7828b252017-11-21 17:08:48 +00007317 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7318 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007319}
7320
Samuel Antao72590762016-01-19 20:04:50 +00007321StmtResult
7322Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7323 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007324 SourceLocation EndLoc, Stmt *AStmt) {
7325 if (!AStmt)
7326 return StmtError();
7327
Alexey Bataeve3727102018-04-18 15:57:46 +00007328 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007329 // 1.2.2 OpenMP Language Terminology
7330 // Structured block - An executable statement with a single entry at the
7331 // top and a single exit at the bottom.
7332 // The point of exit cannot be a branch out of the structured block.
7333 // longjmp() and throw() must not violate the entry/exit criteria.
7334 CS->getCapturedDecl()->setNothrow();
7335 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7336 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7337 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7338 // 1.2.2 OpenMP Language Terminology
7339 // Structured block - An executable statement with a single entry at the
7340 // top and a single exit at the bottom.
7341 // The point of exit cannot be a branch out of the structured block.
7342 // longjmp() and throw() must not violate the entry/exit criteria.
7343 CS->getCapturedDecl()->setNothrow();
7344 }
7345
Samuel Antao72590762016-01-19 20:04:50 +00007346 // OpenMP [2.10.3, Restrictions, p. 102]
7347 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007348 if (!hasClauses(Clauses, OMPC_map)) {
7349 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7350 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007351 return StmtError();
7352 }
7353
Alexey Bataev7828b252017-11-21 17:08:48 +00007354 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7355 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007356}
7357
Samuel Antao686c70c2016-05-26 17:30:50 +00007358StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7359 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007360 SourceLocation EndLoc,
7361 Stmt *AStmt) {
7362 if (!AStmt)
7363 return StmtError();
7364
Alexey Bataeve3727102018-04-18 15:57:46 +00007365 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007366 // 1.2.2 OpenMP Language Terminology
7367 // Structured block - An executable statement with a single entry at the
7368 // top and a single exit at the bottom.
7369 // The point of exit cannot be a branch out of the structured block.
7370 // longjmp() and throw() must not violate the entry/exit criteria.
7371 CS->getCapturedDecl()->setNothrow();
7372 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7373 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7374 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7375 // 1.2.2 OpenMP Language Terminology
7376 // Structured block - An executable statement with a single entry at the
7377 // top and a single exit at the bottom.
7378 // The point of exit cannot be a branch out of the structured block.
7379 // longjmp() and throw() must not violate the entry/exit criteria.
7380 CS->getCapturedDecl()->setNothrow();
7381 }
7382
Alexey Bataev95b64a92017-05-30 16:00:04 +00007383 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007384 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7385 return StmtError();
7386 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007387 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7388 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007389}
7390
Alexey Bataev13314bf2014-10-09 04:18:56 +00007391StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7392 Stmt *AStmt, SourceLocation StartLoc,
7393 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007394 if (!AStmt)
7395 return StmtError();
7396
Alexey Bataeve3727102018-04-18 15:57:46 +00007397 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007398 // 1.2.2 OpenMP Language Terminology
7399 // Structured block - An executable statement with a single entry at the
7400 // top and a single exit at the bottom.
7401 // The point of exit cannot be a branch out of the structured block.
7402 // longjmp() and throw() must not violate the entry/exit criteria.
7403 CS->getCapturedDecl()->setNothrow();
7404
Reid Kleckner87a31802018-03-12 21:43:02 +00007405 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007406
Alexey Bataevceabd412017-11-30 18:01:54 +00007407 DSAStack->setParentTeamsRegionLoc(StartLoc);
7408
Alexey Bataev13314bf2014-10-09 04:18:56 +00007409 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7410}
7411
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007412StmtResult
7413Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7414 SourceLocation EndLoc,
7415 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007416 if (DSAStack->isParentNowaitRegion()) {
7417 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7418 return StmtError();
7419 }
7420 if (DSAStack->isParentOrderedRegion()) {
7421 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7422 return StmtError();
7423 }
7424 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7425 CancelRegion);
7426}
7427
Alexey Bataev87933c72015-09-18 08:07:34 +00007428StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7429 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007430 SourceLocation EndLoc,
7431 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007432 if (DSAStack->isParentNowaitRegion()) {
7433 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7434 return StmtError();
7435 }
7436 if (DSAStack->isParentOrderedRegion()) {
7437 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7438 return StmtError();
7439 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007440 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007441 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7442 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007443}
7444
Alexey Bataev382967a2015-12-08 12:06:20 +00007445static bool checkGrainsizeNumTasksClauses(Sema &S,
7446 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007447 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007448 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007449 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007450 if (C->getClauseKind() == OMPC_grainsize ||
7451 C->getClauseKind() == OMPC_num_tasks) {
7452 if (!PrevClause)
7453 PrevClause = C;
7454 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007455 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007456 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7457 << getOpenMPClauseName(C->getClauseKind())
7458 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007459 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007460 diag::note_omp_previous_grainsize_num_tasks)
7461 << getOpenMPClauseName(PrevClause->getClauseKind());
7462 ErrorFound = true;
7463 }
7464 }
7465 }
7466 return ErrorFound;
7467}
7468
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007469static bool checkReductionClauseWithNogroup(Sema &S,
7470 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007471 const OMPClause *ReductionClause = nullptr;
7472 const OMPClause *NogroupClause = nullptr;
7473 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007474 if (C->getClauseKind() == OMPC_reduction) {
7475 ReductionClause = C;
7476 if (NogroupClause)
7477 break;
7478 continue;
7479 }
7480 if (C->getClauseKind() == OMPC_nogroup) {
7481 NogroupClause = C;
7482 if (ReductionClause)
7483 break;
7484 continue;
7485 }
7486 }
7487 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007488 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7489 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007490 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007491 return true;
7492 }
7493 return false;
7494}
7495
Alexey Bataev49f6e782015-12-01 04:18:41 +00007496StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7497 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007498 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007499 if (!AStmt)
7500 return StmtError();
7501
7502 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7503 OMPLoopDirective::HelperExprs B;
7504 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7505 // define the nested loops number.
7506 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007507 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007508 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007509 VarsWithImplicitDSA, B);
7510 if (NestedLoopCount == 0)
7511 return StmtError();
7512
7513 assert((CurContext->isDependentContext() || B.builtAll()) &&
7514 "omp for loop exprs were not built");
7515
Alexey Bataev382967a2015-12-08 12:06:20 +00007516 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7517 // The grainsize clause and num_tasks clause are mutually exclusive and may
7518 // not appear on the same taskloop directive.
7519 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7520 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007521 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7522 // If a reduction clause is present on the taskloop directive, the nogroup
7523 // clause must not be specified.
7524 if (checkReductionClauseWithNogroup(*this, Clauses))
7525 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007526
Reid Kleckner87a31802018-03-12 21:43:02 +00007527 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007528 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7529 NestedLoopCount, Clauses, AStmt, B);
7530}
7531
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007532StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7533 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007534 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007535 if (!AStmt)
7536 return StmtError();
7537
7538 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7539 OMPLoopDirective::HelperExprs B;
7540 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7541 // define the nested loops number.
7542 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007543 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007544 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7545 VarsWithImplicitDSA, B);
7546 if (NestedLoopCount == 0)
7547 return StmtError();
7548
7549 assert((CurContext->isDependentContext() || B.builtAll()) &&
7550 "omp for loop exprs were not built");
7551
Alexey Bataev5a3af132016-03-29 08:58:54 +00007552 if (!CurContext->isDependentContext()) {
7553 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007554 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007555 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007556 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007557 B.NumIterations, *this, CurScope,
7558 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007559 return StmtError();
7560 }
7561 }
7562
Alexey Bataev382967a2015-12-08 12:06:20 +00007563 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7564 // The grainsize clause and num_tasks clause are mutually exclusive and may
7565 // not appear on the same taskloop directive.
7566 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7567 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007568 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7569 // If a reduction clause is present on the taskloop directive, the nogroup
7570 // clause must not be specified.
7571 if (checkReductionClauseWithNogroup(*this, Clauses))
7572 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007573 if (checkSimdlenSafelenSpecified(*this, Clauses))
7574 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007575
Reid Kleckner87a31802018-03-12 21:43:02 +00007576 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007577 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7578 NestedLoopCount, Clauses, AStmt, B);
7579}
7580
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007581StmtResult Sema::ActOnOpenMPDistributeDirective(
7582 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007583 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007584 if (!AStmt)
7585 return StmtError();
7586
7587 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7588 OMPLoopDirective::HelperExprs B;
7589 // In presence of clause 'collapse' with number of loops, it will
7590 // define the nested loops number.
7591 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007592 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007593 nullptr /*ordered not a clause on distribute*/, AStmt,
7594 *this, *DSAStack, VarsWithImplicitDSA, B);
7595 if (NestedLoopCount == 0)
7596 return StmtError();
7597
7598 assert((CurContext->isDependentContext() || B.builtAll()) &&
7599 "omp for loop exprs were not built");
7600
Reid Kleckner87a31802018-03-12 21:43:02 +00007601 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007602 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7603 NestedLoopCount, Clauses, AStmt, B);
7604}
7605
Carlo Bertolli9925f152016-06-27 14:55:37 +00007606StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7607 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007608 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007609 if (!AStmt)
7610 return StmtError();
7611
Alexey Bataeve3727102018-04-18 15:57:46 +00007612 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007613 // 1.2.2 OpenMP Language Terminology
7614 // Structured block - An executable statement with a single entry at the
7615 // top and a single exit at the bottom.
7616 // The point of exit cannot be a branch out of the structured block.
7617 // longjmp() and throw() must not violate the entry/exit criteria.
7618 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007619 for (int ThisCaptureLevel =
7620 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7621 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7622 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7623 // 1.2.2 OpenMP Language Terminology
7624 // Structured block - An executable statement with a single entry at the
7625 // top and a single exit at the bottom.
7626 // The point of exit cannot be a branch out of the structured block.
7627 // longjmp() and throw() must not violate the entry/exit criteria.
7628 CS->getCapturedDecl()->setNothrow();
7629 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007630
7631 OMPLoopDirective::HelperExprs B;
7632 // In presence of clause 'collapse' with number of loops, it will
7633 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007634 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007635 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007636 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007637 VarsWithImplicitDSA, B);
7638 if (NestedLoopCount == 0)
7639 return StmtError();
7640
7641 assert((CurContext->isDependentContext() || B.builtAll()) &&
7642 "omp for loop exprs were not built");
7643
Reid Kleckner87a31802018-03-12 21:43:02 +00007644 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007645 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007646 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7647 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007648}
7649
Kelvin Li4a39add2016-07-05 05:00:15 +00007650StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7651 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007652 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007653 if (!AStmt)
7654 return StmtError();
7655
Alexey Bataeve3727102018-04-18 15:57:46 +00007656 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007657 // 1.2.2 OpenMP Language Terminology
7658 // Structured block - An executable statement with a single entry at the
7659 // top and a single exit at the bottom.
7660 // The point of exit cannot be a branch out of the structured block.
7661 // longjmp() and throw() must not violate the entry/exit criteria.
7662 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007663 for (int ThisCaptureLevel =
7664 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7665 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7666 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7667 // 1.2.2 OpenMP Language Terminology
7668 // Structured block - An executable statement with a single entry at the
7669 // top and a single exit at the bottom.
7670 // The point of exit cannot be a branch out of the structured block.
7671 // longjmp() and throw() must not violate the entry/exit criteria.
7672 CS->getCapturedDecl()->setNothrow();
7673 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007674
7675 OMPLoopDirective::HelperExprs B;
7676 // In presence of clause 'collapse' with number of loops, it will
7677 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007678 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007679 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007680 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007681 VarsWithImplicitDSA, B);
7682 if (NestedLoopCount == 0)
7683 return StmtError();
7684
7685 assert((CurContext->isDependentContext() || B.builtAll()) &&
7686 "omp for loop exprs were not built");
7687
Alexey Bataev438388c2017-11-22 18:34:02 +00007688 if (!CurContext->isDependentContext()) {
7689 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007690 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007691 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7692 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7693 B.NumIterations, *this, CurScope,
7694 DSAStack))
7695 return StmtError();
7696 }
7697 }
7698
Kelvin Lic5609492016-07-15 04:39:07 +00007699 if (checkSimdlenSafelenSpecified(*this, Clauses))
7700 return StmtError();
7701
Reid Kleckner87a31802018-03-12 21:43:02 +00007702 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007703 return OMPDistributeParallelForSimdDirective::Create(
7704 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7705}
7706
Kelvin Li787f3fc2016-07-06 04:45:38 +00007707StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7708 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007709 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007710 if (!AStmt)
7711 return StmtError();
7712
Alexey Bataeve3727102018-04-18 15:57:46 +00007713 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007714 // 1.2.2 OpenMP Language Terminology
7715 // Structured block - An executable statement with a single entry at the
7716 // top and a single exit at the bottom.
7717 // The point of exit cannot be a branch out of the structured block.
7718 // longjmp() and throw() must not violate the entry/exit criteria.
7719 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007720 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7721 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7722 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7723 // 1.2.2 OpenMP Language Terminology
7724 // Structured block - An executable statement with a single entry at the
7725 // top and a single exit at the bottom.
7726 // The point of exit cannot be a branch out of the structured block.
7727 // longjmp() and throw() must not violate the entry/exit criteria.
7728 CS->getCapturedDecl()->setNothrow();
7729 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007730
7731 OMPLoopDirective::HelperExprs B;
7732 // In presence of clause 'collapse' with number of loops, it will
7733 // define the nested loops number.
7734 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007735 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007736 nullptr /*ordered not a clause on distribute*/, CS, *this,
7737 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007738 if (NestedLoopCount == 0)
7739 return StmtError();
7740
7741 assert((CurContext->isDependentContext() || B.builtAll()) &&
7742 "omp for loop exprs were not built");
7743
Alexey Bataev438388c2017-11-22 18:34:02 +00007744 if (!CurContext->isDependentContext()) {
7745 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007746 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007747 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7748 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7749 B.NumIterations, *this, CurScope,
7750 DSAStack))
7751 return StmtError();
7752 }
7753 }
7754
Kelvin Lic5609492016-07-15 04:39:07 +00007755 if (checkSimdlenSafelenSpecified(*this, Clauses))
7756 return StmtError();
7757
Reid Kleckner87a31802018-03-12 21:43:02 +00007758 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007759 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7760 NestedLoopCount, Clauses, AStmt, B);
7761}
7762
Kelvin Lia579b912016-07-14 02:54:56 +00007763StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7764 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007765 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007766 if (!AStmt)
7767 return StmtError();
7768
Alexey Bataeve3727102018-04-18 15:57:46 +00007769 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007770 // 1.2.2 OpenMP Language Terminology
7771 // Structured block - An executable statement with a single entry at the
7772 // top and a single exit at the bottom.
7773 // The point of exit cannot be a branch out of the structured block.
7774 // longjmp() and throw() must not violate the entry/exit criteria.
7775 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007776 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7777 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7778 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7779 // 1.2.2 OpenMP Language Terminology
7780 // Structured block - An executable statement with a single entry at the
7781 // top and a single exit at the bottom.
7782 // The point of exit cannot be a branch out of the structured block.
7783 // longjmp() and throw() must not violate the entry/exit criteria.
7784 CS->getCapturedDecl()->setNothrow();
7785 }
Kelvin Lia579b912016-07-14 02:54:56 +00007786
7787 OMPLoopDirective::HelperExprs B;
7788 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7789 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007790 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00007791 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007792 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007793 VarsWithImplicitDSA, B);
7794 if (NestedLoopCount == 0)
7795 return StmtError();
7796
7797 assert((CurContext->isDependentContext() || B.builtAll()) &&
7798 "omp target parallel for simd loop exprs were not built");
7799
7800 if (!CurContext->isDependentContext()) {
7801 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007802 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007803 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007804 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7805 B.NumIterations, *this, CurScope,
7806 DSAStack))
7807 return StmtError();
7808 }
7809 }
Kelvin Lic5609492016-07-15 04:39:07 +00007810 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007811 return StmtError();
7812
Reid Kleckner87a31802018-03-12 21:43:02 +00007813 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007814 return OMPTargetParallelForSimdDirective::Create(
7815 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7816}
7817
Kelvin Li986330c2016-07-20 22:57:10 +00007818StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007820 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00007821 if (!AStmt)
7822 return StmtError();
7823
Alexey Bataeve3727102018-04-18 15:57:46 +00007824 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00007825 // 1.2.2 OpenMP Language Terminology
7826 // Structured block - An executable statement with a single entry at the
7827 // top and a single exit at the bottom.
7828 // The point of exit cannot be a branch out of the structured block.
7829 // longjmp() and throw() must not violate the entry/exit criteria.
7830 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007831 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7832 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7833 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7834 // 1.2.2 OpenMP Language Terminology
7835 // Structured block - An executable statement with a single entry at the
7836 // top and a single exit at the bottom.
7837 // The point of exit cannot be a branch out of the structured block.
7838 // longjmp() and throw() must not violate the entry/exit criteria.
7839 CS->getCapturedDecl()->setNothrow();
7840 }
7841
Kelvin Li986330c2016-07-20 22:57:10 +00007842 OMPLoopDirective::HelperExprs B;
7843 // In presence of clause 'collapse' with number of loops, it will define the
7844 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007845 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007846 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007847 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007848 VarsWithImplicitDSA, B);
7849 if (NestedLoopCount == 0)
7850 return StmtError();
7851
7852 assert((CurContext->isDependentContext() || B.builtAll()) &&
7853 "omp target simd loop exprs were not built");
7854
7855 if (!CurContext->isDependentContext()) {
7856 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007857 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007858 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007859 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7860 B.NumIterations, *this, CurScope,
7861 DSAStack))
7862 return StmtError();
7863 }
7864 }
7865
7866 if (checkSimdlenSafelenSpecified(*this, Clauses))
7867 return StmtError();
7868
Reid Kleckner87a31802018-03-12 21:43:02 +00007869 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007870 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7871 NestedLoopCount, Clauses, AStmt, B);
7872}
7873
Kelvin Li02532872016-08-05 14:37:37 +00007874StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7875 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007876 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00007877 if (!AStmt)
7878 return StmtError();
7879
Alexey Bataeve3727102018-04-18 15:57:46 +00007880 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00007881 // 1.2.2 OpenMP Language Terminology
7882 // Structured block - An executable statement with a single entry at the
7883 // top and a single exit at the bottom.
7884 // The point of exit cannot be a branch out of the structured block.
7885 // longjmp() and throw() must not violate the entry/exit criteria.
7886 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007887 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7888 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7889 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7890 // 1.2.2 OpenMP Language Terminology
7891 // Structured block - An executable statement with a single entry at the
7892 // top and a single exit at the bottom.
7893 // The point of exit cannot be a branch out of the structured block.
7894 // longjmp() and throw() must not violate the entry/exit criteria.
7895 CS->getCapturedDecl()->setNothrow();
7896 }
Kelvin Li02532872016-08-05 14:37:37 +00007897
7898 OMPLoopDirective::HelperExprs B;
7899 // In presence of clause 'collapse' with number of loops, it will
7900 // define the nested loops number.
7901 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007902 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007903 nullptr /*ordered not a clause on distribute*/, CS, *this,
7904 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007905 if (NestedLoopCount == 0)
7906 return StmtError();
7907
7908 assert((CurContext->isDependentContext() || B.builtAll()) &&
7909 "omp teams distribute loop exprs were not built");
7910
Reid Kleckner87a31802018-03-12 21:43:02 +00007911 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007912
7913 DSAStack->setParentTeamsRegionLoc(StartLoc);
7914
David Majnemer9d168222016-08-05 17:44:54 +00007915 return OMPTeamsDistributeDirective::Create(
7916 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007917}
7918
Kelvin Li4e325f72016-10-25 12:50:55 +00007919StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7920 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007921 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007922 if (!AStmt)
7923 return StmtError();
7924
Alexey Bataeve3727102018-04-18 15:57:46 +00007925 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00007926 // 1.2.2 OpenMP Language Terminology
7927 // Structured block - An executable statement with a single entry at the
7928 // top and a single exit at the bottom.
7929 // The point of exit cannot be a branch out of the structured block.
7930 // longjmp() and throw() must not violate the entry/exit criteria.
7931 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007932 for (int ThisCaptureLevel =
7933 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7934 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7935 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7936 // 1.2.2 OpenMP Language Terminology
7937 // Structured block - An executable statement with a single entry at the
7938 // top and a single exit at the bottom.
7939 // The point of exit cannot be a branch out of the structured block.
7940 // longjmp() and throw() must not violate the entry/exit criteria.
7941 CS->getCapturedDecl()->setNothrow();
7942 }
7943
Kelvin Li4e325f72016-10-25 12:50:55 +00007944
7945 OMPLoopDirective::HelperExprs B;
7946 // In presence of clause 'collapse' with number of loops, it will
7947 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007948 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00007949 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007950 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007951 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007952
7953 if (NestedLoopCount == 0)
7954 return StmtError();
7955
7956 assert((CurContext->isDependentContext() || B.builtAll()) &&
7957 "omp teams distribute simd loop exprs were not built");
7958
7959 if (!CurContext->isDependentContext()) {
7960 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007961 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007962 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7963 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7964 B.NumIterations, *this, CurScope,
7965 DSAStack))
7966 return StmtError();
7967 }
7968 }
7969
7970 if (checkSimdlenSafelenSpecified(*this, Clauses))
7971 return StmtError();
7972
Reid Kleckner87a31802018-03-12 21:43:02 +00007973 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007974
7975 DSAStack->setParentTeamsRegionLoc(StartLoc);
7976
Kelvin Li4e325f72016-10-25 12:50:55 +00007977 return OMPTeamsDistributeSimdDirective::Create(
7978 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7979}
7980
Kelvin Li579e41c2016-11-30 23:51:03 +00007981StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7982 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007983 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00007984 if (!AStmt)
7985 return StmtError();
7986
Alexey Bataeve3727102018-04-18 15:57:46 +00007987 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00007988 // 1.2.2 OpenMP Language Terminology
7989 // Structured block - An executable statement with a single entry at the
7990 // top and a single exit at the bottom.
7991 // The point of exit cannot be a branch out of the structured block.
7992 // longjmp() and throw() must not violate the entry/exit criteria.
7993 CS->getCapturedDecl()->setNothrow();
7994
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007995 for (int ThisCaptureLevel =
7996 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7997 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7998 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7999 // 1.2.2 OpenMP Language Terminology
8000 // Structured block - An executable statement with a single entry at the
8001 // top and a single exit at the bottom.
8002 // The point of exit cannot be a branch out of the structured block.
8003 // longjmp() and throw() must not violate the entry/exit criteria.
8004 CS->getCapturedDecl()->setNothrow();
8005 }
8006
Kelvin Li579e41c2016-11-30 23:51:03 +00008007 OMPLoopDirective::HelperExprs B;
8008 // In presence of clause 'collapse' with number of loops, it will
8009 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008010 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008011 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008012 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008013 VarsWithImplicitDSA, B);
8014
8015 if (NestedLoopCount == 0)
8016 return StmtError();
8017
8018 assert((CurContext->isDependentContext() || B.builtAll()) &&
8019 "omp for loop exprs were not built");
8020
8021 if (!CurContext->isDependentContext()) {
8022 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008023 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008024 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8025 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8026 B.NumIterations, *this, CurScope,
8027 DSAStack))
8028 return StmtError();
8029 }
8030 }
8031
8032 if (checkSimdlenSafelenSpecified(*this, Clauses))
8033 return StmtError();
8034
Reid Kleckner87a31802018-03-12 21:43:02 +00008035 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008036
8037 DSAStack->setParentTeamsRegionLoc(StartLoc);
8038
Kelvin Li579e41c2016-11-30 23:51:03 +00008039 return OMPTeamsDistributeParallelForSimdDirective::Create(
8040 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8041}
8042
Kelvin Li7ade93f2016-12-09 03:24:30 +00008043StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8044 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008045 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008046 if (!AStmt)
8047 return StmtError();
8048
Alexey Bataeve3727102018-04-18 15:57:46 +00008049 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008050 // 1.2.2 OpenMP Language Terminology
8051 // Structured block - An executable statement with a single entry at the
8052 // top and a single exit at the bottom.
8053 // The point of exit cannot be a branch out of the structured block.
8054 // longjmp() and throw() must not violate the entry/exit criteria.
8055 CS->getCapturedDecl()->setNothrow();
8056
Carlo Bertolli62fae152017-11-20 20:46:39 +00008057 for (int ThisCaptureLevel =
8058 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8059 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8060 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8061 // 1.2.2 OpenMP Language Terminology
8062 // Structured block - An executable statement with a single entry at the
8063 // top and a single exit at the bottom.
8064 // The point of exit cannot be a branch out of the structured block.
8065 // longjmp() and throw() must not violate the entry/exit criteria.
8066 CS->getCapturedDecl()->setNothrow();
8067 }
8068
Kelvin Li7ade93f2016-12-09 03:24:30 +00008069 OMPLoopDirective::HelperExprs B;
8070 // In presence of clause 'collapse' with number of loops, it will
8071 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008072 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008073 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008074 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008075 VarsWithImplicitDSA, B);
8076
8077 if (NestedLoopCount == 0)
8078 return StmtError();
8079
8080 assert((CurContext->isDependentContext() || B.builtAll()) &&
8081 "omp for loop exprs were not built");
8082
Reid Kleckner87a31802018-03-12 21:43:02 +00008083 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008084
8085 DSAStack->setParentTeamsRegionLoc(StartLoc);
8086
Kelvin Li7ade93f2016-12-09 03:24:30 +00008087 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008088 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8089 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008090}
8091
Kelvin Libf594a52016-12-17 05:48:59 +00008092StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8093 Stmt *AStmt,
8094 SourceLocation StartLoc,
8095 SourceLocation EndLoc) {
8096 if (!AStmt)
8097 return StmtError();
8098
Alexey Bataeve3727102018-04-18 15:57:46 +00008099 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008100 // 1.2.2 OpenMP Language Terminology
8101 // Structured block - An executable statement with a single entry at the
8102 // top and a single exit at the bottom.
8103 // The point of exit cannot be a branch out of the structured block.
8104 // longjmp() and throw() must not violate the entry/exit criteria.
8105 CS->getCapturedDecl()->setNothrow();
8106
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008107 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8108 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8109 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8110 // 1.2.2 OpenMP Language Terminology
8111 // Structured block - An executable statement with a single entry at the
8112 // top and a single exit at the bottom.
8113 // The point of exit cannot be a branch out of the structured block.
8114 // longjmp() and throw() must not violate the entry/exit criteria.
8115 CS->getCapturedDecl()->setNothrow();
8116 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008117 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008118
8119 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8120 AStmt);
8121}
8122
Kelvin Li83c451e2016-12-25 04:52:54 +00008123StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8124 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008125 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008126 if (!AStmt)
8127 return StmtError();
8128
Alexey Bataeve3727102018-04-18 15:57:46 +00008129 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008130 // 1.2.2 OpenMP Language Terminology
8131 // Structured block - An executable statement with a single entry at the
8132 // top and a single exit at the bottom.
8133 // The point of exit cannot be a branch out of the structured block.
8134 // longjmp() and throw() must not violate the entry/exit criteria.
8135 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008136 for (int ThisCaptureLevel =
8137 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8138 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8139 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8140 // 1.2.2 OpenMP Language Terminology
8141 // Structured block - An executable statement with a single entry at the
8142 // top and a single exit at the bottom.
8143 // The point of exit cannot be a branch out of the structured block.
8144 // longjmp() and throw() must not violate the entry/exit criteria.
8145 CS->getCapturedDecl()->setNothrow();
8146 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008147
8148 OMPLoopDirective::HelperExprs B;
8149 // In presence of clause 'collapse' with number of loops, it will
8150 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008151 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008152 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8153 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008154 VarsWithImplicitDSA, B);
8155 if (NestedLoopCount == 0)
8156 return StmtError();
8157
8158 assert((CurContext->isDependentContext() || B.builtAll()) &&
8159 "omp target teams distribute loop exprs were not built");
8160
Reid Kleckner87a31802018-03-12 21:43:02 +00008161 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008162 return OMPTargetTeamsDistributeDirective::Create(
8163 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8164}
8165
Kelvin Li80e8f562016-12-29 22:16:30 +00008166StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8167 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008168 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008169 if (!AStmt)
8170 return StmtError();
8171
Alexey Bataeve3727102018-04-18 15:57:46 +00008172 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008173 // 1.2.2 OpenMP Language Terminology
8174 // Structured block - An executable statement with a single entry at the
8175 // top and a single exit at the bottom.
8176 // The point of exit cannot be a branch out of the structured block.
8177 // longjmp() and throw() must not violate the entry/exit criteria.
8178 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008179 for (int ThisCaptureLevel =
8180 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8181 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8182 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8183 // 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 }
8190
Kelvin Li80e8f562016-12-29 22:16:30 +00008191 OMPLoopDirective::HelperExprs B;
8192 // In presence of clause 'collapse' with number of loops, it will
8193 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008194 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008195 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8196 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008197 VarsWithImplicitDSA, B);
8198 if (NestedLoopCount == 0)
8199 return StmtError();
8200
8201 assert((CurContext->isDependentContext() || B.builtAll()) &&
8202 "omp target teams distribute parallel for loop exprs were not built");
8203
Alexey Bataev647dd842018-01-15 20:59:40 +00008204 if (!CurContext->isDependentContext()) {
8205 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008206 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008207 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8208 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8209 B.NumIterations, *this, CurScope,
8210 DSAStack))
8211 return StmtError();
8212 }
8213 }
8214
Reid Kleckner87a31802018-03-12 21:43:02 +00008215 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008216 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008217 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8218 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008219}
8220
Kelvin Li1851df52017-01-03 05:23:48 +00008221StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8222 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008223 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008224 if (!AStmt)
8225 return StmtError();
8226
Alexey Bataeve3727102018-04-18 15:57:46 +00008227 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008228 // 1.2.2 OpenMP Language Terminology
8229 // Structured block - An executable statement with a single entry at the
8230 // top and a single exit at the bottom.
8231 // The point of exit cannot be a branch out of the structured block.
8232 // longjmp() and throw() must not violate the entry/exit criteria.
8233 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008234 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8235 OMPD_target_teams_distribute_parallel_for_simd);
8236 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8237 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8238 // 1.2.2 OpenMP Language Terminology
8239 // Structured block - An executable statement with a single entry at the
8240 // top and a single exit at the bottom.
8241 // The point of exit cannot be a branch out of the structured block.
8242 // longjmp() and throw() must not violate the entry/exit criteria.
8243 CS->getCapturedDecl()->setNothrow();
8244 }
Kelvin Li1851df52017-01-03 05:23:48 +00008245
8246 OMPLoopDirective::HelperExprs B;
8247 // In presence of clause 'collapse' with number of loops, it will
8248 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008249 unsigned NestedLoopCount =
8250 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008251 getCollapseNumberExpr(Clauses),
8252 nullptr /*ordered not a clause on distribute*/, CS, *this,
8253 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008254 if (NestedLoopCount == 0)
8255 return StmtError();
8256
8257 assert((CurContext->isDependentContext() || B.builtAll()) &&
8258 "omp target teams distribute parallel for simd loop exprs were not "
8259 "built");
8260
8261 if (!CurContext->isDependentContext()) {
8262 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008263 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008264 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8265 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8266 B.NumIterations, *this, CurScope,
8267 DSAStack))
8268 return StmtError();
8269 }
8270 }
8271
Alexey Bataev438388c2017-11-22 18:34:02 +00008272 if (checkSimdlenSafelenSpecified(*this, Clauses))
8273 return StmtError();
8274
Reid Kleckner87a31802018-03-12 21:43:02 +00008275 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008276 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8277 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8278}
8279
Kelvin Lida681182017-01-10 18:08:18 +00008280StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8281 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008282 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008283 if (!AStmt)
8284 return StmtError();
8285
8286 auto *CS = cast<CapturedStmt>(AStmt);
8287 // 1.2.2 OpenMP Language Terminology
8288 // Structured block - An executable statement with a single entry at the
8289 // top and a single exit at the bottom.
8290 // The point of exit cannot be a branch out of the structured block.
8291 // longjmp() and throw() must not violate the entry/exit criteria.
8292 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008293 for (int ThisCaptureLevel =
8294 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8295 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8296 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8297 // 1.2.2 OpenMP Language Terminology
8298 // Structured block - An executable statement with a single entry at the
8299 // top and a single exit at the bottom.
8300 // The point of exit cannot be a branch out of the structured block.
8301 // longjmp() and throw() must not violate the entry/exit criteria.
8302 CS->getCapturedDecl()->setNothrow();
8303 }
Kelvin Lida681182017-01-10 18:08:18 +00008304
8305 OMPLoopDirective::HelperExprs B;
8306 // In presence of clause 'collapse' with number of loops, it will
8307 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008308 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008309 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008310 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008311 VarsWithImplicitDSA, B);
8312 if (NestedLoopCount == 0)
8313 return StmtError();
8314
8315 assert((CurContext->isDependentContext() || B.builtAll()) &&
8316 "omp target teams distribute simd loop exprs were not built");
8317
Alexey Bataev438388c2017-11-22 18:34:02 +00008318 if (!CurContext->isDependentContext()) {
8319 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008320 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008321 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8322 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8323 B.NumIterations, *this, CurScope,
8324 DSAStack))
8325 return StmtError();
8326 }
8327 }
8328
8329 if (checkSimdlenSafelenSpecified(*this, Clauses))
8330 return StmtError();
8331
Reid Kleckner87a31802018-03-12 21:43:02 +00008332 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008333 return OMPTargetTeamsDistributeSimdDirective::Create(
8334 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8335}
8336
Alexey Bataeved09d242014-05-28 05:53:51 +00008337OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008338 SourceLocation StartLoc,
8339 SourceLocation LParenLoc,
8340 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008341 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008342 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008343 case OMPC_final:
8344 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8345 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008346 case OMPC_num_threads:
8347 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8348 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008349 case OMPC_safelen:
8350 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8351 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008352 case OMPC_simdlen:
8353 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8354 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008355 case OMPC_collapse:
8356 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8357 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008358 case OMPC_ordered:
8359 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8360 break;
Michael Wonge710d542015-08-07 16:16:36 +00008361 case OMPC_device:
8362 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8363 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008364 case OMPC_num_teams:
8365 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8366 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008367 case OMPC_thread_limit:
8368 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8369 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008370 case OMPC_priority:
8371 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8372 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008373 case OMPC_grainsize:
8374 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8375 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008376 case OMPC_num_tasks:
8377 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8378 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008379 case OMPC_hint:
8380 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8381 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008382 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008383 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008384 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008385 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008386 case OMPC_private:
8387 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008388 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008389 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008390 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008391 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008392 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008393 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008394 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008395 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008396 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008397 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008398 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008399 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008400 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008401 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008402 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008403 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008404 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008405 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008406 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008407 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008408 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008409 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008410 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008411 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008412 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008413 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008414 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008415 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008416 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008417 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008418 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008419 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008420 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008421 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008422 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008423 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008424 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008425 llvm_unreachable("Clause is not allowed.");
8426 }
8427 return Res;
8428}
8429
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008430// An OpenMP directive such as 'target parallel' has two captured regions:
8431// for the 'target' and 'parallel' respectively. This function returns
8432// the region in which to capture expressions associated with a clause.
8433// A return value of OMPD_unknown signifies that the expression should not
8434// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008435static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8436 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8437 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008438 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008439 switch (CKind) {
8440 case OMPC_if:
8441 switch (DKind) {
8442 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008443 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008444 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008445 // If this clause applies to the nested 'parallel' region, capture within
8446 // the 'target' region, otherwise do not capture.
8447 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8448 CaptureRegion = OMPD_target;
8449 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008450 case OMPD_target_teams_distribute_parallel_for:
8451 case OMPD_target_teams_distribute_parallel_for_simd:
8452 // If this clause applies to the nested 'parallel' region, capture within
8453 // the 'teams' region, otherwise do not capture.
8454 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8455 CaptureRegion = OMPD_teams;
8456 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008457 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008458 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008459 CaptureRegion = OMPD_teams;
8460 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008461 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008462 case OMPD_target_enter_data:
8463 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008464 CaptureRegion = OMPD_task;
8465 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008466 case OMPD_cancel:
8467 case OMPD_parallel:
8468 case OMPD_parallel_sections:
8469 case OMPD_parallel_for:
8470 case OMPD_parallel_for_simd:
8471 case OMPD_target:
8472 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008473 case OMPD_target_teams:
8474 case OMPD_target_teams_distribute:
8475 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008476 case OMPD_distribute_parallel_for:
8477 case OMPD_distribute_parallel_for_simd:
8478 case OMPD_task:
8479 case OMPD_taskloop:
8480 case OMPD_taskloop_simd:
8481 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008482 // Do not capture if-clause expressions.
8483 break;
8484 case OMPD_threadprivate:
8485 case OMPD_taskyield:
8486 case OMPD_barrier:
8487 case OMPD_taskwait:
8488 case OMPD_cancellation_point:
8489 case OMPD_flush:
8490 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008491 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008492 case OMPD_declare_simd:
8493 case OMPD_declare_target:
8494 case OMPD_end_declare_target:
8495 case OMPD_teams:
8496 case OMPD_simd:
8497 case OMPD_for:
8498 case OMPD_for_simd:
8499 case OMPD_sections:
8500 case OMPD_section:
8501 case OMPD_single:
8502 case OMPD_master:
8503 case OMPD_critical:
8504 case OMPD_taskgroup:
8505 case OMPD_distribute:
8506 case OMPD_ordered:
8507 case OMPD_atomic:
8508 case OMPD_distribute_simd:
8509 case OMPD_teams_distribute:
8510 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008511 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008512 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8513 case OMPD_unknown:
8514 llvm_unreachable("Unknown OpenMP directive");
8515 }
8516 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008517 case OMPC_num_threads:
8518 switch (DKind) {
8519 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008520 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008521 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008522 CaptureRegion = OMPD_target;
8523 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008524 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008525 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008526 case OMPD_target_teams_distribute_parallel_for:
8527 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008528 CaptureRegion = OMPD_teams;
8529 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008530 case OMPD_parallel:
8531 case OMPD_parallel_sections:
8532 case OMPD_parallel_for:
8533 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008534 case OMPD_distribute_parallel_for:
8535 case OMPD_distribute_parallel_for_simd:
8536 // Do not capture num_threads-clause expressions.
8537 break;
8538 case OMPD_target_data:
8539 case OMPD_target_enter_data:
8540 case OMPD_target_exit_data:
8541 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008542 case OMPD_target:
8543 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008544 case OMPD_target_teams:
8545 case OMPD_target_teams_distribute:
8546 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008547 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008548 case OMPD_task:
8549 case OMPD_taskloop:
8550 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008551 case OMPD_threadprivate:
8552 case OMPD_taskyield:
8553 case OMPD_barrier:
8554 case OMPD_taskwait:
8555 case OMPD_cancellation_point:
8556 case OMPD_flush:
8557 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008558 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008559 case OMPD_declare_simd:
8560 case OMPD_declare_target:
8561 case OMPD_end_declare_target:
8562 case OMPD_teams:
8563 case OMPD_simd:
8564 case OMPD_for:
8565 case OMPD_for_simd:
8566 case OMPD_sections:
8567 case OMPD_section:
8568 case OMPD_single:
8569 case OMPD_master:
8570 case OMPD_critical:
8571 case OMPD_taskgroup:
8572 case OMPD_distribute:
8573 case OMPD_ordered:
8574 case OMPD_atomic:
8575 case OMPD_distribute_simd:
8576 case OMPD_teams_distribute:
8577 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008578 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008579 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8580 case OMPD_unknown:
8581 llvm_unreachable("Unknown OpenMP directive");
8582 }
8583 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008584 case OMPC_num_teams:
8585 switch (DKind) {
8586 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008587 case OMPD_target_teams_distribute:
8588 case OMPD_target_teams_distribute_simd:
8589 case OMPD_target_teams_distribute_parallel_for:
8590 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008591 CaptureRegion = OMPD_target;
8592 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008593 case OMPD_teams_distribute_parallel_for:
8594 case OMPD_teams_distribute_parallel_for_simd:
8595 case OMPD_teams:
8596 case OMPD_teams_distribute:
8597 case OMPD_teams_distribute_simd:
8598 // Do not capture num_teams-clause expressions.
8599 break;
8600 case OMPD_distribute_parallel_for:
8601 case OMPD_distribute_parallel_for_simd:
8602 case OMPD_task:
8603 case OMPD_taskloop:
8604 case OMPD_taskloop_simd:
8605 case OMPD_target_data:
8606 case OMPD_target_enter_data:
8607 case OMPD_target_exit_data:
8608 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008609 case OMPD_cancel:
8610 case OMPD_parallel:
8611 case OMPD_parallel_sections:
8612 case OMPD_parallel_for:
8613 case OMPD_parallel_for_simd:
8614 case OMPD_target:
8615 case OMPD_target_simd:
8616 case OMPD_target_parallel:
8617 case OMPD_target_parallel_for:
8618 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008619 case OMPD_threadprivate:
8620 case OMPD_taskyield:
8621 case OMPD_barrier:
8622 case OMPD_taskwait:
8623 case OMPD_cancellation_point:
8624 case OMPD_flush:
8625 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008626 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008627 case OMPD_declare_simd:
8628 case OMPD_declare_target:
8629 case OMPD_end_declare_target:
8630 case OMPD_simd:
8631 case OMPD_for:
8632 case OMPD_for_simd:
8633 case OMPD_sections:
8634 case OMPD_section:
8635 case OMPD_single:
8636 case OMPD_master:
8637 case OMPD_critical:
8638 case OMPD_taskgroup:
8639 case OMPD_distribute:
8640 case OMPD_ordered:
8641 case OMPD_atomic:
8642 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008643 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008644 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8645 case OMPD_unknown:
8646 llvm_unreachable("Unknown OpenMP directive");
8647 }
8648 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008649 case OMPC_thread_limit:
8650 switch (DKind) {
8651 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008652 case OMPD_target_teams_distribute:
8653 case OMPD_target_teams_distribute_simd:
8654 case OMPD_target_teams_distribute_parallel_for:
8655 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008656 CaptureRegion = OMPD_target;
8657 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008658 case OMPD_teams_distribute_parallel_for:
8659 case OMPD_teams_distribute_parallel_for_simd:
8660 case OMPD_teams:
8661 case OMPD_teams_distribute:
8662 case OMPD_teams_distribute_simd:
8663 // Do not capture thread_limit-clause expressions.
8664 break;
8665 case OMPD_distribute_parallel_for:
8666 case OMPD_distribute_parallel_for_simd:
8667 case OMPD_task:
8668 case OMPD_taskloop:
8669 case OMPD_taskloop_simd:
8670 case OMPD_target_data:
8671 case OMPD_target_enter_data:
8672 case OMPD_target_exit_data:
8673 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008674 case OMPD_cancel:
8675 case OMPD_parallel:
8676 case OMPD_parallel_sections:
8677 case OMPD_parallel_for:
8678 case OMPD_parallel_for_simd:
8679 case OMPD_target:
8680 case OMPD_target_simd:
8681 case OMPD_target_parallel:
8682 case OMPD_target_parallel_for:
8683 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008684 case OMPD_threadprivate:
8685 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 Jacob7ecc0b72017-01-25 11:44:35 +00008692 case OMPD_declare_simd:
8693 case OMPD_declare_target:
8694 case OMPD_end_declare_target:
8695 case OMPD_simd:
8696 case OMPD_for:
8697 case OMPD_for_simd:
8698 case OMPD_sections:
8699 case OMPD_section:
8700 case OMPD_single:
8701 case OMPD_master:
8702 case OMPD_critical:
8703 case OMPD_taskgroup:
8704 case OMPD_distribute:
8705 case OMPD_ordered:
8706 case OMPD_atomic:
8707 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008708 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008709 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8710 case OMPD_unknown:
8711 llvm_unreachable("Unknown OpenMP directive");
8712 }
8713 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008714 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008715 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008716 case OMPD_parallel_for:
8717 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008718 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008719 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008720 case OMPD_teams_distribute_parallel_for:
8721 case OMPD_teams_distribute_parallel_for_simd:
8722 case OMPD_target_parallel_for:
8723 case OMPD_target_parallel_for_simd:
8724 case OMPD_target_teams_distribute_parallel_for:
8725 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008726 CaptureRegion = OMPD_parallel;
8727 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008728 case OMPD_for:
8729 case OMPD_for_simd:
8730 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008731 break;
8732 case OMPD_task:
8733 case OMPD_taskloop:
8734 case OMPD_taskloop_simd:
8735 case OMPD_target_data:
8736 case OMPD_target_enter_data:
8737 case OMPD_target_exit_data:
8738 case OMPD_target_update:
8739 case OMPD_teams:
8740 case OMPD_teams_distribute:
8741 case OMPD_teams_distribute_simd:
8742 case OMPD_target_teams_distribute:
8743 case OMPD_target_teams_distribute_simd:
8744 case OMPD_target:
8745 case OMPD_target_simd:
8746 case OMPD_target_parallel:
8747 case OMPD_cancel:
8748 case OMPD_parallel:
8749 case OMPD_parallel_sections:
8750 case OMPD_threadprivate:
8751 case OMPD_taskyield:
8752 case OMPD_barrier:
8753 case OMPD_taskwait:
8754 case OMPD_cancellation_point:
8755 case OMPD_flush:
8756 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008757 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008758 case OMPD_declare_simd:
8759 case OMPD_declare_target:
8760 case OMPD_end_declare_target:
8761 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008762 case OMPD_sections:
8763 case OMPD_section:
8764 case OMPD_single:
8765 case OMPD_master:
8766 case OMPD_critical:
8767 case OMPD_taskgroup:
8768 case OMPD_distribute:
8769 case OMPD_ordered:
8770 case OMPD_atomic:
8771 case OMPD_distribute_simd:
8772 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008773 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008774 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8775 case OMPD_unknown:
8776 llvm_unreachable("Unknown OpenMP directive");
8777 }
8778 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008779 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008780 switch (DKind) {
8781 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008782 case OMPD_teams_distribute_parallel_for_simd:
8783 case OMPD_teams_distribute:
8784 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008785 case OMPD_target_teams_distribute_parallel_for:
8786 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008787 case OMPD_target_teams_distribute:
8788 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008789 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008790 break;
8791 case OMPD_distribute_parallel_for:
8792 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008793 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008794 case OMPD_distribute_simd:
8795 // Do not capture thread_limit-clause expressions.
8796 break;
8797 case OMPD_parallel_for:
8798 case OMPD_parallel_for_simd:
8799 case OMPD_target_parallel_for_simd:
8800 case OMPD_target_parallel_for:
8801 case OMPD_task:
8802 case OMPD_taskloop:
8803 case OMPD_taskloop_simd:
8804 case OMPD_target_data:
8805 case OMPD_target_enter_data:
8806 case OMPD_target_exit_data:
8807 case OMPD_target_update:
8808 case OMPD_teams:
8809 case OMPD_target:
8810 case OMPD_target_simd:
8811 case OMPD_target_parallel:
8812 case OMPD_cancel:
8813 case OMPD_parallel:
8814 case OMPD_parallel_sections:
8815 case OMPD_threadprivate:
8816 case OMPD_taskyield:
8817 case OMPD_barrier:
8818 case OMPD_taskwait:
8819 case OMPD_cancellation_point:
8820 case OMPD_flush:
8821 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008822 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008823 case OMPD_declare_simd:
8824 case OMPD_declare_target:
8825 case OMPD_end_declare_target:
8826 case OMPD_simd:
8827 case OMPD_for:
8828 case OMPD_for_simd:
8829 case OMPD_sections:
8830 case OMPD_section:
8831 case OMPD_single:
8832 case OMPD_master:
8833 case OMPD_critical:
8834 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008835 case OMPD_ordered:
8836 case OMPD_atomic:
8837 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008838 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008839 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8840 case OMPD_unknown:
8841 llvm_unreachable("Unknown OpenMP directive");
8842 }
8843 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008844 case OMPC_device:
8845 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008846 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008847 case OMPD_target_enter_data:
8848 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008849 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008850 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008851 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008852 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008853 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008854 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008855 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008856 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008857 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008858 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008859 CaptureRegion = OMPD_task;
8860 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008861 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008862 // Do not capture device-clause expressions.
8863 break;
8864 case OMPD_teams_distribute_parallel_for:
8865 case OMPD_teams_distribute_parallel_for_simd:
8866 case OMPD_teams:
8867 case OMPD_teams_distribute:
8868 case OMPD_teams_distribute_simd:
8869 case OMPD_distribute_parallel_for:
8870 case OMPD_distribute_parallel_for_simd:
8871 case OMPD_task:
8872 case OMPD_taskloop:
8873 case OMPD_taskloop_simd:
8874 case OMPD_cancel:
8875 case OMPD_parallel:
8876 case OMPD_parallel_sections:
8877 case OMPD_parallel_for:
8878 case OMPD_parallel_for_simd:
8879 case OMPD_threadprivate:
8880 case OMPD_taskyield:
8881 case OMPD_barrier:
8882 case OMPD_taskwait:
8883 case OMPD_cancellation_point:
8884 case OMPD_flush:
8885 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008886 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008887 case OMPD_declare_simd:
8888 case OMPD_declare_target:
8889 case OMPD_end_declare_target:
8890 case OMPD_simd:
8891 case OMPD_for:
8892 case OMPD_for_simd:
8893 case OMPD_sections:
8894 case OMPD_section:
8895 case OMPD_single:
8896 case OMPD_master:
8897 case OMPD_critical:
8898 case OMPD_taskgroup:
8899 case OMPD_distribute:
8900 case OMPD_ordered:
8901 case OMPD_atomic:
8902 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008903 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008904 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8905 case OMPD_unknown:
8906 llvm_unreachable("Unknown OpenMP directive");
8907 }
8908 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008909 case OMPC_firstprivate:
8910 case OMPC_lastprivate:
8911 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008912 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008913 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008914 case OMPC_linear:
8915 case OMPC_default:
8916 case OMPC_proc_bind:
8917 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008918 case OMPC_safelen:
8919 case OMPC_simdlen:
8920 case OMPC_collapse:
8921 case OMPC_private:
8922 case OMPC_shared:
8923 case OMPC_aligned:
8924 case OMPC_copyin:
8925 case OMPC_copyprivate:
8926 case OMPC_ordered:
8927 case OMPC_nowait:
8928 case OMPC_untied:
8929 case OMPC_mergeable:
8930 case OMPC_threadprivate:
8931 case OMPC_flush:
8932 case OMPC_read:
8933 case OMPC_write:
8934 case OMPC_update:
8935 case OMPC_capture:
8936 case OMPC_seq_cst:
8937 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008938 case OMPC_threads:
8939 case OMPC_simd:
8940 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008941 case OMPC_priority:
8942 case OMPC_grainsize:
8943 case OMPC_nogroup:
8944 case OMPC_num_tasks:
8945 case OMPC_hint:
8946 case OMPC_defaultmap:
8947 case OMPC_unknown:
8948 case OMPC_uniform:
8949 case OMPC_to:
8950 case OMPC_from:
8951 case OMPC_use_device_ptr:
8952 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008953 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008954 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008955 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008956 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008957 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008958 llvm_unreachable("Unexpected OpenMP clause.");
8959 }
8960 return CaptureRegion;
8961}
8962
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008963OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8964 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008965 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008966 SourceLocation NameModifierLoc,
8967 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008968 SourceLocation EndLoc) {
8969 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008970 Stmt *HelperValStmt = nullptr;
8971 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008972 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8973 !Condition->isInstantiationDependent() &&
8974 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008975 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008976 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008977 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008978
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008979 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008980
8981 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8982 CaptureRegion =
8983 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008984 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008985 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008986 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008987 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8988 HelperValStmt = buildPreInits(Context, Captures);
8989 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008990 }
8991
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008992 return new (Context)
8993 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8994 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008995}
8996
Alexey Bataev3778b602014-07-17 07:32:53 +00008997OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8998 SourceLocation StartLoc,
8999 SourceLocation LParenLoc,
9000 SourceLocation EndLoc) {
9001 Expr *ValExpr = Condition;
9002 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9003 !Condition->isInstantiationDependent() &&
9004 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009005 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009006 if (Val.isInvalid())
9007 return nullptr;
9008
Richard Smith03a4aa32016-06-23 19:02:52 +00009009 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009010 }
9011
9012 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9013}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009014ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9015 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009016 if (!Op)
9017 return ExprError();
9018
9019 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9020 public:
9021 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009022 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009023 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9024 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009025 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9026 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009027 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9028 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009029 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9030 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009031 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9032 QualType T,
9033 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009034 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9035 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009036 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9037 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009038 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009039 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009040 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009041 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9042 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009043 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9044 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009045 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9046 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009047 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009048 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009049 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009050 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9051 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009052 llvm_unreachable("conversion functions are permitted");
9053 }
9054 } ConvertDiagnoser;
9055 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9056}
9057
Alexey Bataeve3727102018-04-18 15:57:46 +00009058static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009059 OpenMPClauseKind CKind,
9060 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009061 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9062 !ValExpr->isInstantiationDependent()) {
9063 SourceLocation Loc = ValExpr->getExprLoc();
9064 ExprResult Value =
9065 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9066 if (Value.isInvalid())
9067 return false;
9068
9069 ValExpr = Value.get();
9070 // The expression must evaluate to a non-negative integer value.
9071 llvm::APSInt Result;
9072 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009073 Result.isSigned() &&
9074 !((!StrictlyPositive && Result.isNonNegative()) ||
9075 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009076 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009077 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9078 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009079 return false;
9080 }
9081 }
9082 return true;
9083}
9084
Alexey Bataev568a8332014-03-06 06:15:19 +00009085OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9086 SourceLocation StartLoc,
9087 SourceLocation LParenLoc,
9088 SourceLocation EndLoc) {
9089 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009090 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009091
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009092 // OpenMP [2.5, Restrictions]
9093 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009094 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009095 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009096 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009097
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009098 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009099 OpenMPDirectiveKind CaptureRegion =
9100 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9101 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009102 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009103 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009104 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9105 HelperValStmt = buildPreInits(Context, Captures);
9106 }
9107
9108 return new (Context) OMPNumThreadsClause(
9109 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009110}
9111
Alexey Bataev62c87d22014-03-21 04:51:18 +00009112ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009113 OpenMPClauseKind CKind,
9114 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009115 if (!E)
9116 return ExprError();
9117 if (E->isValueDependent() || E->isTypeDependent() ||
9118 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009119 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009120 llvm::APSInt Result;
9121 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9122 if (ICE.isInvalid())
9123 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009124 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9125 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009126 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009127 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9128 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009129 return ExprError();
9130 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009131 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9132 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9133 << E->getSourceRange();
9134 return ExprError();
9135 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009136 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9137 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009138 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009139 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009140 return ICE;
9141}
9142
9143OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9144 SourceLocation LParenLoc,
9145 SourceLocation EndLoc) {
9146 // OpenMP [2.8.1, simd construct, Description]
9147 // The parameter of the safelen clause must be a constant
9148 // positive integer expression.
9149 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9150 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009151 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009152 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009153 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009154}
9155
Alexey Bataev66b15b52015-08-21 11:14:16 +00009156OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9157 SourceLocation LParenLoc,
9158 SourceLocation EndLoc) {
9159 // OpenMP [2.8.1, simd construct, Description]
9160 // The parameter of the simdlen clause must be a constant
9161 // positive integer expression.
9162 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9163 if (Simdlen.isInvalid())
9164 return nullptr;
9165 return new (Context)
9166 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9167}
9168
Alexander Musman64d33f12014-06-04 07:53:32 +00009169OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9170 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009171 SourceLocation LParenLoc,
9172 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009173 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009174 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009175 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009176 // The parameter of the collapse clause must be a constant
9177 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009178 ExprResult NumForLoopsResult =
9179 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9180 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009181 return nullptr;
9182 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009183 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009184}
9185
Alexey Bataev10e775f2015-07-30 11:36:16 +00009186OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9187 SourceLocation EndLoc,
9188 SourceLocation LParenLoc,
9189 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009190 // OpenMP [2.7.1, loop construct, Description]
9191 // OpenMP [2.8.1, simd construct, Description]
9192 // OpenMP [2.9.6, distribute construct, Description]
9193 // The parameter of the ordered clause must be a constant
9194 // positive integer expression if any.
9195 if (NumForLoops && LParenLoc.isValid()) {
9196 ExprResult NumForLoopsResult =
9197 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9198 if (NumForLoopsResult.isInvalid())
9199 return nullptr;
9200 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009201 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009202 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009203 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009204 auto *Clause = OMPOrderedClause::Create(
9205 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9206 StartLoc, LParenLoc, EndLoc);
9207 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9208 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009209}
9210
Alexey Bataeved09d242014-05-28 05:53:51 +00009211OMPClause *Sema::ActOnOpenMPSimpleClause(
9212 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9213 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009214 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009215 switch (Kind) {
9216 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009217 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009218 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9219 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009220 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009221 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009222 Res = ActOnOpenMPProcBindClause(
9223 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9224 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009225 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009226 case OMPC_atomic_default_mem_order:
9227 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9228 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9229 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9230 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009231 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009232 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009233 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009234 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009235 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009236 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009237 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009238 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009239 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009240 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009241 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009242 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009243 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009244 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009245 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009246 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009247 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009248 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009249 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009250 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009251 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009252 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009253 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009254 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009255 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009256 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009257 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009258 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009259 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009260 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009261 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009262 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009263 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009264 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009265 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009266 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009267 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009268 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009269 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009270 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009271 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009272 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009273 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009274 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009275 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009276 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009277 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009278 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009279 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009280 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009281 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009282 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009283 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009284 llvm_unreachable("Clause is not allowed.");
9285 }
9286 return Res;
9287}
9288
Alexey Bataev6402bca2015-12-28 07:25:51 +00009289static std::string
9290getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9291 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009292 SmallString<256> Buffer;
9293 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009294 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9295 unsigned Skipped = Exclude.size();
9296 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009297 for (unsigned I = First; I < Last; ++I) {
9298 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009299 --Skipped;
9300 continue;
9301 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009302 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9303 if (I == Bound - Skipped)
9304 Out << " or ";
9305 else if (I != Bound + 1 - Skipped)
9306 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009307 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009308 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009309}
9310
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009311OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9312 SourceLocation KindKwLoc,
9313 SourceLocation StartLoc,
9314 SourceLocation LParenLoc,
9315 SourceLocation EndLoc) {
9316 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009317 static_assert(OMPC_DEFAULT_unknown > 0,
9318 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009319 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009320 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9321 /*Last=*/OMPC_DEFAULT_unknown)
9322 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009323 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009324 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009325 switch (Kind) {
9326 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009327 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009328 break;
9329 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009330 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009331 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009332 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009333 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009334 break;
9335 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009336 return new (Context)
9337 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009338}
9339
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009340OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9341 SourceLocation KindKwLoc,
9342 SourceLocation StartLoc,
9343 SourceLocation LParenLoc,
9344 SourceLocation EndLoc) {
9345 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009346 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009347 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9348 /*Last=*/OMPC_PROC_BIND_unknown)
9349 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009350 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009351 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009352 return new (Context)
9353 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009354}
9355
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009356OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9357 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9358 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9359 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9360 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9361 << getListOfPossibleValues(
9362 OMPC_atomic_default_mem_order, /*First=*/0,
9363 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9364 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9365 return nullptr;
9366 }
9367 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9368 LParenLoc, EndLoc);
9369}
9370
Alexey Bataev56dafe82014-06-20 07:16:17 +00009371OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009372 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009373 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009374 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009375 SourceLocation EndLoc) {
9376 OMPClause *Res = nullptr;
9377 switch (Kind) {
9378 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009379 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9380 assert(Argument.size() == NumberOfElements &&
9381 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009382 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009383 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9384 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9385 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9386 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9387 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009388 break;
9389 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009390 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9391 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9392 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9393 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009394 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009395 case OMPC_dist_schedule:
9396 Res = ActOnOpenMPDistScheduleClause(
9397 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9398 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9399 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009400 case OMPC_defaultmap:
9401 enum { Modifier, DefaultmapKind };
9402 Res = ActOnOpenMPDefaultmapClause(
9403 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9404 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009405 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9406 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009407 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009408 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009409 case OMPC_num_threads:
9410 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009411 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009412 case OMPC_collapse:
9413 case OMPC_default:
9414 case OMPC_proc_bind:
9415 case OMPC_private:
9416 case OMPC_firstprivate:
9417 case OMPC_lastprivate:
9418 case OMPC_shared:
9419 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009420 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009421 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009422 case OMPC_linear:
9423 case OMPC_aligned:
9424 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009425 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009426 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009427 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009428 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009429 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009430 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009431 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009432 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009433 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009434 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009435 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009436 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009437 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009438 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009439 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009440 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009441 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009442 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009443 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009444 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009445 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009446 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009447 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009448 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009449 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009450 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009451 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009452 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009453 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009454 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009455 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009456 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009457 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009458 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009459 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009460 llvm_unreachable("Clause is not allowed.");
9461 }
9462 return Res;
9463}
9464
Alexey Bataev6402bca2015-12-28 07:25:51 +00009465static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9466 OpenMPScheduleClauseModifier M2,
9467 SourceLocation M1Loc, SourceLocation M2Loc) {
9468 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9469 SmallVector<unsigned, 2> Excluded;
9470 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9471 Excluded.push_back(M2);
9472 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9473 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9474 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9475 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9476 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9477 << getListOfPossibleValues(OMPC_schedule,
9478 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9479 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9480 Excluded)
9481 << getOpenMPClauseName(OMPC_schedule);
9482 return true;
9483 }
9484 return false;
9485}
9486
Alexey Bataev56dafe82014-06-20 07:16:17 +00009487OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009488 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009489 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009490 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9491 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9492 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9493 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9494 return nullptr;
9495 // OpenMP, 2.7.1, Loop Construct, Restrictions
9496 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9497 // but not both.
9498 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9499 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9500 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9501 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9502 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9503 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9504 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9505 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9506 return nullptr;
9507 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009508 if (Kind == OMPC_SCHEDULE_unknown) {
9509 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009510 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9511 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9512 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9513 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9514 Exclude);
9515 } else {
9516 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9517 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009518 }
9519 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9520 << Values << getOpenMPClauseName(OMPC_schedule);
9521 return nullptr;
9522 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009523 // OpenMP, 2.7.1, Loop Construct, Restrictions
9524 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9525 // schedule(guided).
9526 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9527 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9528 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9529 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9530 diag::err_omp_schedule_nonmonotonic_static);
9531 return nullptr;
9532 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009533 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009534 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009535 if (ChunkSize) {
9536 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9537 !ChunkSize->isInstantiationDependent() &&
9538 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009539 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009540 ExprResult Val =
9541 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9542 if (Val.isInvalid())
9543 return nullptr;
9544
9545 ValExpr = Val.get();
9546
9547 // OpenMP [2.7.1, Restrictions]
9548 // chunk_size must be a loop invariant integer expression with a positive
9549 // value.
9550 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009551 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9552 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9553 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009554 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009555 return nullptr;
9556 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009557 } else if (getOpenMPCaptureRegionForClause(
9558 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9559 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009560 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009561 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009562 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009563 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9564 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009565 }
9566 }
9567 }
9568
Alexey Bataev6402bca2015-12-28 07:25:51 +00009569 return new (Context)
9570 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009571 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009572}
9573
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009574OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9575 SourceLocation StartLoc,
9576 SourceLocation EndLoc) {
9577 OMPClause *Res = nullptr;
9578 switch (Kind) {
9579 case OMPC_ordered:
9580 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9581 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009582 case OMPC_nowait:
9583 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9584 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009585 case OMPC_untied:
9586 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9587 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009588 case OMPC_mergeable:
9589 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9590 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009591 case OMPC_read:
9592 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9593 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009594 case OMPC_write:
9595 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9596 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009597 case OMPC_update:
9598 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9599 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009600 case OMPC_capture:
9601 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9602 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009603 case OMPC_seq_cst:
9604 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9605 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009606 case OMPC_threads:
9607 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9608 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009609 case OMPC_simd:
9610 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9611 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009612 case OMPC_nogroup:
9613 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9614 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009615 case OMPC_unified_address:
9616 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9617 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009618 case OMPC_unified_shared_memory:
9619 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9620 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009621 case OMPC_reverse_offload:
9622 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9623 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009624 case OMPC_dynamic_allocators:
9625 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9626 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009627 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009628 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009629 case OMPC_num_threads:
9630 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009631 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009632 case OMPC_collapse:
9633 case OMPC_schedule:
9634 case OMPC_private:
9635 case OMPC_firstprivate:
9636 case OMPC_lastprivate:
9637 case OMPC_shared:
9638 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009639 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009640 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009641 case OMPC_linear:
9642 case OMPC_aligned:
9643 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009644 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009645 case OMPC_default:
9646 case OMPC_proc_bind:
9647 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009648 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009649 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009650 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009651 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009652 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009653 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009654 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009655 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009656 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009657 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009658 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009659 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009660 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009661 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009662 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009663 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009664 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009665 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009666 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009667 llvm_unreachable("Clause is not allowed.");
9668 }
9669 return Res;
9670}
9671
Alexey Bataev236070f2014-06-20 11:19:47 +00009672OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9673 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009674 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009675 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9676}
9677
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009678OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9679 SourceLocation EndLoc) {
9680 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9681}
9682
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009683OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9684 SourceLocation EndLoc) {
9685 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9686}
9687
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009688OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9689 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009690 return new (Context) OMPReadClause(StartLoc, EndLoc);
9691}
9692
Alexey Bataevdea47612014-07-23 07:46:59 +00009693OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9694 SourceLocation EndLoc) {
9695 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9696}
9697
Alexey Bataev67a4f222014-07-23 10:25:33 +00009698OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9699 SourceLocation EndLoc) {
9700 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9701}
9702
Alexey Bataev459dec02014-07-24 06:46:57 +00009703OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9704 SourceLocation EndLoc) {
9705 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9706}
9707
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009708OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9709 SourceLocation EndLoc) {
9710 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9711}
9712
Alexey Bataev346265e2015-09-25 10:37:12 +00009713OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9714 SourceLocation EndLoc) {
9715 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9716}
9717
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009718OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9719 SourceLocation EndLoc) {
9720 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9721}
9722
Alexey Bataevb825de12015-12-07 10:51:44 +00009723OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9724 SourceLocation EndLoc) {
9725 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9726}
9727
Kelvin Li1408f912018-09-26 04:28:39 +00009728OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9729 SourceLocation EndLoc) {
9730 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9731}
9732
Patrick Lyster4a370b92018-10-01 13:47:43 +00009733OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9734 SourceLocation EndLoc) {
9735 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9736}
9737
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009738OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9739 SourceLocation EndLoc) {
9740 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9741}
9742
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009743OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9744 SourceLocation EndLoc) {
9745 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9746}
9747
Alexey Bataevc5e02582014-06-16 07:08:35 +00009748OMPClause *Sema::ActOnOpenMPVarListClause(
9749 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009750 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
9751 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
9752 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +00009753 OpenMPLinearClauseKind LinKind,
9754 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009755 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
9756 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
9757 SourceLocation StartLoc = Locs.StartLoc;
9758 SourceLocation LParenLoc = Locs.LParenLoc;
9759 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009760 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009761 switch (Kind) {
9762 case OMPC_private:
9763 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9764 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009765 case OMPC_firstprivate:
9766 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9767 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009768 case OMPC_lastprivate:
9769 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9770 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009771 case OMPC_shared:
9772 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9773 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009774 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009775 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009776 EndLoc, ReductionOrMapperIdScopeSpec,
9777 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009778 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009779 case OMPC_task_reduction:
9780 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009781 EndLoc, ReductionOrMapperIdScopeSpec,
9782 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +00009783 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009784 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009785 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9786 EndLoc, ReductionOrMapperIdScopeSpec,
9787 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +00009788 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009789 case OMPC_linear:
9790 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009791 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009792 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009793 case OMPC_aligned:
9794 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9795 ColonLoc, EndLoc);
9796 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009797 case OMPC_copyin:
9798 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9799 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009800 case OMPC_copyprivate:
9801 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9802 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009803 case OMPC_flush:
9804 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9805 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009806 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009807 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009808 StartLoc, LParenLoc, EndLoc);
9809 break;
9810 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009811 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
9812 ReductionOrMapperIdScopeSpec,
9813 ReductionOrMapperId, MapType, IsMapTypeImplicit,
9814 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009815 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009816 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +00009817 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
9818 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +00009819 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009820 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +00009821 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
9822 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +00009823 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009824 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009825 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +00009826 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009827 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009828 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +00009829 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009830 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009831 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009832 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009833 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009834 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009835 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009836 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009837 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009838 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009839 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009840 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009841 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009842 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009843 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009844 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009845 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009846 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009847 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009848 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009849 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009850 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009851 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009852 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009853 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009854 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009855 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009856 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009857 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009858 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009859 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009860 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009861 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009862 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +00009863 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009864 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009865 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009866 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009867 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009868 llvm_unreachable("Clause is not allowed.");
9869 }
9870 return Res;
9871}
9872
Alexey Bataev90c228f2016-02-08 09:29:13 +00009873ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009874 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009875 ExprResult Res = BuildDeclRefExpr(
9876 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9877 if (!Res.isUsable())
9878 return ExprError();
9879 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9880 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9881 if (!Res.isUsable())
9882 return ExprError();
9883 }
9884 if (VK != VK_LValue && Res.get()->isGLValue()) {
9885 Res = DefaultLvalueConversion(Res.get());
9886 if (!Res.isUsable())
9887 return ExprError();
9888 }
9889 return Res;
9890}
9891
Alexey Bataev60da77e2016-02-29 05:54:20 +00009892static std::pair<ValueDecl *, bool>
9893getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9894 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009895 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9896 RefExpr->containsUnexpandedParameterPack())
9897 return std::make_pair(nullptr, true);
9898
Alexey Bataevd985eda2016-02-10 11:29:16 +00009899 // OpenMP [3.1, C/C++]
9900 // A list item is a variable name.
9901 // OpenMP [2.9.3.3, Restrictions, p.1]
9902 // A variable that is part of another variable (as an array or
9903 // structure element) cannot appear in a private clause.
9904 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009905 enum {
9906 NoArrayExpr = -1,
9907 ArraySubscript = 0,
9908 OMPArraySection = 1
9909 } IsArrayExpr = NoArrayExpr;
9910 if (AllowArraySection) {
9911 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009912 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009913 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9914 Base = TempASE->getBase()->IgnoreParenImpCasts();
9915 RefExpr = Base;
9916 IsArrayExpr = ArraySubscript;
9917 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009918 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009919 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9920 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9921 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9922 Base = TempASE->getBase()->IgnoreParenImpCasts();
9923 RefExpr = Base;
9924 IsArrayExpr = OMPArraySection;
9925 }
9926 }
9927 ELoc = RefExpr->getExprLoc();
9928 ERange = RefExpr->getSourceRange();
9929 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009930 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9931 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9932 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9933 (S.getCurrentThisType().isNull() || !ME ||
9934 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9935 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009936 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009937 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9938 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009939 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009940 S.Diag(ELoc,
9941 AllowArraySection
9942 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9943 : diag::err_omp_expected_var_name_member_expr)
9944 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9945 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009946 return std::make_pair(nullptr, false);
9947 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009948 return std::make_pair(
9949 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009950}
9951
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009952OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9953 SourceLocation StartLoc,
9954 SourceLocation LParenLoc,
9955 SourceLocation EndLoc) {
9956 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009957 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00009958 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009959 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009960 SourceLocation ELoc;
9961 SourceRange ERange;
9962 Expr *SimpleRefExpr = RefExpr;
9963 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009964 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009965 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009966 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009967 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009968 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009969 ValueDecl *D = Res.first;
9970 if (!D)
9971 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009972
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009973 QualType Type = D->getType();
9974 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009975
9976 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9977 // A variable that appears in a private clause must not have an incomplete
9978 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009979 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009980 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009981 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009982
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009983 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
9984 // A variable that is privatized must not have a const-qualified type
9985 // unless it is of class type with a mutable member. This restriction does
9986 // not apply to the firstprivate clause.
9987 //
9988 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
9989 // A variable that appears in a private clause must not have a
9990 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +00009991 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009992 continue;
9993
Alexey Bataev758e55e2013-09-06 18:03:48 +00009994 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9995 // in a Construct]
9996 // Variables with the predetermined data-sharing attributes may not be
9997 // listed in data-sharing attributes clauses, except for the cases
9998 // listed below. For these exceptions only, listing a predetermined
9999 // variable in a data-sharing attribute clause is allowed and overrides
10000 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010001 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010002 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010003 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10004 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010005 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010006 continue;
10007 }
10008
Alexey Bataeve3727102018-04-18 15:57:46 +000010009 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010010 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010011 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010012 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010013 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10014 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010015 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010016 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010017 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010018 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010019 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010020 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010021 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010022 continue;
10023 }
10024
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010025 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10026 // A list item cannot appear in both a map clause and a data-sharing
10027 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010028 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010029 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010030 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010031 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010032 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10033 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10034 ConflictKind = WhereFoundClauseKind;
10035 return true;
10036 })) {
10037 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010038 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010039 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010040 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010041 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010042 continue;
10043 }
10044 }
10045
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010046 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10047 // A variable of class type (or array thereof) that appears in a private
10048 // clause requires an accessible, unambiguous default constructor for the
10049 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010050 // Generate helper private variable and initialize it with the default
10051 // value. The address of the original variable is replaced by the address of
10052 // the new private variable in CodeGen. This new variable is not added to
10053 // IdResolver, so the code in the OpenMP region uses original variable for
10054 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010055 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010056 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010057 buildVarDecl(*this, ELoc, Type, D->getName(),
10058 D->hasAttrs() ? &D->getAttrs() : nullptr,
10059 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010060 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010061 if (VDPrivate->isInvalidDecl())
10062 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010063 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010064 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010065
Alexey Bataev90c228f2016-02-08 09:29:13 +000010066 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010067 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010068 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010069 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010070 Vars.push_back((VD || CurContext->isDependentContext())
10071 ? RefExpr->IgnoreParens()
10072 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010073 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010074 }
10075
Alexey Bataeved09d242014-05-28 05:53:51 +000010076 if (Vars.empty())
10077 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010078
Alexey Bataev03b340a2014-10-21 03:16:40 +000010079 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10080 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010081}
10082
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010083namespace {
10084class DiagsUninitializedSeveretyRAII {
10085private:
10086 DiagnosticsEngine &Diags;
10087 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010088 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010089
10090public:
10091 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10092 bool IsIgnored)
10093 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10094 if (!IsIgnored) {
10095 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10096 /*Map*/ diag::Severity::Ignored, Loc);
10097 }
10098 }
10099 ~DiagsUninitializedSeveretyRAII() {
10100 if (!IsIgnored)
10101 Diags.popMappings(SavedLoc);
10102 }
10103};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010104}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010105
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010106OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10107 SourceLocation StartLoc,
10108 SourceLocation LParenLoc,
10109 SourceLocation EndLoc) {
10110 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010111 SmallVector<Expr *, 8> PrivateCopies;
10112 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010113 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010114 bool IsImplicitClause =
10115 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010116 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010117
Alexey Bataeve3727102018-04-18 15:57:46 +000010118 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010119 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010120 SourceLocation ELoc;
10121 SourceRange ERange;
10122 Expr *SimpleRefExpr = RefExpr;
10123 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010124 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010125 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010126 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010127 PrivateCopies.push_back(nullptr);
10128 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010129 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010130 ValueDecl *D = Res.first;
10131 if (!D)
10132 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010133
Alexey Bataev60da77e2016-02-29 05:54:20 +000010134 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010135 QualType Type = D->getType();
10136 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010137
10138 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10139 // A variable that appears in a private clause must not have an incomplete
10140 // type or a reference type.
10141 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010142 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010143 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010144 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010145
10146 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10147 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010148 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010149 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010150 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010151
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010152 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010153 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010154 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010155 DSAStackTy::DSAVarData DVar =
10156 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010157 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010158 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010159 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010160 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10161 // A list item that specifies a given variable may not appear in more
10162 // than one clause on the same directive, except that a variable may be
10163 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010164 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10165 // A list item may appear in a firstprivate or lastprivate clause but not
10166 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010167 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010168 (isOpenMPDistributeDirective(CurrDir) ||
10169 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010170 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010171 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010172 << getOpenMPClauseName(DVar.CKind)
10173 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010174 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010175 continue;
10176 }
10177
10178 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10179 // in a Construct]
10180 // Variables with the predetermined data-sharing attributes may not be
10181 // listed in data-sharing attributes clauses, except for the cases
10182 // listed below. For these exceptions only, listing a predetermined
10183 // variable in a data-sharing attribute clause is allowed and overrides
10184 // the variable's predetermined data-sharing attributes.
10185 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10186 // in a Construct, C/C++, p.2]
10187 // Variables with const-qualified type having no mutable member may be
10188 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010189 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010190 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10191 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010192 << getOpenMPClauseName(DVar.CKind)
10193 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010194 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010195 continue;
10196 }
10197
10198 // OpenMP [2.9.3.4, Restrictions, p.2]
10199 // A list item that is private within a parallel region must not appear
10200 // in a firstprivate clause on a worksharing construct if any of the
10201 // worksharing regions arising from the worksharing construct ever bind
10202 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010203 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10204 // A list item that is private within a teams region must not appear in a
10205 // firstprivate clause on a distribute construct if any of the distribute
10206 // regions arising from the distribute construct ever bind to any of the
10207 // teams regions arising from the teams construct.
10208 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10209 // A list item that appears in a reduction clause of a teams construct
10210 // must not appear in a firstprivate clause on a distribute construct if
10211 // any of the distribute regions arising from the distribute construct
10212 // ever bind to any of the teams regions arising from the teams construct.
10213 if ((isOpenMPWorksharingDirective(CurrDir) ||
10214 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010215 !isOpenMPParallelDirective(CurrDir) &&
10216 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010217 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010218 if (DVar.CKind != OMPC_shared &&
10219 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010220 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010221 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010222 Diag(ELoc, diag::err_omp_required_access)
10223 << getOpenMPClauseName(OMPC_firstprivate)
10224 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010225 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010226 continue;
10227 }
10228 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010229 // OpenMP [2.9.3.4, Restrictions, p.3]
10230 // A list item that appears in a reduction clause of a parallel construct
10231 // must not appear in a firstprivate clause on a worksharing or task
10232 // construct if any of the worksharing or task regions arising from the
10233 // worksharing or task construct ever bind to any of the parallel regions
10234 // arising from the parallel construct.
10235 // OpenMP [2.9.3.4, Restrictions, p.4]
10236 // A list item that appears in a reduction clause in worksharing
10237 // construct must not appear in a firstprivate clause in a task construct
10238 // encountered during execution of any of the worksharing regions arising
10239 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010240 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010241 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010242 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10243 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010244 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010245 isOpenMPWorksharingDirective(K) ||
10246 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010247 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010248 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010249 if (DVar.CKind == OMPC_reduction &&
10250 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010251 isOpenMPWorksharingDirective(DVar.DKind) ||
10252 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010253 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10254 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010255 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010256 continue;
10257 }
10258 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010259
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010260 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10261 // A list item cannot appear in both a map clause and a data-sharing
10262 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010263 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010264 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010265 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010266 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010267 [&ConflictKind](
10268 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10269 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010270 ConflictKind = WhereFoundClauseKind;
10271 return true;
10272 })) {
10273 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010274 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010275 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010276 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010277 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010278 continue;
10279 }
10280 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010281 }
10282
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010283 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010284 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010285 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010286 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10287 << getOpenMPClauseName(OMPC_firstprivate) << Type
10288 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10289 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010290 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010291 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010292 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010293 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010294 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010295 continue;
10296 }
10297
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010298 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010299 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010300 buildVarDecl(*this, ELoc, Type, D->getName(),
10301 D->hasAttrs() ? &D->getAttrs() : nullptr,
10302 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010303 // Generate helper private variable and initialize it with the value of the
10304 // original variable. The address of the original variable is replaced by
10305 // the address of the new private variable in the CodeGen. This new variable
10306 // is not added to IdResolver, so the code in the OpenMP region uses
10307 // original variable for proper diagnostics and variable capturing.
10308 Expr *VDInitRefExpr = nullptr;
10309 // For arrays generate initializer for single element and replace it by the
10310 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010311 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010312 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010313 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010314 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010315 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010316 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010317 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10318 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010319 InitializedEntity Entity =
10320 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010321 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10322
10323 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10324 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10325 if (Result.isInvalid())
10326 VDPrivate->setInvalidDecl();
10327 else
10328 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010329 // Remove temp variable declaration.
10330 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010331 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010332 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10333 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010334 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10335 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010336 AddInitializerToDecl(VDPrivate,
10337 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010338 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010339 }
10340 if (VDPrivate->isInvalidDecl()) {
10341 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010342 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010343 diag::note_omp_task_predetermined_firstprivate_here);
10344 }
10345 continue;
10346 }
10347 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010348 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010349 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10350 RefExpr->getExprLoc());
10351 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010352 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010353 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010354 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010355 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010356 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010357 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010358 ExprCaptures.push_back(Ref->getDecl());
10359 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010360 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010361 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010362 Vars.push_back((VD || CurContext->isDependentContext())
10363 ? RefExpr->IgnoreParens()
10364 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010365 PrivateCopies.push_back(VDPrivateRefExpr);
10366 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010367 }
10368
Alexey Bataeved09d242014-05-28 05:53:51 +000010369 if (Vars.empty())
10370 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010371
10372 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010373 Vars, PrivateCopies, Inits,
10374 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010375}
10376
Alexander Musman1bb328c2014-06-04 13:06:39 +000010377OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10378 SourceLocation StartLoc,
10379 SourceLocation LParenLoc,
10380 SourceLocation EndLoc) {
10381 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010382 SmallVector<Expr *, 8> SrcExprs;
10383 SmallVector<Expr *, 8> DstExprs;
10384 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010385 SmallVector<Decl *, 4> ExprCaptures;
10386 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010387 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010388 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010389 SourceLocation ELoc;
10390 SourceRange ERange;
10391 Expr *SimpleRefExpr = RefExpr;
10392 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010393 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010394 // It will be analyzed later.
10395 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010396 SrcExprs.push_back(nullptr);
10397 DstExprs.push_back(nullptr);
10398 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010399 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010400 ValueDecl *D = Res.first;
10401 if (!D)
10402 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010403
Alexey Bataev74caaf22016-02-20 04:09:36 +000010404 QualType Type = D->getType();
10405 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010406
10407 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10408 // A variable that appears in a lastprivate clause must not have an
10409 // incomplete type or a reference type.
10410 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010411 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010412 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010413 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010414
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010415 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10416 // A variable that is privatized must not have a const-qualified type
10417 // unless it is of class type with a mutable member. This restriction does
10418 // not apply to the firstprivate clause.
10419 //
10420 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10421 // A variable that appears in a lastprivate clause must not have a
10422 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010423 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010424 continue;
10425
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010426 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010427 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10428 // in a Construct]
10429 // Variables with the predetermined data-sharing attributes may not be
10430 // listed in data-sharing attributes clauses, except for the cases
10431 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010432 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10433 // A list item may appear in a firstprivate or lastprivate clause but not
10434 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010435 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010436 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010437 (isOpenMPDistributeDirective(CurrDir) ||
10438 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010439 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10440 Diag(ELoc, diag::err_omp_wrong_dsa)
10441 << getOpenMPClauseName(DVar.CKind)
10442 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010443 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010444 continue;
10445 }
10446
Alexey Bataevf29276e2014-06-18 04:14:57 +000010447 // OpenMP [2.14.3.5, Restrictions, p.2]
10448 // A list item that is private within a parallel region, or that appears in
10449 // the reduction clause of a parallel construct, must not appear in a
10450 // lastprivate clause on a worksharing construct if any of the corresponding
10451 // worksharing regions ever binds to any of the corresponding parallel
10452 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010453 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010454 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010455 !isOpenMPParallelDirective(CurrDir) &&
10456 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010457 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010458 if (DVar.CKind != OMPC_shared) {
10459 Diag(ELoc, diag::err_omp_required_access)
10460 << getOpenMPClauseName(OMPC_lastprivate)
10461 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010462 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010463 continue;
10464 }
10465 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010466
Alexander Musman1bb328c2014-06-04 13:06:39 +000010467 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010468 // A variable of class type (or array thereof) that appears in a
10469 // lastprivate clause requires an accessible, unambiguous default
10470 // constructor for the class type, unless the list item is also specified
10471 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010472 // A variable of class type (or array thereof) that appears in a
10473 // lastprivate clause requires an accessible, unambiguous copy assignment
10474 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010475 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010476 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10477 Type.getUnqualifiedType(), ".lastprivate.src",
10478 D->hasAttrs() ? &D->getAttrs() : nullptr);
10479 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010480 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010481 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010482 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010483 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010484 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010485 // For arrays generate assignment operation for single element and replace
10486 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010487 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10488 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010489 if (AssignmentOp.isInvalid())
10490 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010491 AssignmentOp =
10492 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010493 if (AssignmentOp.isInvalid())
10494 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010495
Alexey Bataev74caaf22016-02-20 04:09:36 +000010496 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010497 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010498 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010499 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010500 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010501 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010502 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010503 ExprCaptures.push_back(Ref->getDecl());
10504 }
10505 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010506 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010507 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010508 ExprResult RefRes = DefaultLvalueConversion(Ref);
10509 if (!RefRes.isUsable())
10510 continue;
10511 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010512 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10513 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010514 if (!PostUpdateRes.isUsable())
10515 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010516 ExprPostUpdates.push_back(
10517 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010518 }
10519 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010520 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010521 Vars.push_back((VD || CurContext->isDependentContext())
10522 ? RefExpr->IgnoreParens()
10523 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010524 SrcExprs.push_back(PseudoSrcExpr);
10525 DstExprs.push_back(PseudoDstExpr);
10526 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010527 }
10528
10529 if (Vars.empty())
10530 return nullptr;
10531
10532 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010533 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010534 buildPreInits(Context, ExprCaptures),
10535 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010536}
10537
Alexey Bataev758e55e2013-09-06 18:03:48 +000010538OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10539 SourceLocation StartLoc,
10540 SourceLocation LParenLoc,
10541 SourceLocation EndLoc) {
10542 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010543 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010544 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010545 SourceLocation ELoc;
10546 SourceRange ERange;
10547 Expr *SimpleRefExpr = RefExpr;
10548 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010549 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010550 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010551 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010552 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010553 ValueDecl *D = Res.first;
10554 if (!D)
10555 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010556
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010557 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010558 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10559 // in a Construct]
10560 // Variables with the predetermined data-sharing attributes may not be
10561 // listed in data-sharing attributes clauses, except for the cases
10562 // listed below. For these exceptions only, listing a predetermined
10563 // variable in a data-sharing attribute clause is allowed and overrides
10564 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010565 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010566 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10567 DVar.RefExpr) {
10568 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10569 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010570 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010571 continue;
10572 }
10573
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010574 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010575 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010576 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010577 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010578 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10579 ? RefExpr->IgnoreParens()
10580 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010581 }
10582
Alexey Bataeved09d242014-05-28 05:53:51 +000010583 if (Vars.empty())
10584 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010585
10586 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10587}
10588
Alexey Bataevc5e02582014-06-16 07:08:35 +000010589namespace {
10590class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10591 DSAStackTy *Stack;
10592
10593public:
10594 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010595 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10596 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010597 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10598 return false;
10599 if (DVar.CKind != OMPC_unknown)
10600 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010601 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010602 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010603 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010604 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010605 }
10606 return false;
10607 }
10608 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010609 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010610 if (Child && Visit(Child))
10611 return true;
10612 }
10613 return false;
10614 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010615 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010616};
Alexey Bataev23b69422014-06-18 07:08:49 +000010617} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010618
Alexey Bataev60da77e2016-02-29 05:54:20 +000010619namespace {
10620// Transform MemberExpression for specified FieldDecl of current class to
10621// DeclRefExpr to specified OMPCapturedExprDecl.
10622class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10623 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010624 ValueDecl *Field = nullptr;
10625 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010626
10627public:
10628 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10629 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10630
10631 ExprResult TransformMemberExpr(MemberExpr *E) {
10632 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10633 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010634 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010635 return CapturedExpr;
10636 }
10637 return BaseTransform::TransformMemberExpr(E);
10638 }
10639 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10640};
10641} // namespace
10642
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010643template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010644static T filterLookupForUDReductionAndMapper(
10645 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010646 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010647 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010648 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010649 return Res;
10650 }
10651 }
10652 return T();
10653}
10654
Alexey Bataev43b90b72018-09-12 16:31:59 +000010655static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10656 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10657
10658 for (auto RD : D->redecls()) {
10659 // Don't bother with extra checks if we already know this one isn't visible.
10660 if (RD == D)
10661 continue;
10662
10663 auto ND = cast<NamedDecl>(RD);
10664 if (LookupResult::isVisible(SemaRef, ND))
10665 return ND;
10666 }
10667
10668 return nullptr;
10669}
10670
10671static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010672argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010673 SourceLocation Loc, QualType Ty,
10674 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10675 // Find all of the associated namespaces and classes based on the
10676 // arguments we have.
10677 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10678 Sema::AssociatedClassSet AssociatedClasses;
10679 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10680 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10681 AssociatedClasses);
10682
10683 // C++ [basic.lookup.argdep]p3:
10684 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10685 // and let Y be the lookup set produced by argument dependent
10686 // lookup (defined as follows). If X contains [...] then Y is
10687 // empty. Otherwise Y is the set of declarations found in the
10688 // namespaces associated with the argument types as described
10689 // below. The set of declarations found by the lookup of the name
10690 // is the union of X and Y.
10691 //
10692 // Here, we compute Y and add its members to the overloaded
10693 // candidate set.
10694 for (auto *NS : AssociatedNamespaces) {
10695 // When considering an associated namespace, the lookup is the
10696 // same as the lookup performed when the associated namespace is
10697 // used as a qualifier (3.4.3.2) except that:
10698 //
10699 // -- Any using-directives in the associated namespace are
10700 // ignored.
10701 //
10702 // -- Any namespace-scope friend functions declared in
10703 // associated classes are visible within their respective
10704 // namespaces even if they are not visible during an ordinary
10705 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000010706 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000010707 for (auto *D : R) {
10708 auto *Underlying = D;
10709 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10710 Underlying = USD->getTargetDecl();
10711
Michael Kruse4304e9d2019-02-19 16:38:20 +000010712 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
10713 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000010714 continue;
10715
10716 if (!SemaRef.isVisible(D)) {
10717 D = findAcceptableDecl(SemaRef, D);
10718 if (!D)
10719 continue;
10720 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10721 Underlying = USD->getTargetDecl();
10722 }
10723 Lookups.emplace_back();
10724 Lookups.back().addDecl(Underlying);
10725 }
10726 }
10727}
10728
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010729static ExprResult
10730buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10731 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10732 const DeclarationNameInfo &ReductionId, QualType Ty,
10733 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10734 if (ReductionIdScopeSpec.isInvalid())
10735 return ExprError();
10736 SmallVector<UnresolvedSet<8>, 4> Lookups;
10737 if (S) {
10738 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10739 Lookup.suppressDiagnostics();
10740 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010741 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010742 do {
10743 S = S->getParent();
10744 } while (S && !S->isDeclScope(D));
10745 if (S)
10746 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000010747 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010748 Lookups.back().append(Lookup.begin(), Lookup.end());
10749 Lookup.clear();
10750 }
10751 } else if (auto *ULE =
10752 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10753 Lookups.push_back(UnresolvedSet<8>());
10754 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010755 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010756 if (D == PrevD)
10757 Lookups.push_back(UnresolvedSet<8>());
10758 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10759 Lookups.back().addDecl(DRD);
10760 PrevD = D;
10761 }
10762 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000010763 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10764 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010765 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000010766 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010767 return !D->isInvalidDecl() &&
10768 (D->getType()->isDependentType() ||
10769 D->getType()->isInstantiationDependentType() ||
10770 D->getType()->containsUnexpandedParameterPack());
10771 })) {
10772 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000010773 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000010774 if (Set.empty())
10775 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010776 ResSet.append(Set.begin(), Set.end());
10777 // The last item marks the end of all declarations at the specified scope.
10778 ResSet.addDecl(Set[Set.size() - 1]);
10779 }
10780 return UnresolvedLookupExpr::Create(
10781 SemaRef.Context, /*NamingClass=*/nullptr,
10782 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10783 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10784 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000010785 // Lookup inside the classes.
10786 // C++ [over.match.oper]p3:
10787 // For a unary operator @ with an operand of a type whose
10788 // cv-unqualified version is T1, and for a binary operator @ with
10789 // a left operand of a type whose cv-unqualified version is T1 and
10790 // a right operand of a type whose cv-unqualified version is T2,
10791 // three sets of candidate functions, designated member
10792 // candidates, non-member candidates and built-in candidates, are
10793 // constructed as follows:
10794 // -- If T1 is a complete class type or a class currently being
10795 // defined, the set of member candidates is the result of the
10796 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10797 // the set of member candidates is empty.
10798 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10799 Lookup.suppressDiagnostics();
10800 if (const auto *TyRec = Ty->getAs<RecordType>()) {
10801 // Complete the type if it can be completed.
10802 // If the type is neither complete nor being defined, bail out now.
10803 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10804 TyRec->getDecl()->getDefinition()) {
10805 Lookup.clear();
10806 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10807 if (Lookup.empty()) {
10808 Lookups.emplace_back();
10809 Lookups.back().append(Lookup.begin(), Lookup.end());
10810 }
10811 }
10812 }
10813 // Perform ADL.
10814 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010815 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010816 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10817 if (!D->isInvalidDecl() &&
10818 SemaRef.Context.hasSameType(D->getType(), Ty))
10819 return D;
10820 return nullptr;
10821 }))
James Y Knightb92d2902019-02-05 16:05:50 +000010822 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
10823 VK_LValue, Loc);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010824 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010825 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10826 if (!D->isInvalidDecl() &&
10827 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10828 !Ty.isMoreQualifiedThan(D->getType()))
10829 return D;
10830 return nullptr;
10831 })) {
10832 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10833 /*DetectVirtual=*/false);
10834 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10835 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10836 VD->getType().getUnqualifiedType()))) {
10837 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10838 /*DiagID=*/0) !=
10839 Sema::AR_inaccessible) {
10840 SemaRef.BuildBasePathArray(Paths, BasePath);
James Y Knightb92d2902019-02-05 16:05:50 +000010841 return SemaRef.BuildDeclRefExpr(
10842 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010843 }
10844 }
10845 }
10846 }
10847 if (ReductionIdScopeSpec.isSet()) {
10848 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10849 return ExprError();
10850 }
10851 return ExprEmpty();
10852}
10853
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010854namespace {
10855/// Data for the reduction-based clauses.
10856struct ReductionData {
10857 /// List of original reduction items.
10858 SmallVector<Expr *, 8> Vars;
10859 /// List of private copies of the reduction items.
10860 SmallVector<Expr *, 8> Privates;
10861 /// LHS expressions for the reduction_op expressions.
10862 SmallVector<Expr *, 8> LHSs;
10863 /// RHS expressions for the reduction_op expressions.
10864 SmallVector<Expr *, 8> RHSs;
10865 /// Reduction operation expression.
10866 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010867 /// Taskgroup descriptors for the corresponding reduction items in
10868 /// in_reduction clauses.
10869 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010870 /// List of captures for clause.
10871 SmallVector<Decl *, 4> ExprCaptures;
10872 /// List of postupdate expressions.
10873 SmallVector<Expr *, 4> ExprPostUpdates;
10874 ReductionData() = delete;
10875 /// Reserves required memory for the reduction data.
10876 ReductionData(unsigned Size) {
10877 Vars.reserve(Size);
10878 Privates.reserve(Size);
10879 LHSs.reserve(Size);
10880 RHSs.reserve(Size);
10881 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010882 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010883 ExprCaptures.reserve(Size);
10884 ExprPostUpdates.reserve(Size);
10885 }
10886 /// Stores reduction item and reduction operation only (required for dependent
10887 /// reduction item).
10888 void push(Expr *Item, Expr *ReductionOp) {
10889 Vars.emplace_back(Item);
10890 Privates.emplace_back(nullptr);
10891 LHSs.emplace_back(nullptr);
10892 RHSs.emplace_back(nullptr);
10893 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010894 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010895 }
10896 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010897 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10898 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010899 Vars.emplace_back(Item);
10900 Privates.emplace_back(Private);
10901 LHSs.emplace_back(LHS);
10902 RHSs.emplace_back(RHS);
10903 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010904 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010905 }
10906};
10907} // namespace
10908
Alexey Bataeve3727102018-04-18 15:57:46 +000010909static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010910 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10911 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10912 const Expr *Length = OASE->getLength();
10913 if (Length == nullptr) {
10914 // For array sections of the form [1:] or [:], we would need to analyze
10915 // the lower bound...
10916 if (OASE->getColonLoc().isValid())
10917 return false;
10918
10919 // This is an array subscript which has implicit length 1!
10920 SingleElement = true;
10921 ArraySizes.push_back(llvm::APSInt::get(1));
10922 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010923 Expr::EvalResult Result;
10924 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010925 return false;
10926
Fangrui Song407659a2018-11-30 23:41:18 +000010927 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010928 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10929 ArraySizes.push_back(ConstantLengthValue);
10930 }
10931
10932 // Get the base of this array section and walk up from there.
10933 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10934
10935 // We require length = 1 for all array sections except the right-most to
10936 // guarantee that the memory region is contiguous and has no holes in it.
10937 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10938 Length = TempOASE->getLength();
10939 if (Length == nullptr) {
10940 // For array sections of the form [1:] or [:], we would need to analyze
10941 // the lower bound...
10942 if (OASE->getColonLoc().isValid())
10943 return false;
10944
10945 // This is an array subscript which has implicit length 1!
10946 ArraySizes.push_back(llvm::APSInt::get(1));
10947 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010948 Expr::EvalResult Result;
10949 if (!Length->EvaluateAsInt(Result, Context))
10950 return false;
10951
10952 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10953 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010954 return false;
10955
10956 ArraySizes.push_back(ConstantLengthValue);
10957 }
10958 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10959 }
10960
10961 // If we have a single element, we don't need to add the implicit lengths.
10962 if (!SingleElement) {
10963 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10964 // Has implicit length 1!
10965 ArraySizes.push_back(llvm::APSInt::get(1));
10966 Base = TempASE->getBase()->IgnoreParenImpCasts();
10967 }
10968 }
10969
10970 // This array section can be privatized as a single value or as a constant
10971 // sized array.
10972 return true;
10973}
10974
Alexey Bataeve3727102018-04-18 15:57:46 +000010975static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010976 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10977 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10978 SourceLocation ColonLoc, SourceLocation EndLoc,
10979 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010980 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010981 DeclarationName DN = ReductionId.getName();
10982 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010983 BinaryOperatorKind BOK = BO_Comma;
10984
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010985 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010986 // OpenMP [2.14.3.6, reduction clause]
10987 // C
10988 // reduction-identifier is either an identifier or one of the following
10989 // operators: +, -, *, &, |, ^, && and ||
10990 // C++
10991 // reduction-identifier is either an id-expression or one of the following
10992 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010993 switch (OOK) {
10994 case OO_Plus:
10995 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010996 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010997 break;
10998 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010999 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011000 break;
11001 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011002 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011003 break;
11004 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011005 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011006 break;
11007 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011008 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011009 break;
11010 case OO_AmpAmp:
11011 BOK = BO_LAnd;
11012 break;
11013 case OO_PipePipe:
11014 BOK = BO_LOr;
11015 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011016 case OO_New:
11017 case OO_Delete:
11018 case OO_Array_New:
11019 case OO_Array_Delete:
11020 case OO_Slash:
11021 case OO_Percent:
11022 case OO_Tilde:
11023 case OO_Exclaim:
11024 case OO_Equal:
11025 case OO_Less:
11026 case OO_Greater:
11027 case OO_LessEqual:
11028 case OO_GreaterEqual:
11029 case OO_PlusEqual:
11030 case OO_MinusEqual:
11031 case OO_StarEqual:
11032 case OO_SlashEqual:
11033 case OO_PercentEqual:
11034 case OO_CaretEqual:
11035 case OO_AmpEqual:
11036 case OO_PipeEqual:
11037 case OO_LessLess:
11038 case OO_GreaterGreater:
11039 case OO_LessLessEqual:
11040 case OO_GreaterGreaterEqual:
11041 case OO_EqualEqual:
11042 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011043 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011044 case OO_PlusPlus:
11045 case OO_MinusMinus:
11046 case OO_Comma:
11047 case OO_ArrowStar:
11048 case OO_Arrow:
11049 case OO_Call:
11050 case OO_Subscript:
11051 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011052 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011053 case NUM_OVERLOADED_OPERATORS:
11054 llvm_unreachable("Unexpected reduction identifier");
11055 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011056 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011057 if (II->isStr("max"))
11058 BOK = BO_GT;
11059 else if (II->isStr("min"))
11060 BOK = BO_LT;
11061 }
11062 break;
11063 }
11064 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011065 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011066 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011067 else
11068 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011069 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011070
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011071 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11072 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011073 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011074 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011075 // OpenMP [2.1, C/C++]
11076 // A list item is a variable or array section, subject to the restrictions
11077 // specified in Section 2.4 on page 42 and in each of the sections
11078 // describing clauses and directives for which a list appears.
11079 // OpenMP [2.14.3.3, Restrictions, p.1]
11080 // A variable that is part of another variable (as an array or
11081 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011082 if (!FirstIter && IR != ER)
11083 ++IR;
11084 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011085 SourceLocation ELoc;
11086 SourceRange ERange;
11087 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011088 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011089 /*AllowArraySection=*/true);
11090 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011091 // Try to find 'declare reduction' corresponding construct before using
11092 // builtin/overloaded operators.
11093 QualType Type = Context.DependentTy;
11094 CXXCastPath BasePath;
11095 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011096 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011097 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011098 Expr *ReductionOp = nullptr;
11099 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011100 (DeclareReductionRef.isUnset() ||
11101 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011102 ReductionOp = DeclareReductionRef.get();
11103 // It will be analyzed later.
11104 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011105 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011106 ValueDecl *D = Res.first;
11107 if (!D)
11108 continue;
11109
Alexey Bataev88202be2017-07-27 13:20:36 +000011110 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011111 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011112 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11113 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011114 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011115 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011116 } else if (OASE) {
11117 QualType BaseType =
11118 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11119 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011120 Type = ATy->getElementType();
11121 else
11122 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011123 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011124 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011125 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011126 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011127 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011128
Alexey Bataevc5e02582014-06-16 07:08:35 +000011129 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11130 // A variable that appears in a private clause must not have an incomplete
11131 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011132 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011133 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011134 continue;
11135 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011136 // A list item that appears in a reduction clause must not be
11137 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011138 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11139 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011140 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011141
11142 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011143 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11144 // If a list-item is a reference type then it must bind to the same object
11145 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011146 if (!ASE && !OASE) {
11147 if (VD) {
11148 VarDecl *VDDef = VD->getDefinition();
11149 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11150 DSARefChecker Check(Stack);
11151 if (Check.Visit(VDDef->getInit())) {
11152 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11153 << getOpenMPClauseName(ClauseKind) << ERange;
11154 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11155 continue;
11156 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011157 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011158 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011159
Alexey Bataevbc529672018-09-28 19:33:14 +000011160 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11161 // in a Construct]
11162 // Variables with the predetermined data-sharing attributes may not be
11163 // listed in data-sharing attributes clauses, except for the cases
11164 // listed below. For these exceptions only, listing a predetermined
11165 // variable in a data-sharing attribute clause is allowed and overrides
11166 // the variable's predetermined data-sharing attributes.
11167 // OpenMP [2.14.3.6, Restrictions, p.3]
11168 // Any number of reduction clauses can be specified on the directive,
11169 // but a list item can appear only once in the reduction clauses for that
11170 // directive.
11171 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11172 if (DVar.CKind == OMPC_reduction) {
11173 S.Diag(ELoc, diag::err_omp_once_referenced)
11174 << getOpenMPClauseName(ClauseKind);
11175 if (DVar.RefExpr)
11176 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11177 continue;
11178 }
11179 if (DVar.CKind != OMPC_unknown) {
11180 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11181 << getOpenMPClauseName(DVar.CKind)
11182 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011183 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011184 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011185 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011186
11187 // OpenMP [2.14.3.6, Restrictions, p.1]
11188 // A list item that appears in a reduction clause of a worksharing
11189 // construct must be shared in the parallel regions to which any of the
11190 // worksharing regions arising from the worksharing construct bind.
11191 if (isOpenMPWorksharingDirective(CurrDir) &&
11192 !isOpenMPParallelDirective(CurrDir) &&
11193 !isOpenMPTeamsDirective(CurrDir)) {
11194 DVar = Stack->getImplicitDSA(D, true);
11195 if (DVar.CKind != OMPC_shared) {
11196 S.Diag(ELoc, diag::err_omp_required_access)
11197 << getOpenMPClauseName(OMPC_reduction)
11198 << getOpenMPClauseName(OMPC_shared);
11199 reportOriginalDsa(S, Stack, D, DVar);
11200 continue;
11201 }
11202 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011203 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011204
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011205 // Try to find 'declare reduction' corresponding construct before using
11206 // builtin/overloaded operators.
11207 CXXCastPath BasePath;
11208 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011209 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011210 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11211 if (DeclareReductionRef.isInvalid())
11212 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011213 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011214 (DeclareReductionRef.isUnset() ||
11215 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011216 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011217 continue;
11218 }
11219 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11220 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011221 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011222 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011223 << Type << ReductionIdRange;
11224 continue;
11225 }
11226
11227 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11228 // The type of a list item that appears in a reduction clause must be valid
11229 // for the reduction-identifier. For a max or min reduction in C, the type
11230 // of the list item must be an allowed arithmetic data type: char, int,
11231 // float, double, or _Bool, possibly modified with long, short, signed, or
11232 // unsigned. For a max or min reduction in C++, the type of the list item
11233 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11234 // double, or bool, possibly modified with long, short, signed, or unsigned.
11235 if (DeclareReductionRef.isUnset()) {
11236 if ((BOK == BO_GT || BOK == BO_LT) &&
11237 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011238 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11239 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011240 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011241 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011242 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11243 VarDecl::DeclarationOnly;
11244 S.Diag(D->getLocation(),
11245 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011246 << D;
11247 }
11248 continue;
11249 }
11250 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011251 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011252 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11253 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011254 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011255 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11256 VarDecl::DeclarationOnly;
11257 S.Diag(D->getLocation(),
11258 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011259 << D;
11260 }
11261 continue;
11262 }
11263 }
11264
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011265 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011266 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11267 D->hasAttrs() ? &D->getAttrs() : nullptr);
11268 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11269 D->hasAttrs() ? &D->getAttrs() : nullptr);
11270 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011271
11272 // Try if we can determine constant lengths for all array sections and avoid
11273 // the VLA.
11274 bool ConstantLengthOASE = false;
11275 if (OASE) {
11276 bool SingleElement;
11277 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011278 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011279 Context, OASE, SingleElement, ArraySizes);
11280
11281 // If we don't have a single element, we must emit a constant array type.
11282 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011283 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011284 PrivateTy = Context.getConstantArrayType(
11285 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011286 }
11287 }
11288
11289 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011290 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011291 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011292 if (!Context.getTargetInfo().isVLASupported() &&
11293 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11294 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11295 S.Diag(ELoc, diag::note_vla_unsupported);
11296 continue;
11297 }
David Majnemer9d168222016-08-05 17:44:54 +000011298 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011299 // Create pseudo array type for private copy. The size for this array will
11300 // be generated during codegen.
11301 // For array subscripts or single variables Private Ty is the same as Type
11302 // (type of the variable or single array element).
11303 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011304 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011305 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011306 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011307 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011308 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011309 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011310 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011311 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011312 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011313 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11314 D->hasAttrs() ? &D->getAttrs() : nullptr,
11315 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011316 // Add initializer for private variable.
11317 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011318 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11319 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011320 if (DeclareReductionRef.isUsable()) {
11321 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11322 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11323 if (DRD->getInitializer()) {
11324 Init = DRDRef;
11325 RHSVD->setInit(DRDRef);
11326 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011327 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011328 } else {
11329 switch (BOK) {
11330 case BO_Add:
11331 case BO_Xor:
11332 case BO_Or:
11333 case BO_LOr:
11334 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11335 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011336 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011337 break;
11338 case BO_Mul:
11339 case BO_LAnd:
11340 if (Type->isScalarType() || Type->isAnyComplexType()) {
11341 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011342 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011343 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011344 break;
11345 case BO_And: {
11346 // '&' reduction op - initializer is '~0'.
11347 QualType OrigType = Type;
11348 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11349 Type = ComplexTy->getElementType();
11350 if (Type->isRealFloatingType()) {
11351 llvm::APFloat InitValue =
11352 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11353 /*isIEEE=*/true);
11354 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11355 Type, ELoc);
11356 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011357 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011358 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11359 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11360 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11361 }
11362 if (Init && OrigType->isAnyComplexType()) {
11363 // Init = 0xFFFF + 0xFFFFi;
11364 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011365 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011366 }
11367 Type = OrigType;
11368 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011369 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011370 case BO_LT:
11371 case BO_GT: {
11372 // 'min' reduction op - initializer is 'Largest representable number in
11373 // the reduction list item type'.
11374 // 'max' reduction op - initializer is 'Least representable number in
11375 // the reduction list item type'.
11376 if (Type->isIntegerType() || Type->isPointerType()) {
11377 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011378 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011379 QualType IntTy =
11380 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11381 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011382 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11383 : llvm::APInt::getMinValue(Size)
11384 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11385 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011386 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11387 if (Type->isPointerType()) {
11388 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011389 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011390 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011391 if (CastExpr.isInvalid())
11392 continue;
11393 Init = CastExpr.get();
11394 }
11395 } else if (Type->isRealFloatingType()) {
11396 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11397 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11398 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11399 Type, ELoc);
11400 }
11401 break;
11402 }
11403 case BO_PtrMemD:
11404 case BO_PtrMemI:
11405 case BO_MulAssign:
11406 case BO_Div:
11407 case BO_Rem:
11408 case BO_Sub:
11409 case BO_Shl:
11410 case BO_Shr:
11411 case BO_LE:
11412 case BO_GE:
11413 case BO_EQ:
11414 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011415 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011416 case BO_AndAssign:
11417 case BO_XorAssign:
11418 case BO_OrAssign:
11419 case BO_Assign:
11420 case BO_AddAssign:
11421 case BO_SubAssign:
11422 case BO_DivAssign:
11423 case BO_RemAssign:
11424 case BO_ShlAssign:
11425 case BO_ShrAssign:
11426 case BO_Comma:
11427 llvm_unreachable("Unexpected reduction operation");
11428 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011429 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011430 if (Init && DeclareReductionRef.isUnset())
11431 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11432 else if (!Init)
11433 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011434 if (RHSVD->isInvalidDecl())
11435 continue;
11436 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011437 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11438 << Type << ReductionIdRange;
11439 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11440 VarDecl::DeclarationOnly;
11441 S.Diag(D->getLocation(),
11442 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011443 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011444 continue;
11445 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011446 // Store initializer for single element in private copy. Will be used during
11447 // codegen.
11448 PrivateVD->setInit(RHSVD->getInit());
11449 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011450 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011451 ExprResult ReductionOp;
11452 if (DeclareReductionRef.isUsable()) {
11453 QualType RedTy = DeclareReductionRef.get()->getType();
11454 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011455 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11456 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011457 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011458 LHS = S.DefaultLvalueConversion(LHS.get());
11459 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011460 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11461 CK_UncheckedDerivedToBase, LHS.get(),
11462 &BasePath, LHS.get()->getValueKind());
11463 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11464 CK_UncheckedDerivedToBase, RHS.get(),
11465 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011466 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011467 FunctionProtoType::ExtProtoInfo EPI;
11468 QualType Params[] = {PtrRedTy, PtrRedTy};
11469 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11470 auto *OVE = new (Context) OpaqueValueExpr(
11471 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011472 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011473 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011474 ReductionOp =
11475 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011476 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011477 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011478 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011479 if (ReductionOp.isUsable()) {
11480 if (BOK != BO_LT && BOK != BO_GT) {
11481 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011482 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011483 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011484 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011485 auto *ConditionalOp = new (Context)
11486 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11487 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011488 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011489 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011490 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011491 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011492 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011493 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11494 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011495 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011496 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011497 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011498 }
11499
Alexey Bataevfa312f32017-07-21 18:48:21 +000011500 // OpenMP [2.15.4.6, Restrictions, p.2]
11501 // A list item that appears in an in_reduction clause of a task construct
11502 // must appear in a task_reduction clause of a construct associated with a
11503 // taskgroup region that includes the participating task in its taskgroup
11504 // set. The construct associated with the innermost region that meets this
11505 // condition must specify the same reduction-identifier as the in_reduction
11506 // clause.
11507 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011508 SourceRange ParentSR;
11509 BinaryOperatorKind ParentBOK;
11510 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011511 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011512 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011513 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11514 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011515 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011516 Stack->getTopMostTaskgroupReductionData(
11517 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011518 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11519 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11520 if (!IsParentBOK && !IsParentReductionOp) {
11521 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11522 continue;
11523 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011524 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11525 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11526 IsParentReductionOp) {
11527 bool EmitError = true;
11528 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11529 llvm::FoldingSetNodeID RedId, ParentRedId;
11530 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11531 DeclareReductionRef.get()->Profile(RedId, Context,
11532 /*Canonical=*/true);
11533 EmitError = RedId != ParentRedId;
11534 }
11535 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011536 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011537 diag::err_omp_reduction_identifier_mismatch)
11538 << ReductionIdRange << RefExpr->getSourceRange();
11539 S.Diag(ParentSR.getBegin(),
11540 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011541 << ParentSR
11542 << (IsParentBOK ? ParentBOKDSA.RefExpr
11543 : ParentReductionOpDSA.RefExpr)
11544 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011545 continue;
11546 }
11547 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011548 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11549 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011550 }
11551
Alexey Bataev60da77e2016-02-29 05:54:20 +000011552 DeclRefExpr *Ref = nullptr;
11553 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011554 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011555 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011556 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011557 VarsExpr =
11558 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11559 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011560 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011561 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011562 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011563 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011564 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011565 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011566 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011567 if (!RefRes.isUsable())
11568 continue;
11569 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011570 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11571 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011572 if (!PostUpdateRes.isUsable())
11573 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011574 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11575 Stack->getCurrentDirective() == OMPD_taskgroup) {
11576 S.Diag(RefExpr->getExprLoc(),
11577 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011578 << RefExpr->getSourceRange();
11579 continue;
11580 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011581 RD.ExprPostUpdates.emplace_back(
11582 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011583 }
11584 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011585 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011586 // All reduction items are still marked as reduction (to do not increase
11587 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011588 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011589 if (CurrDir == OMPD_taskgroup) {
11590 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011591 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11592 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011593 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011594 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011595 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011596 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11597 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011598 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011599 return RD.Vars.empty();
11600}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011601
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011602OMPClause *Sema::ActOnOpenMPReductionClause(
11603 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11604 SourceLocation ColonLoc, SourceLocation EndLoc,
11605 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11606 ArrayRef<Expr *> UnresolvedReductions) {
11607 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011608 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011609 StartLoc, LParenLoc, ColonLoc, EndLoc,
11610 ReductionIdScopeSpec, ReductionId,
11611 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011612 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011613
Alexey Bataevc5e02582014-06-16 07:08:35 +000011614 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011615 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11616 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11617 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11618 buildPreInits(Context, RD.ExprCaptures),
11619 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011620}
11621
Alexey Bataev169d96a2017-07-18 20:17:46 +000011622OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11623 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11624 SourceLocation ColonLoc, SourceLocation EndLoc,
11625 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11626 ArrayRef<Expr *> UnresolvedReductions) {
11627 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011628 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11629 StartLoc, LParenLoc, ColonLoc, EndLoc,
11630 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011631 UnresolvedReductions, RD))
11632 return nullptr;
11633
11634 return OMPTaskReductionClause::Create(
11635 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11636 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11637 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11638 buildPreInits(Context, RD.ExprCaptures),
11639 buildPostUpdate(*this, RD.ExprPostUpdates));
11640}
11641
Alexey Bataevfa312f32017-07-21 18:48:21 +000011642OMPClause *Sema::ActOnOpenMPInReductionClause(
11643 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11644 SourceLocation ColonLoc, SourceLocation EndLoc,
11645 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11646 ArrayRef<Expr *> UnresolvedReductions) {
11647 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011648 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011649 StartLoc, LParenLoc, ColonLoc, EndLoc,
11650 ReductionIdScopeSpec, ReductionId,
11651 UnresolvedReductions, RD))
11652 return nullptr;
11653
11654 return OMPInReductionClause::Create(
11655 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11656 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011657 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011658 buildPreInits(Context, RD.ExprCaptures),
11659 buildPostUpdate(*this, RD.ExprPostUpdates));
11660}
11661
Alexey Bataevecba70f2016-04-12 11:02:11 +000011662bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11663 SourceLocation LinLoc) {
11664 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11665 LinKind == OMPC_LINEAR_unknown) {
11666 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11667 return true;
11668 }
11669 return false;
11670}
11671
Alexey Bataeve3727102018-04-18 15:57:46 +000011672bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011673 OpenMPLinearClauseKind LinKind,
11674 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011675 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011676 // A variable must not have an incomplete type or a reference type.
11677 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11678 return true;
11679 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11680 !Type->isReferenceType()) {
11681 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11682 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11683 return true;
11684 }
11685 Type = Type.getNonReferenceType();
11686
Joel E. Dennybae586f2019-01-04 22:12:13 +000011687 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11688 // A variable that is privatized must not have a const-qualified type
11689 // unless it is of class type with a mutable member. This restriction does
11690 // not apply to the firstprivate clause.
11691 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011692 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011693
11694 // A list item must be of integral or pointer type.
11695 Type = Type.getUnqualifiedType().getCanonicalType();
11696 const auto *Ty = Type.getTypePtrOrNull();
11697 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11698 !Ty->isPointerType())) {
11699 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11700 if (D) {
11701 bool IsDecl =
11702 !VD ||
11703 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11704 Diag(D->getLocation(),
11705 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11706 << D;
11707 }
11708 return true;
11709 }
11710 return false;
11711}
11712
Alexey Bataev182227b2015-08-20 10:54:39 +000011713OMPClause *Sema::ActOnOpenMPLinearClause(
11714 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11715 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11716 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011717 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011718 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000011719 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011720 SmallVector<Decl *, 4> ExprCaptures;
11721 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011722 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000011723 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000011724 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011725 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011726 SourceLocation ELoc;
11727 SourceRange ERange;
11728 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011729 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011730 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011731 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011732 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011733 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000011734 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000011735 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011736 ValueDecl *D = Res.first;
11737 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000011738 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000011739
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011740 QualType Type = D->getType();
11741 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000011742
11743 // OpenMP [2.14.3.7, linear clause]
11744 // A list-item cannot appear in more than one linear clause.
11745 // A list-item that appears in a linear clause cannot appear in any
11746 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011747 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000011748 if (DVar.RefExpr) {
11749 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11750 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000011751 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000011752 continue;
11753 }
11754
Alexey Bataevecba70f2016-04-12 11:02:11 +000011755 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000011756 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011757 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000011758
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011759 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000011760 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011761 buildVarDecl(*this, ELoc, Type, D->getName(),
11762 D->hasAttrs() ? &D->getAttrs() : nullptr,
11763 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011764 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011765 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011766 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011767 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011768 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011769 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011770 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011771 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011772 ExprCaptures.push_back(Ref->getDecl());
11773 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11774 ExprResult RefRes = DefaultLvalueConversion(Ref);
11775 if (!RefRes.isUsable())
11776 continue;
11777 ExprResult PostUpdateRes =
11778 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11779 SimpleRefExpr, RefRes.get());
11780 if (!PostUpdateRes.isUsable())
11781 continue;
11782 ExprPostUpdates.push_back(
11783 IgnoredValueConversions(PostUpdateRes.get()).get());
11784 }
11785 }
11786 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011787 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011788 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011789 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011790 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011791 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011792 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011793 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011794
11795 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011796 Vars.push_back((VD || CurContext->isDependentContext())
11797 ? RefExpr->IgnoreParens()
11798 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011799 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000011800 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000011801 }
11802
11803 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011804 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011805
11806 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000011807 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011808 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11809 !Step->isInstantiationDependent() &&
11810 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011811 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011812 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000011813 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011814 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011815 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000011816
Alexander Musman3276a272015-03-21 10:12:56 +000011817 // Build var to save the step value.
11818 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011819 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000011820 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011821 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011822 ExprResult CalcStep =
11823 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011824 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011825
Alexander Musman8dba6642014-04-22 13:09:42 +000011826 // Warn about zero linear step (it would be probably better specified as
11827 // making corresponding variables 'const').
11828 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011829 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11830 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011831 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11832 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011833 if (!IsConstant && CalcStep.isUsable()) {
11834 // Calculate the step beforehand instead of doing this on each iteration.
11835 // (This is not used if the number of iterations may be kfold-ed).
11836 CalcStepExpr = CalcStep.get();
11837 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011838 }
11839
Alexey Bataev182227b2015-08-20 10:54:39 +000011840 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11841 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011842 StepExpr, CalcStepExpr,
11843 buildPreInits(Context, ExprCaptures),
11844 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011845}
11846
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011847static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11848 Expr *NumIterations, Sema &SemaRef,
11849 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011850 // Walk the vars and build update/final expressions for the CodeGen.
11851 SmallVector<Expr *, 8> Updates;
11852 SmallVector<Expr *, 8> Finals;
11853 Expr *Step = Clause.getStep();
11854 Expr *CalcStep = Clause.getCalcStep();
11855 // OpenMP [2.14.3.7, linear clause]
11856 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000011857 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000011858 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011859 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000011860 Step = cast<BinaryOperator>(CalcStep)->getLHS();
11861 bool HasErrors = false;
11862 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011863 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000011864 OpenMPLinearClauseKind LinKind = Clause.getModifier();
11865 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011866 SourceLocation ELoc;
11867 SourceRange ERange;
11868 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011869 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011870 ValueDecl *D = Res.first;
11871 if (Res.second || !D) {
11872 Updates.push_back(nullptr);
11873 Finals.push_back(nullptr);
11874 HasErrors = true;
11875 continue;
11876 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011877 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011878 // OpenMP [2.15.11, distribute simd Construct]
11879 // A list item may not appear in a linear clause, unless it is the loop
11880 // iteration variable.
11881 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11882 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11883 SemaRef.Diag(ELoc,
11884 diag::err_omp_linear_distribute_var_non_loop_iteration);
11885 Updates.push_back(nullptr);
11886 Finals.push_back(nullptr);
11887 HasErrors = true;
11888 continue;
11889 }
Alexander Musman3276a272015-03-21 10:12:56 +000011890 Expr *InitExpr = *CurInit;
11891
11892 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011893 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011894 Expr *CapturedRef;
11895 if (LinKind == OMPC_LINEAR_uval)
11896 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11897 else
11898 CapturedRef =
11899 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11900 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11901 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011902
11903 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011904 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000011905 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011906 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000011907 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011908 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011909 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011910 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011911 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011912 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011913
11914 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011915 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000011916 if (!Info.first)
11917 Final =
11918 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11919 InitExpr, NumIterations, Step, /*Subtract=*/false);
11920 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011921 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011922 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011923 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011924
Alexander Musman3276a272015-03-21 10:12:56 +000011925 if (!Update.isUsable() || !Final.isUsable()) {
11926 Updates.push_back(nullptr);
11927 Finals.push_back(nullptr);
11928 HasErrors = true;
11929 } else {
11930 Updates.push_back(Update.get());
11931 Finals.push_back(Final.get());
11932 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011933 ++CurInit;
11934 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011935 }
11936 Clause.setUpdates(Updates);
11937 Clause.setFinals(Finals);
11938 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011939}
11940
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011941OMPClause *Sema::ActOnOpenMPAlignedClause(
11942 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11943 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011944 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011945 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011946 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11947 SourceLocation ELoc;
11948 SourceRange ERange;
11949 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011950 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000011951 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011952 // It will be analyzed later.
11953 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011954 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011955 ValueDecl *D = Res.first;
11956 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011957 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011958
Alexey Bataev1efd1662016-03-29 10:59:56 +000011959 QualType QType = D->getType();
11960 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011961
11962 // OpenMP [2.8.1, simd construct, Restrictions]
11963 // The type of list items appearing in the aligned clause must be
11964 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011965 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011966 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011967 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011968 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011969 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011970 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011971 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011972 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011973 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011974 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011975 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011976 continue;
11977 }
11978
11979 // OpenMP [2.8.1, simd construct, Restrictions]
11980 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011981 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011982 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011983 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11984 << getOpenMPClauseName(OMPC_aligned);
11985 continue;
11986 }
11987
Alexey Bataev1efd1662016-03-29 10:59:56 +000011988 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011989 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000011990 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11991 Vars.push_back(DefaultFunctionArrayConversion(
11992 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11993 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011994 }
11995
11996 // OpenMP [2.8.1, simd construct, Description]
11997 // The parameter of the aligned clause, alignment, must be a constant
11998 // positive integer expression.
11999 // If no optional parameter is specified, implementation-defined default
12000 // alignments for SIMD instructions on the target platforms are assumed.
12001 if (Alignment != nullptr) {
12002 ExprResult AlignResult =
12003 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12004 if (AlignResult.isInvalid())
12005 return nullptr;
12006 Alignment = AlignResult.get();
12007 }
12008 if (Vars.empty())
12009 return nullptr;
12010
12011 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12012 EndLoc, Vars, Alignment);
12013}
12014
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012015OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12016 SourceLocation StartLoc,
12017 SourceLocation LParenLoc,
12018 SourceLocation EndLoc) {
12019 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012020 SmallVector<Expr *, 8> SrcExprs;
12021 SmallVector<Expr *, 8> DstExprs;
12022 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012023 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012024 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12025 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012026 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012027 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012028 SrcExprs.push_back(nullptr);
12029 DstExprs.push_back(nullptr);
12030 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012031 continue;
12032 }
12033
Alexey Bataeved09d242014-05-28 05:53:51 +000012034 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012035 // OpenMP [2.1, C/C++]
12036 // A list item is a variable name.
12037 // OpenMP [2.14.4.1, Restrictions, p.1]
12038 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012039 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012040 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012041 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12042 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012043 continue;
12044 }
12045
12046 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012047 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012048
12049 QualType Type = VD->getType();
12050 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12051 // It will be analyzed later.
12052 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012053 SrcExprs.push_back(nullptr);
12054 DstExprs.push_back(nullptr);
12055 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012056 continue;
12057 }
12058
12059 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12060 // A list item that appears in a copyin clause must be threadprivate.
12061 if (!DSAStack->isThreadPrivate(VD)) {
12062 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012063 << getOpenMPClauseName(OMPC_copyin)
12064 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012065 continue;
12066 }
12067
12068 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12069 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012070 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012071 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012072 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12073 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012074 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012075 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012076 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012077 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012078 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012079 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012080 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012081 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012082 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012083 // For arrays generate assignment operation for single element and replace
12084 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012085 ExprResult AssignmentOp =
12086 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12087 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012088 if (AssignmentOp.isInvalid())
12089 continue;
12090 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012091 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012092 if (AssignmentOp.isInvalid())
12093 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012094
12095 DSAStack->addDSA(VD, DE, OMPC_copyin);
12096 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012097 SrcExprs.push_back(PseudoSrcExpr);
12098 DstExprs.push_back(PseudoDstExpr);
12099 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012100 }
12101
Alexey Bataeved09d242014-05-28 05:53:51 +000012102 if (Vars.empty())
12103 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012104
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012105 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12106 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012107}
12108
Alexey Bataevbae9a792014-06-27 10:37:06 +000012109OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12110 SourceLocation StartLoc,
12111 SourceLocation LParenLoc,
12112 SourceLocation EndLoc) {
12113 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012114 SmallVector<Expr *, 8> SrcExprs;
12115 SmallVector<Expr *, 8> DstExprs;
12116 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012117 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012118 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12119 SourceLocation ELoc;
12120 SourceRange ERange;
12121 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012122 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012123 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012124 // It will be analyzed later.
12125 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012126 SrcExprs.push_back(nullptr);
12127 DstExprs.push_back(nullptr);
12128 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012129 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012130 ValueDecl *D = Res.first;
12131 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012132 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012133
Alexey Bataeve122da12016-03-17 10:50:17 +000012134 QualType Type = D->getType();
12135 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012136
12137 // OpenMP [2.14.4.2, Restrictions, p.2]
12138 // A list item that appears in a copyprivate clause may not appear in a
12139 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012140 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012141 DSAStackTy::DSAVarData DVar =
12142 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012143 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12144 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012145 Diag(ELoc, diag::err_omp_wrong_dsa)
12146 << getOpenMPClauseName(DVar.CKind)
12147 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012148 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012149 continue;
12150 }
12151
12152 // OpenMP [2.11.4.2, Restrictions, p.1]
12153 // All list items that appear in a copyprivate clause must be either
12154 // threadprivate or private in the enclosing context.
12155 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012156 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012157 if (DVar.CKind == OMPC_shared) {
12158 Diag(ELoc, diag::err_omp_required_access)
12159 << getOpenMPClauseName(OMPC_copyprivate)
12160 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012161 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012162 continue;
12163 }
12164 }
12165 }
12166
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012167 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012168 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012169 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012170 << getOpenMPClauseName(OMPC_copyprivate) << Type
12171 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012172 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012173 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012174 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012175 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012176 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012177 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012178 continue;
12179 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012180
Alexey Bataevbae9a792014-06-27 10:37:06 +000012181 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12182 // A variable of class type (or array thereof) that appears in a
12183 // copyin clause requires an accessible, unambiguous copy assignment
12184 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012185 Type = Context.getBaseElementType(Type.getNonReferenceType())
12186 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012187 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012188 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012189 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012190 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12191 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012192 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012193 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012194 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12195 ExprResult AssignmentOp = BuildBinOp(
12196 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012197 if (AssignmentOp.isInvalid())
12198 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012199 AssignmentOp =
12200 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012201 if (AssignmentOp.isInvalid())
12202 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012203
12204 // No need to mark vars as copyprivate, they are already threadprivate or
12205 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012206 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012207 Vars.push_back(
12208 VD ? RefExpr->IgnoreParens()
12209 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012210 SrcExprs.push_back(PseudoSrcExpr);
12211 DstExprs.push_back(PseudoDstExpr);
12212 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012213 }
12214
12215 if (Vars.empty())
12216 return nullptr;
12217
Alexey Bataeva63048e2015-03-23 06:18:07 +000012218 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12219 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012220}
12221
Alexey Bataev6125da92014-07-21 11:26:11 +000012222OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12223 SourceLocation StartLoc,
12224 SourceLocation LParenLoc,
12225 SourceLocation EndLoc) {
12226 if (VarList.empty())
12227 return nullptr;
12228
12229 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12230}
Alexey Bataevdea47612014-07-23 07:46:59 +000012231
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012232OMPClause *
12233Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12234 SourceLocation DepLoc, SourceLocation ColonLoc,
12235 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12236 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012237 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012238 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012239 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012240 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012241 return nullptr;
12242 }
12243 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012244 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12245 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012246 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012247 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012248 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12249 /*Last=*/OMPC_DEPEND_unknown, Except)
12250 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012251 return nullptr;
12252 }
12253 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012254 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012255 llvm::APSInt DepCounter(/*BitWidth=*/32);
12256 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012257 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12258 if (const Expr *OrderedCountExpr =
12259 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012260 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12261 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012262 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012263 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012264 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012265 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12266 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12267 // It will be analyzed later.
12268 Vars.push_back(RefExpr);
12269 continue;
12270 }
12271
12272 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012273 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012274 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012275 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012276 DepCounter >= TotalDepCount) {
12277 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12278 continue;
12279 }
12280 ++DepCounter;
12281 // OpenMP [2.13.9, Summary]
12282 // depend(dependence-type : vec), where dependence-type is:
12283 // 'sink' and where vec is the iteration vector, which has the form:
12284 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12285 // where n is the value specified by the ordered clause in the loop
12286 // directive, xi denotes the loop iteration variable of the i-th nested
12287 // loop associated with the loop directive, and di is a constant
12288 // non-negative integer.
12289 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012290 // It will be analyzed later.
12291 Vars.push_back(RefExpr);
12292 continue;
12293 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012294 SimpleExpr = SimpleExpr->IgnoreImplicit();
12295 OverloadedOperatorKind OOK = OO_None;
12296 SourceLocation OOLoc;
12297 Expr *LHS = SimpleExpr;
12298 Expr *RHS = nullptr;
12299 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12300 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12301 OOLoc = BO->getOperatorLoc();
12302 LHS = BO->getLHS()->IgnoreParenImpCasts();
12303 RHS = BO->getRHS()->IgnoreParenImpCasts();
12304 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12305 OOK = OCE->getOperator();
12306 OOLoc = OCE->getOperatorLoc();
12307 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12308 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12309 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12310 OOK = MCE->getMethodDecl()
12311 ->getNameInfo()
12312 .getName()
12313 .getCXXOverloadedOperator();
12314 OOLoc = MCE->getCallee()->getExprLoc();
12315 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12316 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012317 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012318 SourceLocation ELoc;
12319 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012320 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012321 if (Res.second) {
12322 // It will be analyzed later.
12323 Vars.push_back(RefExpr);
12324 }
12325 ValueDecl *D = Res.first;
12326 if (!D)
12327 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012328
Alexey Bataev17daedf2018-02-15 22:42:57 +000012329 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12330 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12331 continue;
12332 }
12333 if (RHS) {
12334 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12335 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12336 if (RHSRes.isInvalid())
12337 continue;
12338 }
12339 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012340 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012341 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012342 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012343 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012344 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012345 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12346 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012347 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012348 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012349 continue;
12350 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012351 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012352 } else {
12353 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12354 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12355 (ASE &&
12356 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12357 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12358 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12359 << RefExpr->getSourceRange();
12360 continue;
12361 }
12362 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12363 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12364 ExprResult Res =
12365 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12366 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12367 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12368 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12369 << RefExpr->getSourceRange();
12370 continue;
12371 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012372 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012373 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012374 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012375
12376 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12377 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012378 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012379 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12380 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12381 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12382 }
12383 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12384 Vars.empty())
12385 return nullptr;
12386
Alexey Bataev8b427062016-05-25 12:36:08 +000012387 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012388 DepKind, DepLoc, ColonLoc, Vars,
12389 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012390 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12391 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012392 DSAStack->addDoacrossDependClause(C, OpsOffs);
12393 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012394}
Michael Wonge710d542015-08-07 16:16:36 +000012395
12396OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12397 SourceLocation LParenLoc,
12398 SourceLocation EndLoc) {
12399 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012400 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012401
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012402 // OpenMP [2.9.1, Restrictions]
12403 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012404 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012405 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012406 return nullptr;
12407
Alexey Bataev931e19b2017-10-02 16:32:39 +000012408 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012409 OpenMPDirectiveKind CaptureRegion =
12410 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12411 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012412 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012413 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012414 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12415 HelperValStmt = buildPreInits(Context, Captures);
12416 }
12417
Alexey Bataev8451efa2018-01-15 19:06:12 +000012418 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12419 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012420}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012421
Alexey Bataeve3727102018-04-18 15:57:46 +000012422static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012423 DSAStackTy *Stack, QualType QTy,
12424 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012425 NamedDecl *ND;
12426 if (QTy->isIncompleteType(&ND)) {
12427 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12428 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012429 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012430 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12431 !QTy.isTrivialType(SemaRef.Context))
12432 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012433 return true;
12434}
12435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012436/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012437/// (array section or array subscript) does NOT specify the whole size of the
12438/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012439static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012440 const Expr *E,
12441 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012442 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012443
12444 // If this is an array subscript, it refers to the whole size if the size of
12445 // the dimension is constant and equals 1. Also, an array section assumes the
12446 // format of an array subscript if no colon is used.
12447 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012448 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012449 return ATy->getSize().getSExtValue() != 1;
12450 // Size can't be evaluated statically.
12451 return false;
12452 }
12453
12454 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012455 const Expr *LowerBound = OASE->getLowerBound();
12456 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012457
12458 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012459 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012460 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012461 Expr::EvalResult Result;
12462 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012463 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012464
12465 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012466 if (ConstLowerBound.getSExtValue())
12467 return true;
12468 }
12469
12470 // If we don't have a length we covering the whole dimension.
12471 if (!Length)
12472 return false;
12473
12474 // If the base is a pointer, we don't have a way to get the size of the
12475 // pointee.
12476 if (BaseQTy->isPointerType())
12477 return false;
12478
12479 // We can only check if the length is the same as the size of the dimension
12480 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012481 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012482 if (!CATy)
12483 return false;
12484
Fangrui Song407659a2018-11-30 23:41:18 +000012485 Expr::EvalResult Result;
12486 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012487 return false; // Can't get the integer value as a constant.
12488
Fangrui Song407659a2018-11-30 23:41:18 +000012489 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012490 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12491}
12492
12493// Return true if it can be proven that the provided array expression (array
12494// section or array subscript) does NOT specify a single element of the array
12495// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012496static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012497 const Expr *E,
12498 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012499 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012500
12501 // An array subscript always refer to a single element. Also, an array section
12502 // assumes the format of an array subscript if no colon is used.
12503 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12504 return false;
12505
12506 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012507 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012508
12509 // If we don't have a length we have to check if the array has unitary size
12510 // for this dimension. Also, we should always expect a length if the base type
12511 // is pointer.
12512 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012513 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012514 return ATy->getSize().getSExtValue() != 1;
12515 // We cannot assume anything.
12516 return false;
12517 }
12518
12519 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012520 Expr::EvalResult Result;
12521 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012522 return false; // Can't get the integer value as a constant.
12523
Fangrui Song407659a2018-11-30 23:41:18 +000012524 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012525 return ConstLength.getSExtValue() != 1;
12526}
12527
Samuel Antao661c0902016-05-26 17:39:58 +000012528// Return the expression of the base of the mappable expression or null if it
12529// cannot be determined and do all the necessary checks to see if the expression
12530// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012531// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012532static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012533 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012534 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012535 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012536 SourceLocation ELoc = E->getExprLoc();
12537 SourceRange ERange = E->getSourceRange();
12538
12539 // The base of elements of list in a map clause have to be either:
12540 // - a reference to variable or field.
12541 // - a member expression.
12542 // - an array expression.
12543 //
12544 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12545 // reference to 'r'.
12546 //
12547 // If we have:
12548 //
12549 // struct SS {
12550 // Bla S;
12551 // foo() {
12552 // #pragma omp target map (S.Arr[:12]);
12553 // }
12554 // }
12555 //
12556 // We want to retrieve the member expression 'this->S';
12557
Alexey Bataeve3727102018-04-18 15:57:46 +000012558 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012559
Samuel Antao5de996e2016-01-22 20:21:36 +000012560 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12561 // If a list item is an array section, it must specify contiguous storage.
12562 //
12563 // For this restriction it is sufficient that we make sure only references
12564 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012565 // exist except in the rightmost expression (unless they cover the whole
12566 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012567 //
12568 // r.ArrS[3:5].Arr[6:7]
12569 //
12570 // r.ArrS[3:5].x
12571 //
12572 // but these would be valid:
12573 // r.ArrS[3].Arr[6:7]
12574 //
12575 // r.ArrS[3].x
12576
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012577 bool AllowUnitySizeArraySection = true;
12578 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012579
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012580 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012581 E = E->IgnoreParenImpCasts();
12582
12583 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12584 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012585 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012586
12587 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012588
12589 // If we got a reference to a declaration, we should not expect any array
12590 // section before that.
12591 AllowUnitySizeArraySection = false;
12592 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012593
12594 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012595 CurComponents.emplace_back(CurE, CurE->getDecl());
12596 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012597 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012598
12599 if (isa<CXXThisExpr>(BaseE))
12600 // We found a base expression: this->Val.
12601 RelevantExpr = CurE;
12602 else
12603 E = BaseE;
12604
12605 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012606 if (!NoDiagnose) {
12607 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12608 << CurE->getSourceRange();
12609 return nullptr;
12610 }
12611 if (RelevantExpr)
12612 return nullptr;
12613 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012614 }
12615
12616 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12617
12618 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12619 // A bit-field cannot appear in a map clause.
12620 //
12621 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012622 if (!NoDiagnose) {
12623 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12624 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12625 return nullptr;
12626 }
12627 if (RelevantExpr)
12628 return nullptr;
12629 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012630 }
12631
12632 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12633 // If the type of a list item is a reference to a type T then the type
12634 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012635 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012636
12637 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12638 // A list item cannot be a variable that is a member of a structure with
12639 // a union type.
12640 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012641 if (CurType->isUnionType()) {
12642 if (!NoDiagnose) {
12643 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12644 << CurE->getSourceRange();
12645 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012646 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012647 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012648 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012649
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012650 // If we got a member expression, we should not expect any array section
12651 // before that:
12652 //
12653 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12654 // If a list item is an element of a structure, only the rightmost symbol
12655 // of the variable reference can be an array section.
12656 //
12657 AllowUnitySizeArraySection = false;
12658 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012659
12660 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012661 CurComponents.emplace_back(CurE, FD);
12662 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012663 E = CurE->getBase()->IgnoreParenImpCasts();
12664
12665 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012666 if (!NoDiagnose) {
12667 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12668 << 0 << CurE->getSourceRange();
12669 return nullptr;
12670 }
12671 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012672 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012673
12674 // If we got an array subscript that express the whole dimension we
12675 // can have any array expressions before. If it only expressing part of
12676 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012677 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012678 E->getType()))
12679 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012680
Patrick Lystere13b1e32019-01-02 19:28:48 +000012681 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12682 Expr::EvalResult Result;
12683 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12684 if (!Result.Val.getInt().isNullValue()) {
12685 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12686 diag::err_omp_invalid_map_this_expr);
12687 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12688 diag::note_omp_invalid_subscript_on_this_ptr_map);
12689 }
12690 }
12691 RelevantExpr = TE;
12692 }
12693
Samuel Antao90927002016-04-26 14:54:23 +000012694 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012695 CurComponents.emplace_back(CurE, nullptr);
12696 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012697 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000012698 E = CurE->getBase()->IgnoreParenImpCasts();
12699
Alexey Bataev27041fa2017-12-05 15:22:49 +000012700 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012701 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12702
Samuel Antao5de996e2016-01-22 20:21:36 +000012703 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12704 // If the type of a list item is a reference to a type T then the type
12705 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000012706 if (CurType->isReferenceType())
12707 CurType = CurType->getPointeeType();
12708
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012709 bool IsPointer = CurType->isAnyPointerType();
12710
12711 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012712 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12713 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012714 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012715 }
12716
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012717 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000012718 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012719 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000012720 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012721
Samuel Antaodab51bb2016-07-18 23:22:11 +000012722 if (AllowWholeSizeArraySection) {
12723 // Any array section is currently allowed. Allowing a whole size array
12724 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012725 //
12726 // If this array section refers to the whole dimension we can still
12727 // accept other array sections before this one, except if the base is a
12728 // pointer. Otherwise, only unitary sections are accepted.
12729 if (NotWhole || IsPointer)
12730 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000012731 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012732 // A unity or whole array section is not allowed and that is not
12733 // compatible with the properties of the current array section.
12734 SemaRef.Diag(
12735 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12736 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012737 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012738 }
Samuel Antao90927002016-04-26 14:54:23 +000012739
Patrick Lystere13b1e32019-01-02 19:28:48 +000012740 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12741 Expr::EvalResult ResultR;
12742 Expr::EvalResult ResultL;
12743 if (CurE->getLength()->EvaluateAsInt(ResultR,
12744 SemaRef.getASTContext())) {
12745 if (!ResultR.Val.getInt().isOneValue()) {
12746 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12747 diag::err_omp_invalid_map_this_expr);
12748 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12749 diag::note_omp_invalid_length_on_this_ptr_mapping);
12750 }
12751 }
12752 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
12753 ResultL, SemaRef.getASTContext())) {
12754 if (!ResultL.Val.getInt().isNullValue()) {
12755 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12756 diag::err_omp_invalid_map_this_expr);
12757 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12758 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
12759 }
12760 }
12761 RelevantExpr = TE;
12762 }
12763
Samuel Antao90927002016-04-26 14:54:23 +000012764 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012765 CurComponents.emplace_back(CurE, nullptr);
12766 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012767 if (!NoDiagnose) {
12768 // If nothing else worked, this is not a valid map clause expression.
12769 SemaRef.Diag(
12770 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12771 << ERange;
12772 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000012773 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012774 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012775 }
12776
12777 return RelevantExpr;
12778}
12779
12780// Return true if expression E associated with value VD has conflicts with other
12781// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000012782static bool checkMapConflicts(
12783 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000012784 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000012785 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12786 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012787 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000012788 SourceLocation ELoc = E->getExprLoc();
12789 SourceRange ERange = E->getSourceRange();
12790
12791 // In order to easily check the conflicts we need to match each component of
12792 // the expression under test with the components of the expressions that are
12793 // already in the stack.
12794
Samuel Antao5de996e2016-01-22 20:21:36 +000012795 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012796 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012797 "Map clause expression with unexpected base!");
12798
12799 // Variables to help detecting enclosing problems in data environment nests.
12800 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000012801 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012802
Samuel Antao90927002016-04-26 14:54:23 +000012803 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12804 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000012805 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12806 ERange, CKind, &EnclosingExpr,
12807 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12808 StackComponents,
12809 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012810 assert(!StackComponents.empty() &&
12811 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012812 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012813 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000012814 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012815
Samuel Antao90927002016-04-26 14:54:23 +000012816 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000012817 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000012818
Samuel Antao5de996e2016-01-22 20:21:36 +000012819 // Expressions must start from the same base. Here we detect at which
12820 // point both expressions diverge from each other and see if we can
12821 // detect if the memory referred to both expressions is contiguous and
12822 // do not overlap.
12823 auto CI = CurComponents.rbegin();
12824 auto CE = CurComponents.rend();
12825 auto SI = StackComponents.rbegin();
12826 auto SE = StackComponents.rend();
12827 for (; CI != CE && SI != SE; ++CI, ++SI) {
12828
12829 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12830 // At most one list item can be an array item derived from a given
12831 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000012832 if (CurrentRegionOnly &&
12833 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12834 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12835 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12836 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12837 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000012838 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000012839 << CI->getAssociatedExpression()->getSourceRange();
12840 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12841 diag::note_used_here)
12842 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000012843 return true;
12844 }
12845
12846 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000012847 if (CI->getAssociatedExpression()->getStmtClass() !=
12848 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000012849 break;
12850
12851 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000012852 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000012853 break;
12854 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000012855 // Check if the extra components of the expressions in the enclosing
12856 // data environment are redundant for the current base declaration.
12857 // If they are, the maps completely overlap, which is legal.
12858 for (; SI != SE; ++SI) {
12859 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000012860 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000012861 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012862 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012863 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000012864 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012865 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000012866 Type =
12867 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12868 }
12869 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012870 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000012871 SemaRef, SI->getAssociatedExpression(), Type))
12872 break;
12873 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012874
12875 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12876 // List items of map clauses in the same construct must not share
12877 // original storage.
12878 //
12879 // If the expressions are exactly the same or one is a subset of the
12880 // other, it means they are sharing storage.
12881 if (CI == CE && SI == SE) {
12882 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012883 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000012884 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012885 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012886 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012887 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12888 << ERange;
12889 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012890 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12891 << RE->getSourceRange();
12892 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012893 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012894 // If we find the same expression in the enclosing data environment,
12895 // that is legal.
12896 IsEnclosedByDataEnvironmentExpr = true;
12897 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000012898 }
12899
Samuel Antao90927002016-04-26 14:54:23 +000012900 QualType DerivedType =
12901 std::prev(CI)->getAssociatedDeclaration()->getType();
12902 SourceLocation DerivedLoc =
12903 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012904
12905 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12906 // If the type of a list item is a reference to a type T then the type
12907 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012908 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012909
12910 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12911 // A variable for which the type is pointer and an array section
12912 // derived from that variable must not appear as list items of map
12913 // clauses of the same construct.
12914 //
12915 // Also, cover one of the cases in:
12916 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12917 // If any part of the original storage of a list item has corresponding
12918 // storage in the device data environment, all of the original storage
12919 // must have corresponding storage in the device data environment.
12920 //
12921 if (DerivedType->isAnyPointerType()) {
12922 if (CI == CE || SI == SE) {
12923 SemaRef.Diag(
12924 DerivedLoc,
12925 diag::err_omp_pointer_mapped_along_with_derived_section)
12926 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012927 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12928 << RE->getSourceRange();
12929 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000012930 }
12931 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000012932 SI->getAssociatedExpression()->getStmtClass() ||
12933 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12934 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012935 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012936 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012937 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012938 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12939 << RE->getSourceRange();
12940 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012941 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012942 }
12943
12944 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12945 // List items of map clauses in the same construct must not share
12946 // original storage.
12947 //
12948 // An expression is a subset of the other.
12949 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012950 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000012951 if (CI != CE || SI != SE) {
12952 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12953 // a pointer.
12954 auto Begin =
12955 CI != CE ? CurComponents.begin() : StackComponents.begin();
12956 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12957 auto It = Begin;
12958 while (It != End && !It->getAssociatedDeclaration())
12959 std::advance(It, 1);
12960 assert(It != End &&
12961 "Expected at least one component with the declaration.");
12962 if (It != Begin && It->getAssociatedDeclaration()
12963 ->getType()
12964 .getCanonicalType()
12965 ->isAnyPointerType()) {
12966 IsEnclosedByDataEnvironmentExpr = false;
12967 EnclosingExpr = nullptr;
12968 return false;
12969 }
12970 }
Samuel Antao661c0902016-05-26 17:39:58 +000012971 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012972 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012973 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012974 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12975 << ERange;
12976 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012977 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12978 << RE->getSourceRange();
12979 return true;
12980 }
12981
12982 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012983 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012984 if (!CurrentRegionOnly && SI != SE)
12985 EnclosingExpr = RE;
12986
12987 // The current expression is a subset of the expression in the data
12988 // environment.
12989 IsEnclosedByDataEnvironmentExpr |=
12990 (!CurrentRegionOnly && CI != CE && SI == SE);
12991
12992 return false;
12993 });
12994
12995 if (CurrentRegionOnly)
12996 return FoundError;
12997
12998 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12999 // If any part of the original storage of a list item has corresponding
13000 // storage in the device data environment, all of the original storage must
13001 // have corresponding storage in the device data environment.
13002 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13003 // If a list item is an element of a structure, and a different element of
13004 // the structure has a corresponding list item in the device data environment
13005 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013006 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013007 // data environment prior to the task encountering the construct.
13008 //
13009 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13010 SemaRef.Diag(ELoc,
13011 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13012 << ERange;
13013 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13014 << EnclosingExpr->getSourceRange();
13015 return true;
13016 }
13017
13018 return FoundError;
13019}
13020
Michael Kruse4304e9d2019-02-19 16:38:20 +000013021// Look up the user-defined mapper given the mapper name and mapped type, and
13022// build a reference to it.
13023ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13024 CXXScopeSpec &MapperIdScopeSpec,
13025 const DeclarationNameInfo &MapperId,
13026 QualType Type, Expr *UnresolvedMapper) {
13027 if (MapperIdScopeSpec.isInvalid())
13028 return ExprError();
13029 // Find all user-defined mappers with the given MapperId.
13030 SmallVector<UnresolvedSet<8>, 4> Lookups;
13031 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13032 Lookup.suppressDiagnostics();
13033 if (S) {
13034 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13035 NamedDecl *D = Lookup.getRepresentativeDecl();
13036 while (S && !S->isDeclScope(D))
13037 S = S->getParent();
13038 if (S)
13039 S = S->getParent();
13040 Lookups.emplace_back();
13041 Lookups.back().append(Lookup.begin(), Lookup.end());
13042 Lookup.clear();
13043 }
13044 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13045 // Extract the user-defined mappers with the given MapperId.
13046 Lookups.push_back(UnresolvedSet<8>());
13047 for (NamedDecl *D : ULE->decls()) {
13048 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13049 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13050 Lookups.back().addDecl(DMD);
13051 }
13052 }
13053 // Defer the lookup for dependent types. The results will be passed through
13054 // UnresolvedMapper on instantiation.
13055 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13056 Type->isInstantiationDependentType() ||
13057 Type->containsUnexpandedParameterPack() ||
13058 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13059 return !D->isInvalidDecl() &&
13060 (D->getType()->isDependentType() ||
13061 D->getType()->isInstantiationDependentType() ||
13062 D->getType()->containsUnexpandedParameterPack());
13063 })) {
13064 UnresolvedSet<8> URS;
13065 for (const UnresolvedSet<8> &Set : Lookups) {
13066 if (Set.empty())
13067 continue;
13068 URS.append(Set.begin(), Set.end());
13069 }
13070 return UnresolvedLookupExpr::Create(
13071 SemaRef.Context, /*NamingClass=*/nullptr,
13072 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13073 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13074 }
13075 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13076 // The type must be of struct, union or class type in C and C++
13077 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13078 return ExprEmpty();
13079 SourceLocation Loc = MapperId.getLoc();
13080 // Perform argument dependent lookup.
13081 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13082 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13083 // Return the first user-defined mapper with the desired type.
13084 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13085 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13086 if (!D->isInvalidDecl() &&
13087 SemaRef.Context.hasSameType(D->getType(), Type))
13088 return D;
13089 return nullptr;
13090 }))
13091 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13092 // Find the first user-defined mapper with a type derived from the desired
13093 // type.
13094 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13095 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13096 if (!D->isInvalidDecl() &&
13097 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13098 !Type.isMoreQualifiedThan(D->getType()))
13099 return D;
13100 return nullptr;
13101 })) {
13102 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13103 /*DetectVirtual=*/false);
13104 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13105 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13106 VD->getType().getUnqualifiedType()))) {
13107 if (SemaRef.CheckBaseClassAccess(
13108 Loc, VD->getType(), Type, Paths.front(),
13109 /*DiagID=*/0) != Sema::AR_inaccessible) {
13110 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13111 }
13112 }
13113 }
13114 }
13115 // Report error if a mapper is specified, but cannot be found.
13116 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13117 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13118 << Type << MapperId.getName();
13119 return ExprError();
13120 }
13121 return ExprEmpty();
13122}
13123
Samuel Antao661c0902016-05-26 17:39:58 +000013124namespace {
13125// Utility struct that gathers all the related lists associated with a mappable
13126// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013127struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013128 // The list of expressions.
13129 ArrayRef<Expr *> VarList;
13130 // The list of processed expressions.
13131 SmallVector<Expr *, 16> ProcessedVarList;
13132 // The mappble components for each expression.
13133 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13134 // The base declaration of the variable.
13135 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013136 // The reference to the user-defined mapper associated with every expression.
13137 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013138
13139 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13140 // We have a list of components and base declarations for each entry in the
13141 // variable list.
13142 VarComponents.reserve(VarList.size());
13143 VarBaseDeclarations.reserve(VarList.size());
13144 }
13145};
13146}
13147
13148// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013149// \a CKind. In the check process the valid expressions, mappable expression
13150// components, variables, and user-defined mappers are extracted and used to
13151// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13152// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13153// and \a MapperId are expected to be valid if the clause kind is 'map'.
13154static void checkMappableExpressionList(
13155 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13156 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013157 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13158 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013159 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013160 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013161 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13162 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013163 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013164
13165 // If the identifier of user-defined mapper is not specified, it is "default".
13166 // We do not change the actual name in this clause to distinguish whether a
13167 // mapper is specified explicitly, i.e., it is not explicitly specified when
13168 // MapperId.getName() is empty.
13169 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13170 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13171 MapperId.setName(DeclNames.getIdentifier(
13172 &SemaRef.getASTContext().Idents.get("default")));
13173 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013174
13175 // Iterators to find the current unresolved mapper expression.
13176 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13177 bool UpdateUMIt = false;
13178 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013179
Samuel Antao90927002016-04-26 14:54:23 +000013180 // Keep track of the mappable components and base declarations in this clause.
13181 // Each entry in the list is going to have a list of components associated. We
13182 // record each set of the components so that we can build the clause later on.
13183 // In the end we should have the same amount of declarations and component
13184 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013185
Alexey Bataeve3727102018-04-18 15:57:46 +000013186 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013187 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013188 SourceLocation ELoc = RE->getExprLoc();
13189
Michael Kruse4304e9d2019-02-19 16:38:20 +000013190 // Find the current unresolved mapper expression.
13191 if (UpdateUMIt && UMIt != UMEnd) {
13192 UMIt++;
13193 assert(
13194 UMIt != UMEnd &&
13195 "Expect the size of UnresolvedMappers to match with that of VarList");
13196 }
13197 UpdateUMIt = true;
13198 if (UMIt != UMEnd)
13199 UnresolvedMapper = *UMIt;
13200
Alexey Bataeve3727102018-04-18 15:57:46 +000013201 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013202
13203 if (VE->isValueDependent() || VE->isTypeDependent() ||
13204 VE->isInstantiationDependent() ||
13205 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013206 // Try to find the associated user-defined mapper.
13207 ExprResult ER = buildUserDefinedMapperRef(
13208 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13209 VE->getType().getCanonicalType(), UnresolvedMapper);
13210 if (ER.isInvalid())
13211 continue;
13212 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013213 // We can only analyze this information once the missing information is
13214 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013215 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013216 continue;
13217 }
13218
Alexey Bataeve3727102018-04-18 15:57:46 +000013219 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013220
Samuel Antao5de996e2016-01-22 20:21:36 +000013221 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013222 SemaRef.Diag(ELoc,
13223 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013224 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013225 continue;
13226 }
13227
Samuel Antao90927002016-04-26 14:54:23 +000013228 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13229 ValueDecl *CurDeclaration = nullptr;
13230
13231 // Obtain the array or member expression bases if required. Also, fill the
13232 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013233 const Expr *BE = checkMapClauseExpressionBase(
13234 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013235 if (!BE)
13236 continue;
13237
Samuel Antao90927002016-04-26 14:54:23 +000013238 assert(!CurComponents.empty() &&
13239 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013240
Patrick Lystere13b1e32019-01-02 19:28:48 +000013241 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13242 // Add store "this" pointer to class in DSAStackTy for future checking
13243 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013244 // Try to find the associated user-defined mapper.
13245 ExprResult ER = buildUserDefinedMapperRef(
13246 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13247 VE->getType().getCanonicalType(), UnresolvedMapper);
13248 if (ER.isInvalid())
13249 continue;
13250 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013251 // Skip restriction checking for variable or field declarations
13252 MVLI.ProcessedVarList.push_back(RE);
13253 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13254 MVLI.VarComponents.back().append(CurComponents.begin(),
13255 CurComponents.end());
13256 MVLI.VarBaseDeclarations.push_back(nullptr);
13257 continue;
13258 }
13259
Samuel Antao90927002016-04-26 14:54:23 +000013260 // For the following checks, we rely on the base declaration which is
13261 // expected to be associated with the last component. The declaration is
13262 // expected to be a variable or a field (if 'this' is being mapped).
13263 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13264 assert(CurDeclaration && "Null decl on map clause.");
13265 assert(
13266 CurDeclaration->isCanonicalDecl() &&
13267 "Expecting components to have associated only canonical declarations.");
13268
13269 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013270 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013271
13272 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013273 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013274
13275 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013276 // threadprivate variables cannot appear in a map clause.
13277 // OpenMP 4.5 [2.10.5, target update Construct]
13278 // threadprivate variables cannot appear in a from clause.
13279 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013280 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013281 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13282 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013283 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013284 continue;
13285 }
13286
Samuel Antao5de996e2016-01-22 20:21:36 +000013287 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13288 // A list item cannot appear in both a map clause and a data-sharing
13289 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013290
Samuel Antao5de996e2016-01-22 20:21:36 +000013291 // Check conflicts with other map clause expressions. We check the conflicts
13292 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013293 // environment, because the restrictions are different. We only have to
13294 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013295 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013296 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013297 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013298 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013299 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013300 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013301 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013302
Samuel Antao661c0902016-05-26 17:39:58 +000013303 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013304 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13305 // If the type of a list item is a reference to a type T then the type will
13306 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013307 auto I = llvm::find_if(
13308 CurComponents,
13309 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13310 return MC.getAssociatedDeclaration();
13311 });
13312 assert(I != CurComponents.end() && "Null decl on map clause.");
13313 QualType Type =
13314 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013315
Samuel Antao661c0902016-05-26 17:39:58 +000013316 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13317 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013318 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013319 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013320 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013321 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013322 continue;
13323
Samuel Antao661c0902016-05-26 17:39:58 +000013324 if (CKind == OMPC_map) {
13325 // target enter data
13326 // OpenMP [2.10.2, Restrictions, p. 99]
13327 // A map-type must be specified in all map clauses and must be either
13328 // to or alloc.
13329 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13330 if (DKind == OMPD_target_enter_data &&
13331 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13332 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13333 << (IsMapTypeImplicit ? 1 : 0)
13334 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13335 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013336 continue;
13337 }
Samuel Antao661c0902016-05-26 17:39:58 +000013338
13339 // target exit_data
13340 // OpenMP [2.10.3, Restrictions, p. 102]
13341 // A map-type must be specified in all map clauses and must be either
13342 // from, release, or delete.
13343 if (DKind == OMPD_target_exit_data &&
13344 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13345 MapType == OMPC_MAP_delete)) {
13346 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13347 << (IsMapTypeImplicit ? 1 : 0)
13348 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13349 << getOpenMPDirectiveName(DKind);
13350 continue;
13351 }
13352
13353 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13354 // A list item cannot appear in both a map clause and a data-sharing
13355 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013356 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13357 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013358 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013359 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013360 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013361 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013362 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013363 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013364 continue;
13365 }
13366 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013367 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013368
Michael Kruse01f670d2019-02-22 22:29:42 +000013369 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013370 ExprResult ER = buildUserDefinedMapperRef(
13371 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13372 Type.getCanonicalType(), UnresolvedMapper);
13373 if (ER.isInvalid())
13374 continue;
13375 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013376
Samuel Antao90927002016-04-26 14:54:23 +000013377 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013378 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013379
13380 // Store the components in the stack so that they can be used to check
13381 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013382 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13383 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013384
13385 // Save the components and declaration to create the clause. For purposes of
13386 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013387 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013388 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13389 MVLI.VarComponents.back().append(CurComponents.begin(),
13390 CurComponents.end());
13391 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13392 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013393 }
Samuel Antao661c0902016-05-26 17:39:58 +000013394}
13395
Michael Kruse4304e9d2019-02-19 16:38:20 +000013396OMPClause *Sema::ActOnOpenMPMapClause(
13397 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13398 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13399 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13400 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13401 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13402 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13403 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13404 OMPC_MAP_MODIFIER_unknown,
13405 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013406 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13407
13408 // Process map-type-modifiers, flag errors for duplicate modifiers.
13409 unsigned Count = 0;
13410 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13411 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13412 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13413 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13414 continue;
13415 }
13416 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013417 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013418 Modifiers[Count] = MapTypeModifiers[I];
13419 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13420 ++Count;
13421 }
13422
Michael Kruse4304e9d2019-02-19 16:38:20 +000013423 MappableVarListInfo MVLI(VarList);
13424 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013425 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13426 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013427
Samuel Antao5de996e2016-01-22 20:21:36 +000013428 // We need to produce a map clause even if we don't have variables so that
13429 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013430 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13431 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13432 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13433 MapperIdScopeSpec.getWithLocInContext(Context),
13434 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013435}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013436
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013437QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13438 TypeResult ParsedType) {
13439 assert(ParsedType.isUsable());
13440
13441 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13442 if (ReductionType.isNull())
13443 return QualType();
13444
13445 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13446 // A type name in a declare reduction directive cannot be a function type, an
13447 // array type, a reference type, or a type qualified with const, volatile or
13448 // restrict.
13449 if (ReductionType.hasQualifiers()) {
13450 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13451 return QualType();
13452 }
13453
13454 if (ReductionType->isFunctionType()) {
13455 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13456 return QualType();
13457 }
13458 if (ReductionType->isReferenceType()) {
13459 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13460 return QualType();
13461 }
13462 if (ReductionType->isArrayType()) {
13463 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13464 return QualType();
13465 }
13466 return ReductionType;
13467}
13468
13469Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13470 Scope *S, DeclContext *DC, DeclarationName Name,
13471 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13472 AccessSpecifier AS, Decl *PrevDeclInScope) {
13473 SmallVector<Decl *, 8> Decls;
13474 Decls.reserve(ReductionTypes.size());
13475
13476 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013477 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013478 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13479 // A reduction-identifier may not be re-declared in the current scope for the
13480 // same type or for a type that is compatible according to the base language
13481 // rules.
13482 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13483 OMPDeclareReductionDecl *PrevDRD = nullptr;
13484 bool InCompoundScope = true;
13485 if (S != nullptr) {
13486 // Find previous declaration with the same name not referenced in other
13487 // declarations.
13488 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13489 InCompoundScope =
13490 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13491 LookupName(Lookup, S);
13492 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13493 /*AllowInlineNamespace=*/false);
13494 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013495 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013496 while (Filter.hasNext()) {
13497 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13498 if (InCompoundScope) {
13499 auto I = UsedAsPrevious.find(PrevDecl);
13500 if (I == UsedAsPrevious.end())
13501 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013502 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013503 UsedAsPrevious[D] = true;
13504 }
13505 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13506 PrevDecl->getLocation();
13507 }
13508 Filter.done();
13509 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013510 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013511 if (!PrevData.second) {
13512 PrevDRD = PrevData.first;
13513 break;
13514 }
13515 }
13516 }
13517 } else if (PrevDeclInScope != nullptr) {
13518 auto *PrevDRDInScope = PrevDRD =
13519 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13520 do {
13521 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13522 PrevDRDInScope->getLocation();
13523 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13524 } while (PrevDRDInScope != nullptr);
13525 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013526 for (const auto &TyData : ReductionTypes) {
13527 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013528 bool Invalid = false;
13529 if (I != PreviousRedeclTypes.end()) {
13530 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13531 << TyData.first;
13532 Diag(I->second, diag::note_previous_definition);
13533 Invalid = true;
13534 }
13535 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13536 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13537 Name, TyData.first, PrevDRD);
13538 DC->addDecl(DRD);
13539 DRD->setAccess(AS);
13540 Decls.push_back(DRD);
13541 if (Invalid)
13542 DRD->setInvalidDecl();
13543 else
13544 PrevDRD = DRD;
13545 }
13546
13547 return DeclGroupPtrTy::make(
13548 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13549}
13550
13551void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13552 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13553
13554 // Enter new function scope.
13555 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013556 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013557 getCurFunction()->setHasOMPDeclareReductionCombiner();
13558
13559 if (S != nullptr)
13560 PushDeclContext(S, DRD);
13561 else
13562 CurContext = DRD;
13563
Faisal Valid143a0c2017-04-01 21:30:49 +000013564 PushExpressionEvaluationContext(
13565 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013566
13567 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013568 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13569 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13570 // uses semantics of argument handles by value, but it should be passed by
13571 // reference. C lang does not support references, so pass all parameters as
13572 // pointers.
13573 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013574 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013575 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013576 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13577 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13578 // uses semantics of argument handles by value, but it should be passed by
13579 // reference. C lang does not support references, so pass all parameters as
13580 // pointers.
13581 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013582 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013583 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13584 if (S != nullptr) {
13585 PushOnScopeChains(OmpInParm, S);
13586 PushOnScopeChains(OmpOutParm, S);
13587 } else {
13588 DRD->addDecl(OmpInParm);
13589 DRD->addDecl(OmpOutParm);
13590 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013591 Expr *InE =
13592 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13593 Expr *OutE =
13594 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13595 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013596}
13597
13598void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13599 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13600 DiscardCleanupsInEvaluationContext();
13601 PopExpressionEvaluationContext();
13602
13603 PopDeclContext();
13604 PopFunctionScopeInfo();
13605
13606 if (Combiner != nullptr)
13607 DRD->setCombiner(Combiner);
13608 else
13609 DRD->setInvalidDecl();
13610}
13611
Alexey Bataev070f43a2017-09-06 14:49:58 +000013612VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013613 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13614
13615 // Enter new function scope.
13616 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013617 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013618
13619 if (S != nullptr)
13620 PushDeclContext(S, DRD);
13621 else
13622 CurContext = DRD;
13623
Faisal Valid143a0c2017-04-01 21:30:49 +000013624 PushExpressionEvaluationContext(
13625 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013626
13627 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013628 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13629 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13630 // uses semantics of argument handles by value, but it should be passed by
13631 // reference. C lang does not support references, so pass all parameters as
13632 // pointers.
13633 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013634 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013635 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013636 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13637 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13638 // uses semantics of argument handles by value, but it should be passed by
13639 // reference. C lang does not support references, so pass all parameters as
13640 // pointers.
13641 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013642 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013643 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013644 if (S != nullptr) {
13645 PushOnScopeChains(OmpPrivParm, S);
13646 PushOnScopeChains(OmpOrigParm, S);
13647 } else {
13648 DRD->addDecl(OmpPrivParm);
13649 DRD->addDecl(OmpOrigParm);
13650 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013651 Expr *OrigE =
13652 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13653 Expr *PrivE =
13654 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13655 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013656 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013657}
13658
Alexey Bataev070f43a2017-09-06 14:49:58 +000013659void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13660 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013661 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13662 DiscardCleanupsInEvaluationContext();
13663 PopExpressionEvaluationContext();
13664
13665 PopDeclContext();
13666 PopFunctionScopeInfo();
13667
Alexey Bataev070f43a2017-09-06 14:49:58 +000013668 if (Initializer != nullptr) {
13669 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13670 } else if (OmpPrivParm->hasInit()) {
13671 DRD->setInitializer(OmpPrivParm->getInit(),
13672 OmpPrivParm->isDirectInit()
13673 ? OMPDeclareReductionDecl::DirectInit
13674 : OMPDeclareReductionDecl::CopyInit);
13675 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013676 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013677 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013678}
13679
13680Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13681 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013682 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013683 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013684 if (S)
13685 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13686 /*AddToContext=*/false);
13687 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013688 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013689 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013690 }
13691 return DeclReductions;
13692}
13693
Michael Kruse251e1482019-02-01 20:25:04 +000013694TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13695 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13696 QualType T = TInfo->getType();
13697 if (D.isInvalidType())
13698 return true;
13699
13700 if (getLangOpts().CPlusPlus) {
13701 // Check that there are no default arguments (C++ only).
13702 CheckExtraCXXDefaultArguments(D);
13703 }
13704
13705 return CreateParsedType(T, TInfo);
13706}
13707
13708QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
13709 TypeResult ParsedType) {
13710 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
13711
13712 QualType MapperType = GetTypeFromParser(ParsedType.get());
13713 assert(!MapperType.isNull() && "Expect valid mapper type");
13714
13715 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13716 // The type must be of struct, union or class type in C and C++
13717 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
13718 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
13719 return QualType();
13720 }
13721 return MapperType;
13722}
13723
13724OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
13725 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
13726 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
13727 Decl *PrevDeclInScope) {
13728 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
13729 forRedeclarationInCurContext());
13730 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13731 // A mapper-identifier may not be redeclared in the current scope for the
13732 // same type or for a type that is compatible according to the base language
13733 // rules.
13734 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13735 OMPDeclareMapperDecl *PrevDMD = nullptr;
13736 bool InCompoundScope = true;
13737 if (S != nullptr) {
13738 // Find previous declaration with the same name not referenced in other
13739 // declarations.
13740 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13741 InCompoundScope =
13742 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13743 LookupName(Lookup, S);
13744 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13745 /*AllowInlineNamespace=*/false);
13746 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
13747 LookupResult::Filter Filter = Lookup.makeFilter();
13748 while (Filter.hasNext()) {
13749 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
13750 if (InCompoundScope) {
13751 auto I = UsedAsPrevious.find(PrevDecl);
13752 if (I == UsedAsPrevious.end())
13753 UsedAsPrevious[PrevDecl] = false;
13754 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
13755 UsedAsPrevious[D] = true;
13756 }
13757 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13758 PrevDecl->getLocation();
13759 }
13760 Filter.done();
13761 if (InCompoundScope) {
13762 for (const auto &PrevData : UsedAsPrevious) {
13763 if (!PrevData.second) {
13764 PrevDMD = PrevData.first;
13765 break;
13766 }
13767 }
13768 }
13769 } else if (PrevDeclInScope) {
13770 auto *PrevDMDInScope = PrevDMD =
13771 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
13772 do {
13773 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
13774 PrevDMDInScope->getLocation();
13775 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
13776 } while (PrevDMDInScope != nullptr);
13777 }
13778 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
13779 bool Invalid = false;
13780 if (I != PreviousRedeclTypes.end()) {
13781 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
13782 << MapperType << Name;
13783 Diag(I->second, diag::note_previous_definition);
13784 Invalid = true;
13785 }
13786 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
13787 MapperType, VN, PrevDMD);
13788 DC->addDecl(DMD);
13789 DMD->setAccess(AS);
13790 if (Invalid)
13791 DMD->setInvalidDecl();
13792
13793 // Enter new function scope.
13794 PushFunctionScope();
13795 setFunctionHasBranchProtectedScope();
13796
13797 CurContext = DMD;
13798
13799 return DMD;
13800}
13801
13802void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
13803 Scope *S,
13804 QualType MapperType,
13805 SourceLocation StartLoc,
13806 DeclarationName VN) {
13807 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
13808 if (S)
13809 PushOnScopeChains(VD, S);
13810 else
13811 DMD->addDecl(VD);
13812 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
13813 DMD->setMapperVarRef(MapperVarRefExpr);
13814}
13815
13816Sema::DeclGroupPtrTy
13817Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
13818 ArrayRef<OMPClause *> ClauseList) {
13819 PopDeclContext();
13820 PopFunctionScopeInfo();
13821
13822 if (D) {
13823 if (S)
13824 PushOnScopeChains(D, S, /*AddToContext=*/false);
13825 D->CreateClauses(Context, ClauseList);
13826 }
13827
13828 return DeclGroupPtrTy::make(DeclGroupRef(D));
13829}
13830
David Majnemer9d168222016-08-05 17:44:54 +000013831OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000013832 SourceLocation StartLoc,
13833 SourceLocation LParenLoc,
13834 SourceLocation EndLoc) {
13835 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013836 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013837
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013838 // OpenMP [teams Constrcut, Restrictions]
13839 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013840 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000013841 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013842 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013843
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013844 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013845 OpenMPDirectiveKind CaptureRegion =
13846 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13847 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013848 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013849 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013850 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13851 HelperValStmt = buildPreInits(Context, Captures);
13852 }
13853
13854 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13855 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000013856}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013857
13858OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13859 SourceLocation StartLoc,
13860 SourceLocation LParenLoc,
13861 SourceLocation EndLoc) {
13862 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013863 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013864
13865 // OpenMP [teams Constrcut, Restrictions]
13866 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013867 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000013868 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013869 return nullptr;
13870
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013871 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013872 OpenMPDirectiveKind CaptureRegion =
13873 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13874 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013875 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013876 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013877 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13878 HelperValStmt = buildPreInits(Context, Captures);
13879 }
13880
13881 return new (Context) OMPThreadLimitClause(
13882 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013883}
Alexey Bataeva0569352015-12-01 10:17:31 +000013884
13885OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13886 SourceLocation StartLoc,
13887 SourceLocation LParenLoc,
13888 SourceLocation EndLoc) {
13889 Expr *ValExpr = Priority;
13890
13891 // OpenMP [2.9.1, task Constrcut]
13892 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013893 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000013894 /*StrictlyPositive=*/false))
13895 return nullptr;
13896
13897 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13898}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013899
13900OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13901 SourceLocation StartLoc,
13902 SourceLocation LParenLoc,
13903 SourceLocation EndLoc) {
13904 Expr *ValExpr = Grainsize;
13905
13906 // OpenMP [2.9.2, taskloop Constrcut]
13907 // The parameter of the grainsize clause must be a positive integer
13908 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013909 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013910 /*StrictlyPositive=*/true))
13911 return nullptr;
13912
13913 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13914}
Alexey Bataev382967a2015-12-08 12:06:20 +000013915
13916OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13917 SourceLocation StartLoc,
13918 SourceLocation LParenLoc,
13919 SourceLocation EndLoc) {
13920 Expr *ValExpr = NumTasks;
13921
13922 // OpenMP [2.9.2, taskloop Constrcut]
13923 // The parameter of the num_tasks clause must be a positive integer
13924 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013925 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000013926 /*StrictlyPositive=*/true))
13927 return nullptr;
13928
13929 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13930}
13931
Alexey Bataev28c75412015-12-15 08:19:24 +000013932OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13933 SourceLocation LParenLoc,
13934 SourceLocation EndLoc) {
13935 // OpenMP [2.13.2, critical construct, Description]
13936 // ... where hint-expression is an integer constant expression that evaluates
13937 // to a valid lock hint.
13938 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13939 if (HintExpr.isInvalid())
13940 return nullptr;
13941 return new (Context)
13942 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13943}
13944
Carlo Bertollib4adf552016-01-15 18:50:31 +000013945OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13946 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13947 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13948 SourceLocation EndLoc) {
13949 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13950 std::string Values;
13951 Values += "'";
13952 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13953 Values += "'";
13954 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13955 << Values << getOpenMPClauseName(OMPC_dist_schedule);
13956 return nullptr;
13957 }
13958 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000013959 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000013960 if (ChunkSize) {
13961 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13962 !ChunkSize->isInstantiationDependent() &&
13963 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013964 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000013965 ExprResult Val =
13966 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13967 if (Val.isInvalid())
13968 return nullptr;
13969
13970 ValExpr = Val.get();
13971
13972 // OpenMP [2.7.1, Restrictions]
13973 // chunk_size must be a loop invariant integer expression with a positive
13974 // value.
13975 llvm::APSInt Result;
13976 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13977 if (Result.isSigned() && !Result.isStrictlyPositive()) {
13978 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13979 << "dist_schedule" << ChunkSize->getSourceRange();
13980 return nullptr;
13981 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000013982 } else if (getOpenMPCaptureRegionForClause(
13983 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13984 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000013985 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013986 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013987 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000013988 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13989 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013990 }
13991 }
13992 }
13993
13994 return new (Context)
13995 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000013996 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013997}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013998
13999OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14000 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14001 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14002 SourceLocation KindLoc, SourceLocation EndLoc) {
14003 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014004 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014005 std::string Value;
14006 SourceLocation Loc;
14007 Value += "'";
14008 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14009 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014010 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014011 Loc = MLoc;
14012 } else {
14013 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014014 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014015 Loc = KindLoc;
14016 }
14017 Value += "'";
14018 Diag(Loc, diag::err_omp_unexpected_clause_value)
14019 << Value << getOpenMPClauseName(OMPC_defaultmap);
14020 return nullptr;
14021 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014022 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014023
14024 return new (Context)
14025 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14026}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014027
14028bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14029 DeclContext *CurLexicalContext = getCurLexicalContext();
14030 if (!CurLexicalContext->isFileContext() &&
14031 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014032 !CurLexicalContext->isExternCXXContext() &&
14033 !isa<CXXRecordDecl>(CurLexicalContext) &&
14034 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14035 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14036 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014037 Diag(Loc, diag::err_omp_region_not_file_context);
14038 return false;
14039 }
Kelvin Libc38e632018-09-10 02:07:09 +000014040 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014041 return true;
14042}
14043
14044void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014045 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014046 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014047 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014048}
14049
David Majnemer9d168222016-08-05 17:44:54 +000014050void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14051 CXXScopeSpec &ScopeSpec,
14052 const DeclarationNameInfo &Id,
14053 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14054 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014055 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14056 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14057
14058 if (Lookup.isAmbiguous())
14059 return;
14060 Lookup.suppressDiagnostics();
14061
14062 if (!Lookup.isSingleResult()) {
14063 if (TypoCorrection Corrected =
14064 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14065 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14066 CTK_ErrorRecovery)) {
14067 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14068 << Id.getName());
14069 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14070 return;
14071 }
14072
14073 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14074 return;
14075 }
14076
14077 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014078 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14079 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014080 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14081 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014082 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14083 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14084 cast<ValueDecl>(ND));
14085 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014086 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014087 ND->addAttr(A);
14088 if (ASTMutationListener *ML = Context.getASTMutationListener())
14089 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014090 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014091 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014092 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14093 << Id.getName();
14094 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014095 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014096 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014097 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014098}
14099
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014100static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14101 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014102 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014103 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014104 auto *VD = cast<VarDecl>(D);
14105 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14106 return;
14107 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14108 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014109}
14110
14111static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14112 Sema &SemaRef, DSAStackTy *Stack,
14113 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014114 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14115 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14116 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014117}
14118
Kelvin Li1ce87c72017-12-12 20:08:12 +000014119void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14120 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014121 if (!D || D->isInvalidDecl())
14122 return;
14123 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014124 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014125 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014126 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014127 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14128 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014129 return;
14130 // 2.10.6: threadprivate variable cannot appear in a declare target
14131 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014132 if (DSAStack->isThreadPrivate(VD)) {
14133 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014134 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014135 return;
14136 }
14137 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014138 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14139 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014140 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014141 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14142 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14143 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014144 assert(IdLoc.isValid() && "Source location is expected");
14145 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14146 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14147 return;
14148 }
14149 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014150 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14151 // Problem if any with var declared with incomplete type will be reported
14152 // as normal, so no need to check it here.
14153 if ((E || !VD->getType()->isIncompleteType()) &&
14154 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14155 return;
14156 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14157 // Checking declaration inside declare target region.
14158 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14159 isa<FunctionTemplateDecl>(D)) {
14160 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14161 Context, OMPDeclareTargetDeclAttr::MT_To);
14162 D->addAttr(A);
14163 if (ASTMutationListener *ML = Context.getASTMutationListener())
14164 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14165 }
14166 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014167 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014168 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014169 if (!E)
14170 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014171 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14172}
Samuel Antao661c0902016-05-26 17:39:58 +000014173
14174OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014175 CXXScopeSpec &MapperIdScopeSpec,
14176 DeclarationNameInfo &MapperId,
14177 const OMPVarListLocTy &Locs,
14178 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014179 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014180 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14181 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014182 if (MVLI.ProcessedVarList.empty())
14183 return nullptr;
14184
Michael Kruse01f670d2019-02-22 22:29:42 +000014185 return OMPToClause::Create(
14186 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14187 MVLI.VarComponents, MVLI.UDMapperList,
14188 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014189}
Samuel Antaoec172c62016-05-26 17:49:04 +000014190
14191OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014192 CXXScopeSpec &MapperIdScopeSpec,
14193 DeclarationNameInfo &MapperId,
14194 const OMPVarListLocTy &Locs,
14195 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014196 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014197 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14198 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014199 if (MVLI.ProcessedVarList.empty())
14200 return nullptr;
14201
Michael Kruse0336c752019-02-25 20:34:15 +000014202 return OMPFromClause::Create(
14203 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14204 MVLI.VarComponents, MVLI.UDMapperList,
14205 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014206}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014207
14208OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014209 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014210 MappableVarListInfo MVLI(VarList);
14211 SmallVector<Expr *, 8> PrivateCopies;
14212 SmallVector<Expr *, 8> Inits;
14213
Alexey Bataeve3727102018-04-18 15:57:46 +000014214 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014215 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14216 SourceLocation ELoc;
14217 SourceRange ERange;
14218 Expr *SimpleRefExpr = RefExpr;
14219 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14220 if (Res.second) {
14221 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014222 MVLI.ProcessedVarList.push_back(RefExpr);
14223 PrivateCopies.push_back(nullptr);
14224 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014225 }
14226 ValueDecl *D = Res.first;
14227 if (!D)
14228 continue;
14229
14230 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014231 Type = Type.getNonReferenceType().getUnqualifiedType();
14232
14233 auto *VD = dyn_cast<VarDecl>(D);
14234
14235 // Item should be a pointer or reference to pointer.
14236 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014237 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14238 << 0 << RefExpr->getSourceRange();
14239 continue;
14240 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014241
14242 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014243 auto VDPrivate =
14244 buildVarDecl(*this, ELoc, Type, D->getName(),
14245 D->hasAttrs() ? &D->getAttrs() : nullptr,
14246 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014247 if (VDPrivate->isInvalidDecl())
14248 continue;
14249
14250 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014251 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014252 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14253
14254 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014255 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014256 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014257 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14258 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014259 AddInitializerToDecl(VDPrivate,
14260 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014261 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014262
14263 // If required, build a capture to implement the privatization initialized
14264 // with the current list item value.
14265 DeclRefExpr *Ref = nullptr;
14266 if (!VD)
14267 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14268 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14269 PrivateCopies.push_back(VDPrivateRefExpr);
14270 Inits.push_back(VDInitRefExpr);
14271
14272 // We need to add a data sharing attribute for this variable to make sure it
14273 // is correctly captured. A variable that shows up in a use_device_ptr has
14274 // similar properties of a first private variable.
14275 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14276
14277 // Create a mappable component for the list item. List items in this clause
14278 // only need a component.
14279 MVLI.VarBaseDeclarations.push_back(D);
14280 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14281 MVLI.VarComponents.back().push_back(
14282 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014283 }
14284
Samuel Antaocc10b852016-07-28 14:23:26 +000014285 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014286 return nullptr;
14287
Samuel Antaocc10b852016-07-28 14:23:26 +000014288 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014289 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14290 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014291}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014292
14293OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014294 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014295 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014296 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014297 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014298 SourceLocation ELoc;
14299 SourceRange ERange;
14300 Expr *SimpleRefExpr = RefExpr;
14301 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14302 if (Res.second) {
14303 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014304 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014305 }
14306 ValueDecl *D = Res.first;
14307 if (!D)
14308 continue;
14309
14310 QualType Type = D->getType();
14311 // item should be a pointer or array or reference to pointer or array
14312 if (!Type.getNonReferenceType()->isPointerType() &&
14313 !Type.getNonReferenceType()->isArrayType()) {
14314 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14315 << 0 << RefExpr->getSourceRange();
14316 continue;
14317 }
Samuel Antao6890b092016-07-28 14:25:09 +000014318
14319 // Check if the declaration in the clause does not show up in any data
14320 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014321 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014322 if (isOpenMPPrivate(DVar.CKind)) {
14323 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14324 << getOpenMPClauseName(DVar.CKind)
14325 << getOpenMPClauseName(OMPC_is_device_ptr)
14326 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014327 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014328 continue;
14329 }
14330
Alexey Bataeve3727102018-04-18 15:57:46 +000014331 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014332 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014333 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014334 [&ConflictExpr](
14335 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14336 OpenMPClauseKind) -> bool {
14337 ConflictExpr = R.front().getAssociatedExpression();
14338 return true;
14339 })) {
14340 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14341 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14342 << ConflictExpr->getSourceRange();
14343 continue;
14344 }
14345
14346 // Store the components in the stack so that they can be used to check
14347 // against other clauses later on.
14348 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14349 DSAStack->addMappableExpressionComponents(
14350 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14351
14352 // Record the expression we've just processed.
14353 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14354
14355 // Create a mappable component for the list item. List items in this clause
14356 // only need a component. We use a null declaration to signal fields in
14357 // 'this'.
14358 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14359 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14360 "Unexpected device pointer expression!");
14361 MVLI.VarBaseDeclarations.push_back(
14362 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14363 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14364 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014365 }
14366
Samuel Antao6890b092016-07-28 14:25:09 +000014367 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014368 return nullptr;
14369
Michael Kruse4304e9d2019-02-19 16:38:20 +000014370 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14371 MVLI.VarBaseDeclarations,
14372 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014373}